python wav文件写入
时间: 2023-08-27 10:20:52 浏览: 109
在Python中,有多种方法可以用来写入WAV文件。下面是两种常见的方法:
方法一:使用wave和numpy库
```python
import wave
import numpy as np
# 设置参数
framerate = 44100 # 取样频率
time = 10 # 录音时长(秒)
# 生成音频数据
t = np.arange(0, time, 1.0/framerate)
wave_data = np.sin(2*np.pi*1000*t) * 10000 # 这里以1000Hz的正弦波为例
# 打开WAV文件
with wave.open("output.wav", "wb") as f:
# 配置声道数、量化位数和取样频率
f.setnchannels(1) # 单声道
f.setsampwidth(2) # 量化位数为16位
f.setframerate(framerate)
# 将音频数据转换为二进制数据并写入文件
f.writeframes(wave_data.astype(np.short).tostring())
```
方法二:使用soundfile库
```python
import soundfile as sf
import numpy as np
# 生成音频数据
audio = np.sin(2*np.pi*1000*t) # 这里以1000Hz的正弦波为例
# 写入WAV文件
sf.write('output.wav', audio, framerate, 'PCM_24')
```
以上代码分别使用了wave和soundfile库来写入WAV文件,其中wave库使用了numpy库来生成音频数据,而soundfile库直接使用了numpy生成的音频数据。你可以根据自己的需求选择其中一种方法进行使用。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [使用python写Wave文件](https://blog.csdn.net/qq_39516859/article/details/79834039)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [【音频】python读取写入wav文件](https://blog.csdn.net/weixin_41932970/article/details/130713881)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文
相关推荐















