Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

python - How to play sound with Pyqt5 QtMultimedia?

def play_tts(self,file_path):
   file = open(file_path)
   mixer.init()
   mixer.music.load(file)
   mixer.music.play()
   while mixer.music.get_busy():
       time.sleep(0.03)
       if window.ttsIs:
           break
   mixer.stop()
   mixer.quit()
   file.close()
   remove(file_path)

How do I write the above code with QtMultimedia?

Can you give me a example?

question from:https://stackoverflow.com/questions/66066171/how-to-play-sound-with-qsound-in-pyqt5

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If the file is a .wav then just use QSound:

import os
import sys

from PyQt5 import QtCore, QtMultimedia

CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))


def main():
    filename = os.path.join(CURRENT_DIR, "beal.wav")

    app = QtCore.QCoreApplication(sys.argv)

    QtMultimedia.QSound.play(filename)


    # end in 5 seconds:
    QtCore.QTimer.singleShot(5 * 1000, app.quit)

    sys.exit(app.exec_())


if __name__ == "__main__":
    main()

If you want to play more formats then you should use QMediaPlayer:

import os
import sys

from PyQt5 import QtCore, QtMultimedia

CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))


def main():
    filename = os.path.join(CURRENT_DIR, "sound.mp3")

    app = QtCore.QCoreApplication(sys.argv)

    player = QtMultimedia.QMediaPlayer()

    def handle_state_changed(state):
        if state == QtMultimedia.QMediaPlayer.PlayingState:
            print("started")
        elif state == QtMultimedia.QMediaPlayer.StoppedState:
            print("finished")
            QtCore.QCoreApplication.quit()

    player.stateChanged.connect(handle_state_changed)

    url = QtCore.QUrl.fromLocalFile(filename)
    player.setMedia(QtMultimedia.QMediaContent(url))
    player.play()

    sys.exit(app.exec_())


if __name__ == "__main__":
    main()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...