如何使用pyqt5播放声音?

uxhixvfz  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(493)
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)

如何使用QT多媒体编写上述代码?
你能给我举个例子吗?

x0fgdtte

x0fgdtte1#

如果文件是.wav,则只需使用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()

如果要播放更多格式,则应使用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()

相关问题