这个简单的代码将有一个 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_())
有没有办法用代码指定它将播放到哪个音频设备输出?或者以某种方式设置播放器默认输出设备。
具体示例是拥有 2 个播放设备、扬声器和耳机。
假设扬声器是系统的默认输出设备,我怎样才能用耳机而不是扬声器播放?我需要能够用代码来改变它。
正如您在上面的代码中看到的,有一个组合框列出了所有输出设备。我希望当您单击时,根据您选择的组合框条目,它会在所选设备上播放。
- 更新 -
根据 Chiku1022 的回答,我设法做到了这一点:
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 可以。