QBuffer是一个 io 设备——一旦你读过它,你需要重置它的位置以便再次读取它。因此,在您的代码中,您将需要执行以下操作:
...
self._buffer = buf
self.mediaPlayer=QMediaPlayer(self)
self.mediaPlayer.setMedia(QMediaContent(), self._buffer)
def play(self):
self._buffer.seek(0)
self.mediaPlayer.play()
编辑:
经过一些实际测试,我发现只需要保留对缓冲区的引用即可重播音频。下面的脚本是一个适合我的完整示例(在 Linux 上,使用 GStreamer 后端):
import sys
from PyQt5 import QtCore, QtWidgets, QtMultimedia
class Window(QtWidgets.QWidget):
def __init__(self):
super(Window, self).__init__()
self.buttonOpen = QtWidgets.QPushButton('Open', self)
self.buttonOpen.clicked.connect(self.handleOpen)
self.buttonPlay = QtWidgets.QPushButton('Play', self)
self.buttonPlay.clicked.connect(self.handlePlay)
layout = QtWidgets.QHBoxLayout(self)
layout.addWidget(self.buttonOpen)
layout.addWidget(self.buttonPlay)
self.mediaPlayer = QtMultimedia.QMediaPlayer(self)
self._buffer = QtCore.QBuffer()
def handlePlay(self):
if self.buttonPlay.text() == 'Play':
self.buttonPlay.setText('Stop')
# self._buffer.seek(0)
self.mediaPlayer.play()
else:
self.buttonPlay.setText('Play')
self.mediaPlayer.stop()
def handleOpen(self):
path, ok = QtWidgets.QFileDialog.getOpenFileName(
self, filter='WAV Files (*.wav)')
if ok:
self._buffer.close()
with open(path, 'rb') as stream:
self._buffer.setData(stream.read())
if self._buffer.open(QtCore.QIODevice.ReadOnly):
self.mediaPlayer.setMedia(
QtMultimedia.QMediaContent(), self._buffer)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.setGeometry(600, 100, 200, 50)
window.show()
sys.exit(app.exec_())