[英]How can I play audio (playsound) in the background of a Python script?
[英]How can I play audio with playsound and type in an entry box at the same time in tkinter?
我想在play_audio
function 運行時在user_text
輸入框中輸入一些內容
我嘗試了以下代碼:
from tkinter import *
from playsound import playsound
root = Tk()
def play_audio():
playsound('audio.mp3')
play_audio_button = Button(root, text='Play audio', command=play_audio)
user_text = Entry(root)
play_audio_button.pack()
user_text.pack(padx=10, pady=10)
mainloop()
但它不會讓我在后台播放音頻時做任何事情。 它只允許我在音頻結束后打字。
我也嘗試在沒有 tkinter 的情況下做同樣的事情並且它有效:
def play_audio():
playsound('audio.mp3')
play_audio()
play_audio_input = input('Your text: \n')
它確實讓我在后台播放音頻時打字。
那么我怎樣才能讓它在 tkinter 中工作呢?
playsound
可以在后台運行聲音,如果你需要循環播放聲音或者不僅僅是運行單個聲音文件,你應該使用線程。
def play_audio():
playsound('audio.mp3', block=False)
如果你想循環播放你不需要多處理的聲音, threading模塊非常適合在后台運行任務,它將在另一個線程中運行音頻,讓主線程運行你的 GUI。
import threading
def play_audio():
while True:
playsound('audio.mp3')
play_audio_button = Button(root, text='Play audio', command=lambda: threading.Thread(play_audio).start())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.