尝试使用 QMediaPlayer 添加声音事件

Trying adding a sound event using QMediaPlayer

我使用 pyqt5 制作了一个小应用程序,我想播放 5 秒的 mp3。我读到如果我使用 Qt 工具就不需要使用单独的线程,所以我在这里。

为什么这行不通,是不是更重要?

from PyQt5 import QtCore, QtWidgets, QtMultimedia

player = QtMultimedia.QMediaPlayer()
sound = QtMultimedia.QMediaContent(QtCore.QUrl.fromLocalFile("c:/alarm.mp3"))
player.setMedia(sound)
player.setVolume(100)
player.play()

我是不是看错了文档?

http://doc.qt.io/qt-5/qmediaplayer.html

player = new QMediaPlayer;
connect(player, SIGNAL(positionChanged(qint64)), this,   
        SLOT(positionChanged(qint64)));
player->setMedia(QUrl::fromLocalFile("/Users/me/Music/coolsong.mp3"));
player->setVolume(50);
player->play();

您必须添加 QGuiApplication:

from PyQt5 import QtCore, QtWidgets, QtMultimedia, QtGui
import sys

app = QtGui.QGuiApplication(sys.argv)
player = QtMultimedia.QMediaPlayer()
sound = QtMultimedia.QMediaContent(QtCore.QUrl.fromLocalFile({your filename})
player.setMedia(sound)
player.setVolume(100)
player.play()
sys.exit(app.exec_())