This simple code will have a GUI button that, when pressed, will play example.mp3
to the default audio output device.
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_())
Is there a way to specify, with code, to which audio device output will it play? Or somehow set the player default output device.
Concrete example would be having 2 playback devices, speakers and headphones. Let's say speakers are default output device for the system, how could I play to headphones instead of speaker? I need to be able to change this with code.
As you can see in the above code there is a combobox that lists all output devices. I would like to when you click, based on which combobox entry you selected, it plays to that selected device.
--UPDATE--
Based on Chiku1022 answerI I managed to do this:
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)
The strings in combo_box_devices are just scv.availableOutputs()
Altho it was hinted setting QT_MULTIMEDIA_PREFERRED_PLUGINS to windowsmediafoundation does not work for me,leaving it to default DirectShow works.
Qt5+ How to set default audio device for QMediaPlayer
This the one your are searching for. Its in C++, so you need to think out the python way out from it. Its not that difficult. I'm currently not on my PC, else I would have written the python code here.
UPDATE
os.environ['QT_MULTIMEDIA_PREFERRED_PLUGINS'] = 'windowsmediafoundation'
Add the above line of code at the top of your code. This will help your media player to use the latest media API of windows instead of DirectShow, so QAudioDeviceInfo will work correctly.