我一直在寻找在python中播放mp3文件的解决方案,许多stackoverflow答案(对于其他问题)似乎推荐pyglet。我正在编写一个程序,它接受一段文字,将其分成单个单词,然后使用gTT下载这些单词的mp3(如果它们尚未下载)并播放它们。
from pyglet import media, app, clock
from gtts import gTTS
import os
import time
from num2words import num2words
cwd = os.getcwd()
beep = media.load('beep.mp3', streaming = False)
def get_mp3(text):
player = media.Player()
lowertext = text.lower()
words = lowertext.split()
player.queue(beep)
for word in words:
save_path = cwd + '\\tts_downloads\\{}.mp3'.format(word)
if os.path.isfile(save_path) == False:
tts = gTTS(word, 'en-us')
tts.save(save_path)
mp3 = media.load(save_path)
player.queue(mp3)
player.queue(beep)
player.play()
app.run()
但是我发现在播放文件之后pyglet不会让我的程序进展。如何在播放完成后退出pyglet应用程序,以便我的代码可以进展?
或者还有其他方法可以在python中播放mp3文件吗?
答案 0 :(得分:0)
这是因为app.run()
是一个永无止境的循环,以保持GL上下文的活跃。只有一种解决方法,那就是创建自己的继承Pyglet属性的类。
我会给你一个示例代码,如果您有任何问题,请随时提出。
import pyglet
from pyglet.gl import *
# Optional audio outputs (Linux examples):
# pyglet.options['audio'] = ('alsa', 'openal', 'silent')
key = pyglet.window.key
class main(pyglet.window.Window):
def __init__ (self):
super(main, self).__init__(800, 800, fullscreen = False)
self.x, self.y = 0, 0
self.bg = pyglet.sprite.Sprite(pyglet.image.load('background.jpg'))
self.sprites = {}
self.player = pyglet.media.Player()
self.alive = 1
def on_draw(self):
self.render()
def on_close(self):
self.alive = 0
def on_key_press(self, symbol, modifiers):
# Do something when a key is pressed?
# Pause the audio for instance?
# use `if symbol == key.SPACE: ...`
# This is just an example of how you could load the audio.
# You could also do a standard input() call and enter a string
# on the command line.
if symbol == key.ENTER:
self.player.queue(media.load('beep.mp3', streaming = False))
if nog self.player.playing:
self.player.play()
if symbol == key.ESC: # [ESC]
self.alive = 0
def render(self):
self.clear()
self.bg.draw()
# self.sprites is a dictionary where you store sprites
# to be rendered, if you have any.
for sprite_name, sprite in self.sprites.items():
sprite.draw()
self.flip()
def run(self):
while self.alive == 1:
self.render()
# -----------> This is key <----------
# This is what replaces pyglet.app.run()
# but is required for the GUI to not freeze
#
event = self.dispatch_events()
self.player.delete() # Free resources. (Not really needed but as an example)
x = main()
x.run()
现在这只是如何加载音频源并播放它们的最基本的例子。按 Enter 并触发beep.mp3
。
通常情况下,您还希望将某个功能挂钩到self.player.eos(),以便在耗尽资源时执行某些操作。
另请注意,如果它尚未播放,则只会调用play()
一次。这些是您想要尊重的属性。
啊和 Escape 退出应用程序。