[英]How to loop-play an audio with pyaudio?
我想使用Pyaudio和tkinter播放音频波形文件,其中按下按钮时播放音频,按下停止按钮时音频停止。 现在,音频是一个简单的5秒钟的波形文件,假定如此,音频将在5秒钟后停止。 我想知道如何循环播放,这样除非单击停止按钮,否则音频将一直持续播放。 我找不到这种代码的方法。
from tkinter import *
import pyaudio
import wave
import sys
import threading
# --- classes ---
def play_audio():
global is_playing
global my_thread
chunk = 1024
wf = wave.open('sound.wav', 'rb')
p = pyaudio.PyAudio()
stream = p.open(
format = p.get_format_from_width(wf.getsampwidth()),
channels = wf.getnchannels(),
rate = wf.getframerate(),
output = True)
data = wf.readframes(chunk)
while data != '' and is_playing: # is_playing to stop playing
stream.write(data)
data = wf.readframes(chunk)
stream.stop_stream()
stream.close()
p.terminate()
# --- functions ---
def press_button_play():
global is_playing
global my_thread
if not is_playing:
is_playing = True
my_thread = threading.Thread(target=play_audio)
my_thread.start()
def press_button_stop():
global is_playing
global my_thread
if is_playing:
is_playing = False
my_thread.join()
# --- main ---
is_playing = False
my_thread = None
root = Tk()
root.title("Compose-O-Matic")
root.geometry("400x300")
button_start = Button(root, text="PLAY", command=press_button_play)
button_start.grid()
button_stop = Button(root, text="STOP", command=press_button_stop)
button_stop.grid()
root.mainloop()
循环播放音频的一种方法是定义一个loop_play
函数,该函数将在循环中执行play_audio
并将此函数作为线程的目标传递:
def loop_play():
while is_playing:
play_audio()
def press_button_play():
global is_playing
global my_thread
if not is_playing:
is_playing = True
my_thread = threading.Thread(target=loop_play)
my_thread.start()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.