简体   繁体   English

如何在Python中播放MP3而没有无限循环?

[英]How to play mp3 in python without infinite loop?

I am writing a program which reads a string, then convert it into speech and play it as mp3. 我正在编写一个程序,该程序读取字符串,然后将其转换为语音并以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. 我已经检查并发现mp3文件已创建,可以用标准mp3播放器播放,但不能播放脚本。 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. 我正在使用gtts模块(用于将文本转换为语音)和vlc模块(用于播放mp3),代码如下所示。请注意,“ m”是我要转换为声音的文本。

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 我进一步发现当我在播放命令后提供无限循环时,mp3会播放。

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. 有什么办法可以避免无限循环,我已经将所有必需的模块导入到项目中了。

What you are doing is starting a subprocess with the vlc lib, when your program closes, it closes the subprocess. 您正在执行的操作是使用vlc lib启动子进程,当程序关闭时,它会关闭子进程。 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. 但是,存在一种用于找到媒体长度的解决方案 ,因此可以根据代码设置睡眠时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM