Python PyQT5 Play WAV File: A Completed Guide – PyQT Tutorial

By | April 12, 2020

Python pyqt5 library can allow us to play wav file, there are some methods can play. In this tutorial, we will use some examples to tell you how to do.

Install pyqt5 in python

To play wav file using pyqt5, you should intall it first. You can install it using anaconda.

Anaconda Install PyQT: A Completed Guide

Then we can use pyqt to play wav file

Import libraries

You should import some python libraries

import sys
from PyQt5.QtWidgets import QMainWindow,QApplication
from PyQt5 import QtCore, QtMultimedia

We will play a wav file Alarm06.wav as an example.

Method 1: Use QtMultimedia.QMediaPlayer to play wav file

Here is an example code.

if __name__ == '__main__':
    app = QApplication(sys.argv)
    url = QtCore.QUrl.fromLocalFile("Alarm06.wav")
    content = QtMultimedia.QMediaContent(url)
    player = QtMultimedia.QMediaPlayer()

Method 2: Use QtMultimedia.QSound to play wav file

Here is an example.

if __name__ == '__main__':
    app = QApplication(sys.argv)
    sound_file = 'Alarm06.wav'
    sound = QtMultimedia.QSound(sound_file)

Method 3: Use tMultimedia.QSoundEffect to play wav file

This method is much better than method 2, whicn provides more operations on wav file.

if __name__ == '__main__':
    app = QApplication(sys.argv)
    sound_file = 'Alarm06.wav'
    sound = QtMultimedia.QSoundEffect()

As to us, Method 3 is the best in all three methods, you can apply more control to the wav when playing.

Leave a Reply

Your email address will not be published. Required fields are marked *