我正在尝试在 Pyglet 中构建一个简单的媒体工具,它需要一个搜索功能。文件被加载、暂停,然后被告知在特定时间寻找;但是,当调用 Player.seek() 时,文件不会查找。下面是我使用的测试代码:
import os
import pyglet
from os.path import abspath, isfile
def loadsong(filename):
# check for file
print("Attempting to load "+filename)
filename = abspath(filename)
if not ( isfile(filename) ):
raise Exception(filename+" not found.")
# create a player for this file
song = pyglet.media.load(filename)
source = song.play()
source.eos_action = source.EOS_LOOP
source.pause()
return source
music = loadsong("test.mp3")
music.seek(57)
music.play()
pyglet.app.run()
我在这里做错了什么?我正在使用 Python 3.5.2、Pyglet 1.2 alpha 1 和 AVBin 11 alpha 4。
请您参考如下方法:
首先,您遇到的错误非常重要。
但我假设这是行上的 Segmentation fault (core dumped):
music.seek(12)
另一个快速说明,修正你的缩进!您正在使用 3 个空格,无论您是空格专家还是标签专家 - 3 个空格只是奇数 -
您在尝试搜索时遇到段错误的原因很可能是因为 AVbin,它是一个旧的(和死的 afaik)项目。
我组装了一些更类似于音乐播放器的东西,下面是一个关于如何使用 Seek 处理 wav 文件的示例:
import pyglet
from pyglet.gl import *
from os.path import abspath, isfile
pyglet.options['audio'] = ('pulseaudio', 'alsa', 'openal', 'silent')
pyglet.have_avbin=False
key = pyglet.window.key
def loadsong(filename):
# check for file
filename = abspath(filename)
# create a player for this file
player = pyglet.media.Player()
player.queue(pyglet.media.load(filename, streaming=False))
#player.play()
#song.eos_action = song.EOS_LOOP
#song.pause()
return player
class main(pyglet.window.Window):
def __init__ (self):
super(main, self).__init__(300, 300, fullscreen = False)
self.alive = 1
self.player = loadsong('./test.wav')
def on_draw(self):
self.render()
def on_close(self):
self.alive = 0
def on_key_press(self, symbol, modifiers):
if symbol == key.ESCAPE: # [ESC]
self.alive = 0
elif symbol == key.SPACE:
if self.player.playing:
self.player.pause()
else:
self.player.play()
elif symbol == key.RIGHT:
print('Skipping to:',self.player.time+2)
self.player.source.seek(self.player.time+2)
elif symbol == key.LEFT:
print('Rewinding to:',self.player.time-2)
self.player.source.seek(self.player.time-2)
def render(self):
self.clear()
#source = pyglet.text.Label(str(self.player.source.info.title.decode('UTF-8')), x=20, y=300-30)
volume = pyglet.text.Label(str(self.player.volume*100)+'% volume', x=20, y=40)
p_time = pyglet.text.Label(str(self.player.time), x=20, y=20)
#source.draw()
volume.draw()
p_time.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()
x = main()
x.run()
一些重要的注意事项:
pyglet.have_avbin=False
这将完全关闭 AVbin,可能有一种方法可以针对个别来源将其关闭。但由于我很少使用它,所以老实说我不知道该怎么做。所以关闭它:)
其次:
streaming=False
media.load() 调用非常重要,否则您的声音中可能会出现奇怪的伪像,或者根本没有声音。例如,我听到了一种超高音调的抓取声,如果没有那面旗帜,这几乎让我失聪。
除此之外,代码非常简单。
self.player.source.seek(<time>)
在作为 pyglet.media.Player() 实例的播放器对象上调用。而且效果非常好。
另一种解决方法是手动安装 AVbin 7这似乎工作得更好,但我不愿意将它安装在这台机器上只是为了测试目的。但是我多年来收集的总体信息是那个旧库更好地工作Mp3 文件。
