0

I am writing a program which reads a string, then convert it into speech and play it as mp3. But the program does not play the music. I have checked and find out that the mp3 file is created and can be played with standard mp3 players but not the script. I am using gtts module (for converting text to speech) and vlc module (to play mp3) The code is like this.Please note that 'm' is the text I want to convert to sound.

tts = gTTS(text=m, lang='en')
tts.save("greeting.mp3")
p = vlc.MediaPlayer("greeting.mp3")
p.play()

I have further found out that the mp3 plays when I provide an infinite loop after play command.Like this

tts = gTTS(text=m, lang='en')
tts.save("greeting.mp3")
p = vlc.MediaPlayer("greeting.mp3")
p.play()
while True:
    pass

Is there any way I can avoid that Infinite loop.I have already imported all the required modules to the project.

AMAL JOY
  • 3
  • 3
  • 1
    is `p.play()` the last statement in your program? If so, the problem might be that program terminates before it has a chance to play the mp3 – Sweeney Todd Nov 06 '16 at 17:31
  • yes i too think so... How can we fix it? – AMAL JOY Nov 06 '16 at 17:34
  • I don't know much about the vlc module you are using but It seems to have a `is_playing()` method. So, you can replace `while True:` with `while p.is_playing()` and probably replace the `pass` with a `sleep` function to avoid busy waiting – Sweeney Todd Nov 06 '16 at 17:38
  • I guess there is also a `get_length()` method which returns the length in ms . You can also use it like `time.sleep( p.get_length()/1000.)` – Sweeney Todd Nov 06 '16 at 17:46

1 Answers1

0

What you are doing is starting a subprocess with the vlc lib, when your program closes, it closes the subprocess. So the quickest solution (without learning how to properly handle processes) is to set sleep timer:

import time

tts = gTTS(text=m, lang='en')
tts.save("greeting.mp3")
p = vlc.MediaPlayer("greeting.mp3")
p.play()
time.sleep(120) # number of seconds in

However, there is this solution for finding the length of media so the sleep period can be set from code.

Community
  • 1
  • 1
dgmt
  • 485
  • 1
  • 3
  • 13