昨天用PyQt5的QtMultimedia模块播放音乐时,单独使用可播放,放代码里结合使用死的播放不了。以下是测试demo可播放代码:
# -*- coding: utf-8 -*- # Nola from PyQt5 import QtWidgets, QtCore, QtMultimedia import sys app = QtWidgets.QApplication(sys.argv) url = QtCore.QUrl.fromLocalFile(r"D:projectpyqt5_tutorialUmusicmusic_datasWalk Off the Earth、Jocelyn Alice、Krnfx - Havana.mp3") content = QtMultimedia.QMediaContent(url) player = QtMultimedia.QMediaPlayer() player.setMedia(content) player.setVolume(50.0) player.play() sys.exit(app.exec())
# -*- coding: utf-8 -*- # Nola from PyQt5 import QtWidgets, QtMultimedia from PyQt5.QtCore import QUrl import sys class MainUi(QtWidgets.QMainWindow): def __init__(self): super().__init__() self.init_ui() def init_ui(self): button1 = QtWidgets.QPushButton("button1",self) url = QUrl.fromLocalFile(r"D:projectpyqt5_tutorialUmusicmusic_datas出逃 - 罗之豪.mp3") content = QtMultimedia.QMediaContent(url) self.player = QtMultimedia.QMediaPlayer() self.player.setMedia(content) button1.clicked.connect(self.playmusic) def playmusic(self): self.player.play() def main(): app = QtWidgets.QApplication(sys.argv) gui = MainUi() gui.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
看似简单的几行代码,放到代码里后,打印QtMultimedia.QMediaPlayer.MediaStatus() 输出一直是0--> UnknownMediaStatus,未知的状态。
在github上找到一位大神用PyQt5仿了网易云音乐,看他的代码是另外创建个播放器类继承QMediaPlayer:
创建个单独的Player类,两个方法play_music和pause_music,放代码里调用还是无法播放,在play处try没有任何报错,调试也没找到错误,最怕的就是什么都不输出。。。
今早,仔细看了下以上两个可运行的demo,QMediaPlayer的实例化应该在setupUi初始化后,完美有声音了,play和pause正常运行。代码如下:
class MyPlayer(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self): super(MyPlayer, self).__init__() self.setupUi(self) self.setWindowTitle("Umusic") self.setWindowIcon(QIcon("MusicCloud.ico")) self.played = QtMultimedia.QMediaPlayer() self.played.setVolume(50.0) ...