weixin_37871547
weixin_37871547
采纳率0%
2018-12-28 22:23 阅读 2.0k

pyqt5 mediaplayer播放音乐没声音,哪里错了?

5

按下按钮,没有报错,但是没有声音

from PyQt5 import QtCore, QtGui, QtWidgets, QtMultimedia
from PyQt5.QtCore import QUrl, Qt
from PyQt5.QtWidgets import QGridLayout
import sys


class MainUi(QtWidgets.QMainWindow):

    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        button1 = QtWidgets.QPushButton("button1",self)
        button1.clicked.connect(self.playmusic)


    def playmusic(self):
        url = QUrl.fromLocalFile(r"D:\four\CS003\project\music\Stay.mp3")
        content = QtMultimedia.QMediaContent(url)
        player = QtMultimedia.QMediaPlayer()
        player.setMedia(content)
        player.setVolume(100)
        player.play()


def main():
    app = QtWidgets.QApplication(sys.argv)
    gui = MainUi()
    gui.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

3条回答 默认 最新

  • weixin_39416561 lyhsdy 2018-12-31 02:37

    ←如果以下回答对你有帮助,请点击右边的向上箭头及采纳下答案

    from PyQt5 import QtCore, QtGui, QtWidgets, QtMultimedia
    from PyQt5.QtCore import QUrl, Qt
    from PyQt5.QtWidgets import QGridLayout
    import sys
    
    
    class MainUi(QtWidgets.QMainWindow):
    
        def __init__(self):
            super().__init__()
            self.init_ui()
    
        def init_ui(self):
            button1 = QtWidgets.QPushButton("button1",self)
            button1.clicked.connect(self.playmusic)
            url = QUrl.fromLocalFile(r"D:\four\CS003\project\music\Stay.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()
    
    
    点赞 1 评论 复制链接分享
  • devmiao devmiao 2018-12-28 15:56
  • weixin_44528542 weixin_44528542 2021-02-24 21:18

    只要改动你代码中的这行就行了,player = QtMultimedia.QMediaPlayer(self),你少个self

    或者你把player作为实例的对象,前面加self, 像2楼一样改。

    点赞 评论 复制链接分享

相关推荐