If the file is a .wav then just use QSound:
import os
import sys
from PyQt5 import QtCore, QtMultimedia
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
def main():
filename = os.path.join(CURRENT_DIR, "beal.wav")
app = QtCore.QCoreApplication(sys.argv)
QtMultimedia.QSound.play(filename)
# end in 5 seconds:
QtCore.QTimer.singleShot(5 * 1000, app.quit)
sys.exit(app.exec_())
if __name__ == "__main__":
main()
If you want to play more formats then you should use QMediaPlayer:
import os
import sys
from PyQt5 import QtCore, QtMultimedia
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
def main():
filename = os.path.join(CURRENT_DIR, "sound.mp3")
app = QtCore.QCoreApplication(sys.argv)
player = QtMultimedia.QMediaPlayer()
def handle_state_changed(state):
if state == QtMultimedia.QMediaPlayer.PlayingState:
print("started")
elif state == QtMultimedia.QMediaPlayer.StoppedState:
print("finished")
QtCore.QCoreApplication.quit()
player.stateChanged.connect(handle_state_changed)
url = QtCore.QUrl.fromLocalFile(filename)
player.setMedia(QtMultimedia.QMediaContent(url))
player.play()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
Improve your knowledge in data science from scratch using Data science online courses