如何使用pyaudio循环播放音频?

编程入门 行业动态 更新时间:2024-10-27 05:28:09
本文介绍了如何使用pyaudio循环播放音频?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想使用Pyaudio和tkinter播放音频波形文件,其中按下按钮时播放音频,按下停止按钮时音频停止.现在,音频是一个简单的5秒波形文件,假设如此,音频将在5秒后停止.我想知道如何循环播放,这样除非单击停止按钮,否则音频将一直持续播放.我找不到这种代码的方法.

I want to play an audio wave file using Pyaudio and tkinter where the audio plays when the button is pressed and the audio stops when the stop button is pressed. Now, the audio is a simple 5 secs wave file, as it is suppose to, the audio stops after 5 secs. I would like to know how to loop it, such that the audio keeps on playing forever unless the stop button is clicked. I cannot find a way with this code.

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并将该函数作为线程的目标传递:

A way to loop-play the audio is to define a function loop_play that will execute play_audio in loop and pass this function as target of the thread:

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()

更多推荐

如何使用pyaudio循环播放音频?

本文发布于:2023-07-11 12:00:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1093979.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   音频   pyaudio

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!