I have the following function to convert text to speech:
from gtts import gTTS
import vlc, time
def say(text, language = 'en'):
speech = gTTS(text = text, lang = language, slow = False)
mp3_file = 'text.mp3'
speech.save(mp3_file)
p = vlc.MediaPlayer(mp3_file)
p.play()
But when I give it some text to convert into audio and play it back, it converts the text to audio just fine, but when playing it back it clips off the beginning and end. In the following example:
say('Hello and Welcome to this session!')
it only plays/pronounces the "welcome to" part. I know that the text is getting converted to audio just fine because when I double click on the generated mp3 file text.mp3, it plays just fine, from beginning to end without any sort of clipping in both Groove Music Player and Windows Media Player.
I found this question where the same problem is being encountered; I followed the suggestion and included a time.sleep(2) before, and after too, just in case, the p.play() in the function:
time.sleep(2)
p.play()
time.sleep(2)
But the result is the same, it clips off the beginning and ending parts of the audio file. How do I fix it?
EDIT: I mentioned above that the generated mp3 file text.mp3 plays just fine from beginning to end without any sort of clipping in both Groove Music Player and Windows Media Player. However, when I manually open the file with VLC Media Player, I found that it too clips off some portion at the beginning and end! The portion clipped off when manually opening the file in VLC Media Player is a bit lesser though, than when playing the file with the vlc library in Python (i.e., using p.play() in the function above). Like, in the example text above, when I right click on the text.mp3 file and open with VLC Media Player, I can hear "lo and welcome to". So I guess there is something wrong with VLC itself. So, is there some other Python library that I can use to play the audio flawlessly?