用python编写播放切割wav音频且带有开始暂停按钮和时间进度条的代码
时间: 2024-04-29 17:25:14 浏览: 94
好的,以下是可以回答的内容:
您可以使用Python中的PyAudio库来播放和切割WAV音频文件。以下是一个示例代码:
```
import pyaudio
import wave
import threading
import time
import tkinter as tk
from tkinter import ttk
class AudioPlayer:
def __init__(self, filename):
self.filename = filename
self.wf = wave.open(self.filename, 'rb')
self.p = pyaudio.PyAudio()
self.stream = self.p.open(
format=self.p.get_format_from_width(self.wf.getsampwidth()),
channels=self.wf.getnchannels(),
rate=self.wf.getframerate(),
output=True
)
self.playing = False
self.paused = False
self.frames = []
self.current_frame = 0
self.duration = self.wf.getnframes() / self.wf.getframerate()
self.time_var = tk.StringVar()
self.time_var.set("00:00 / {}".format(self.format_time(self.duration)))
self.create_gui()
def create_gui(self):
self.root = tk.Tk()
self.root.title("Audio Player")
self.root.geometry('400x100')
self.play_button = ttk.Button(self.root, text='Play', command=self.play)
self.pause_button = ttk.Button(self.root, text='Pause', command=self.pause)
self.progress_bar = ttk.Progressbar(self.root, orient='horizontal', mode='determinate', maximum=self.duration)
self.time_label = ttk.Label(self.root, textvariable=self.time_var)
self.play_button.pack(side='left', padx=5, pady=5)
self.pause_button.pack(side='left', padx=5, pady=5)
self.progress_bar.pack(side='left', fill='x', padx=5, pady=5)
self.time_label.pack(side='left', padx=5, pady=5)
def play(self):
if not self.playing:
if self.paused:
self.stream.start_stream()
self.paused = False
else:
self.frames = self.wf.readframes(1024)
self.stream.start_stream()
self.playing = True
self.current_frame = 0
threading.Thread(target=self.update_progress).start()
def pause(self):
if self.playing:
self.stream.stop_stream()
self.paused = True
def update_progress(self):
while self.playing and self.current_frame < self.duration:
time.sleep(1)
self.current_frame += 1
self.progress_bar['value'] = self.current_frame
self.time_var.set("{} / {}".format(self.format_time(self.current_frame), self.format_time(self.duration)))
self.playing = False
def format_time(self, seconds):
minutes = int(seconds // 60)
seconds = int(seconds % 60)
return "{:02d}:{:02d}".format(minutes, seconds)
def run(self):
self.root.mainloop()
def cleanup(self):
self.stream.stop_stream()
self.stream.close()
self.p.terminate()
self.wf.close()
if __name__ == '__main__':
player = AudioPlayer('audio.wav')
player.run()
player.cleanup()
```
这个代码使用了PyAudio库来播放WAV音频文件,并使用了Tkinter模块来创建GUI界面。您可以在GUI界面上看到一个播放按钮、一个暂停按钮和一个时间进度条。
希望这个代码能帮到您。
阅读全文