这个简单的代码将有一个GUI按钮,当按下该按钮时,将播放example.mp3
到默认的音频输出设备。
import sys
from PyQt5 import QtCore, QtMultimedia
from PyQt5.QtMultimedia import QAudio, QAudioDeviceInfo
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QComboBox
class SimplePlay(QWidget):
def __init__(self):
super().__init__()
self.player = QtMultimedia.QMediaPlayer()
url = QtCore.QUrl.fromLocalFile(QtCore.QDir.current().absoluteFilePath("example.mp3"))
self.sound_file = QtMultimedia.QMediaContent(url)
button = QPushButton("Play", self)
button.clicked.connect(self.on_click)
self.combo_box_devices = QComboBox(self)
self.combo_box_devices.setGeometry(0, 50, 300, 50)
for device in QAudioDeviceInfo.availableDevices(QAudio.AudioOutput):
self.combo_box_devices.addItem(device.deviceName())
self.show()
def on_click(self):
self.player.setMedia(self.sound_file)
self.player.play()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = SimplePlay()
sys.exit(app.exec_())
是否有一种方法,用代码来指定它将播放到哪个音频设备输出?或以某种方式设置播放机默认输出设备。
具体的例子是有两个回放设备,扬声器和耳机。假设扬声器是系统的默认输出设备,我怎么能播放耳机而不是扬声器呢?我需要能够用代码来改变这一点。
正如您在上面的代码中所看到的,有一个组合框列出了所有的输出设备。我想当您单击,根据您选择的组合框条目,它播放到选定的设备。
--更新--
基于Chiku1022 answerI,我成功地做到了这一点:
scv: QtMultimedia.QMediaService = self.player.service()
out: QtMultimedia.QAudioOutputSelectorControl = scv.requestControl("org.qt-project.qt.audiooutputselectorcontrol/5.0")
out.setActiveOutput(self.combo_box_devices.currentText())
scv.releaseControl(out)
scv = self.player.service()
out = scv.requestControl("org.qt-project.qt.audiooutputselectorcontrol/5.0")
out.setActiveOutput(self.combo_box_devices.currentText())
scv.releaseControl(out)
combo_box_devices中的字符串只是scv.availableOutputs()
尽管有人暗示将QT_MULTIMEDIA_PREFERRED_PLUGINS设置为windowsmediafoundation对我不起作用,但将其留给默认的DirectShow工作。
发布于 2021-01-04 16:48:18
Qt5+ How to set default audio device for QMediaPlayer
这是你要找的。它在C++中,所以您需要想出摆脱它的python的方法。没那么难。我现在不在我的电脑上,否则我会在这里写python代码。
更新
os.environ['QT_MULTIMEDIA_PREFERRED_PLUGINS'] = 'windowsmediafoundation'
在代码的顶部添加上面的代码行。这将帮助您的媒体播放器使用最新的windows媒体API而不是DirectShow,因此QAudioDeviceInfo将正确工作。
https://stackoverflow.com/questions/65566249
复制相似问题