pythonpyqtpyqt5qtmultimediaqurl

Playing Audio with QtMultimedia?


Part of a PyQt5 program I'm writing is to take in an audio stream and play it back. I've searched around and this is the code I have found that is said to work:

url = QtCore.QUrl.fromLocalFile('office theme.mp3')
content = QtMultimedia.QMediaContent(url)
player = QtMultimedia.QMediaPlayer()
player.setMedia(content)
player.play()

However, this does not work for me. I have tried putting the code in a variety of places (after the window.show() call, inside and outside of various classes I have, etc). I can verify that the MP3 is valid as I can play it in Clementine, VLC, and Dolphin. It was also taken directly from my Plex server, so it's definitely a valid MP3 file. I have tried converting this file to OGG and to WAV with no luck. I have also tried FLAC and AAC audio files and they do not work either.

I saw on a forum that someone suggested running a command to check if PyQt could see any audio devices. I ran the following code and it returned multiple audio output devices:

print(QtMultimedia.QAudioDeviceInfo.availableDevices(QtMultimedia.QAudio.AudioOutput))

All I need to do is take in a reference to an audio file (eventually opened from a file dialogue, but I'll cross that bridge when I come to it) and play it. Am I doing it incorrectly? I am by no means an expert on PyQt and have been experimenting for a couple of days only.

I'm currently running on Antergos Arch Linux.


Solution

  • You have to pass the complete path, but if you want to just pass the name of the file and that the program adds the rest you can use QDir::current():

    import sys
    
    from PyQt5 import QtCore, QtWidgets, QtMultimedia
    
    if __name__ == '__main__':
        app = QtWidgets.QApplication(sys.argv)
        filename = 'office theme.mp3'
        fullpath = QtCore.QDir.current().absoluteFilePath(filename) 
        url = QtCore.QUrl.fromLocalFile(fullpath)
        content = QtMultimedia.QMediaContent(url)
        player = QtMultimedia.QMediaPlayer()
        player.setMedia(content)
        player.play()
        sys.exit(app.exec_())