import tkinter as tk
from tkinter import filedialog
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import wavfile
# 设置初始阈值
threshold_value = 0.5
def is_discrete_interval(segment_data, threshold):
return np.max(segment_data) - np.min(segment_data) >= threshold
def analyze_audio():
audio_file = filedialog.askopenfilename(title='选择音频文件', filetypes=[('WAV Files', '*.wav')])
if audio_file:
sample_rate, data = wavfile.read(audio_file)
total_duration = len(data) / sample_rate
segment_duration = 30 # 分段时长为30秒
num_segments = int(np.ceil(total_duration / segment_duration))
for i in range(num_segments):
start_time = i * segment_duration
end_time = min((i + 1) * segment_duration, total_duration) # 最后一段按实际长度来计算
start_index = int(start_time * sample_rate)
end_index = int(end_time * sample_rate)
segment_data = data[start_index:end_index].astype(np.float32)
print(f"第 {i+1} 段的阈值为: {threshold_value}")
plt.figure(figsize=(8, 4))
plt.plot(np.arange(start_time, end_time, 1/sample_rate), segment_data, color='blue')
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.title(f'Segment {i+1}')
# 计算离散区间的阈值
threshold = threshold_value * (np.max(segment_data) - np.min(segment_data))
non_sine_indices = np.where(~is_discrete_interval(segment_data, threshold))[0]
if len(non_sine_indices) > 0:
print(f"第 {i+1} 段的离散区间索引值范围:{non_sine_indices}")
print(f"第 {i+1} 段的离散区间时间范围:{(start_time, end_time)}")
plt.tight_layout()
plt.show()
def set_threshold():
global threshold_value
threshold_value = float(threshold_entry.get())
analyze_audio() # 设置阈值后立即重新分析音频
root = tk.Tk()
root.title("音频分析")
root.geometry("400x300")
threshold_label = tk.Label(root, text="离散区间幅度阈值:")
threshold_label.pack()
threshold_entry = tk.Entry(root)
threshold_entry.pack()
threshold_button = tk.Button(root, text="设置阈值", command=set_threshold)
threshold_button.pack()
file_button = tk.Button(root, text="选择音频文件", command=analyze_audio)
file_button.pack()
root.mainloop()