帮我用python写一个截取wav音频文件片段的程序
时间: 2023-03-24 08:00:31 浏览: 79
好的,以下是使用 Python 编写一个截取 WAV 音频文件片段的程序:
```python
import wave
# 打开音频文件
with wave.open("audio.wav", "rb") as wave_file:
# 获取音频文件的参数
num_channels = wave_file.getnchannels() # 声道数
sample_width = wave_file.getsampwidth() # 采样宽度(字节数)
frame_rate = wave_file.getframerate() # 采样率
num_frames = wave_file.getnframes() # 总帧数
duration = num_frames / frame_rate # 总时长(秒)
# 输出音频文件的参数
print("声道数:", num_channels)
print("采样宽度:", sample_width)
print("采样率:", frame_rate)
print("总帧数:", num_frames)
print("总时长:", duration, "秒")
# 设置截取音频的起始和结束时间
start_time = 10 # 起始时间为第 10 秒
end_time = 20 # 结束时间为第 20 秒
# 计算截取音频的起始和结束帧数
start_frame = int(start_time * frame_rate)
end_frame = int(end_time * frame_rate)
# 将文件指针移动到起始帧
wave_file.setpos(start_frame)
# 读取指定帧数的音频数据
frames = wave_file.readframes(end_frame - start_frame)
# 保存截取后的音频数据为新的 WAV 文件
with wave.open("output.wav", "wb") as output_file:
# 设置输出文件的参数与输入文件相同
output_file.setnchannels(num_channels)
output_file.setsampwidth(sample_width)
output_file.setframerate(frame_rate)
# 写入截取后的音频数据
output_file.writeframes(frames)
print("截取完成!")
```
使用该程序时,需要将 `audio.wav` 替换为要截取的音频文件的文件名,`start_time` 和 `end_time` 分别为要截取的起始和结束时间(以秒为单位),最后程序将截取后的音频数据保存为 `output.wav` 文件。