本文介紹了如何使用 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)
如何用 QtMultimedia 編寫上述代碼?
How do I write the above code with QtMultimedia?
你能舉個例子嗎?
推薦答案
如果文件是 .wav 則只需使用 QSound:
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()
如果你想播放更多格式,那么你應該使用 QMediaPlayer:
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()
這篇關于如何使用 Pyqt5 QtMultimedia 播放聲音?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!