尝试使用QMediaPlayer

时间:2017-03-16 22:31:46

标签: python qt pyqt pyqt5 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();

1 个答案:

答案 0 :(得分:1)

您必须添加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_())