PyQt5之QtMultimedia模塊音樂播放沒聲音已解決

  昨天用PyQt5的QtMultimedia模塊播放音樂時,單獨使用可播放,放代碼裏結合使用死的播放不了。如下是測試demo可播放代碼:git

# -*- coding: utf-8 -*-
# Nola
from PyQt5 import QtWidgets, QtCore, QtMultimedia
import sys

app = QtWidgets.QApplication(sys.argv)
url = QtCore.QUrl.fromLocalFile(r"D:\project\pyqt5_tutorial\Umusic\music_datas\Walk 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:\project\pyqt5_tutorial\Umusic\music_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

  在github上找到一位大神用PyQt5仿了網易雲音樂,看他的代碼是另外建立個播放器類繼承QMediaPlayer:app

  建立個單獨的Player類,兩個方法play_music和pause_music,放代碼裏調用仍是沒法播放,在play處try沒有任何報錯,調試也沒找到錯誤,最怕的就是什麼都不輸出。。。測試

  今早,仔細看了下以上兩個可運行的demo,QMediaPlayer的實例化應該在setupUi初始化後,完美有聲音了,play和pause正常運行。代碼以下:ui

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)
        ...
相關文章
相關標籤/搜索