QtMultimedia MP3 audio playback

2019-07-25 14:52发布

问题:

I want to play an audio (MP3) file when the QmainWindow opens and have used the script from here. This is what my code looks like:

app = QApplication(sys.argv)

window = MainWindow()
window.show()

url = QUrl.fromLocalFile("./sound2.mp3")
content = QMediaContent(url)
player = QMediaPlayer()
player.setMedia(content)
player.play()

player.stateChanged.connect(app.quit)

app.exec_()

There is no problem running the script except that when I close the app the MP3 sound file continues to play when it should in fact stop. How do I modify the code? Thanks in advance.