我想在我的软件上播放一个mp3文件时,按下了一个按钮。我是这样做的:
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), playsong)
和功能:
def playsong():
m_media = Phonon.MediaObject()
m_media.setCurrentSource(Phonon.MediaSource("files/song.mp3"))
m_media.play()
这不会引发任何错误。但是这首歌不会播放。我看过很多c++的例子,还有一些python的例子,里面有很多歌曲和播放列表等等。我只想播放一首单曲,我错过什么了吗?
我在pyqt上使用phonon,我的代码有几行:
output = Phonon.AudioOutput(Phonon.MusicCategory)
m_media = Phonon.MediaObject()
Phonon.createPath(m_media, output)
m_media.setCurrentSource(Phonon.MediaSource("files/song.mp3"))
m_media.play()
但老实说,我发现phonon不能播放一些带有奇怪ID3标签的特定歌曲,所以我切换到pyaudiere (https://pypi.python.org/pypi/pyaudiere),它更稳定(但是是的,它与Qt的集成较少)。
下面是一个简单的音乐播放器示例:
from PyQt4 import QtGui, QtCore
from PyQt4.phonon import Phonon
class Window(QtGui.QPushButton):
def __init__(self):
QtGui.QPushButton.__init__(self, 'Choose File')
self.mediaObject = Phonon.MediaObject(self)
self.audioOutput = Phonon.AudioOutput(Phonon.MusicCategory, self)
Phonon.createPath(self.mediaObject, self.audioOutput)
self.mediaObject.stateChanged.connect(self.handleStateChanged)
self.clicked.connect(self.handleButton)
def handleButton(self):
if self.mediaObject.state() == Phonon.PlayingState:
self.mediaObject.stop()
else:
path = QtGui.QFileDialog.getOpenFileName(self, self.text())
if path:
self.mediaObject.setCurrentSource(Phonon.MediaSource(path))
self.mediaObject.play()
def handleStateChanged(self, newstate, oldstate):
if newstate == Phonon.PlayingState:
self.setText('Stop')
elif newstate == Phonon.StoppedState:
self.setText('Choose File')
elif newstate == Phonon.ErrorState:
source = self.mediaObject.currentSource().fileName()
print 'ERROR: could not play:', source.toLocal8Bit().data()
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
app.setApplicationName('Phonon')
win = Window()
win.resize(200, 100)
win.show()
sys.exit(app.exec_())