python 音频设备操作
21 April 2018
写数据到Wave文件
wave 接口文档: https://docs.python.org/3/library/wave.html
%matplotlib notebook
import wave
import numpy as np
import scipy.signal as signal
# 采样率
sample_rate = 8000
# 生成 10s 的声音文件
time = 10
# 生成采样点对应的时间序列
w_time = np.arange(0, time, 1.0/sample_rate)
# 生成 100Hz 到 1000Hz 的鸟声(Chirp)信号
w_data = signal.chirp(w_time, 100, time, 1000, method='linear') * 10000
w_data = w_data.astype(np.short)
# 把数据写到 wave 文件中,可以使用 audacity 软件查看
with wave.open('sweep.wav', 'wb') as f:
f.setnchannels(1)
f.setsampwidth(2)
f.setframerate(sample_rate)
f.writeframes(w_data)
从Wave文件读数据并播放
pyaudio 项目地址: https://github.com/jleb/pyaudio
pyaudio 接口文档: http://people.csail.mit.edu/hubert/pyaudio/
import wave
import numpy as np
import pyaudio
chunk = 1024
# 从文件中读出音频参数及数据
with wave.open('sweep.wav', 'rb') as f:
params = f.getparams()
nchannels, sample_width, sample_rate, nframes = params[0:4]
# 打开声卡设备
pdev = pyaudio.PyAudio()
stream = pdev.open(format = pdev.get_format_from_width(sample_width),
channels = nchannels,
rate = sample_rate,
output = True)
# 读出数据并写到声卡
while True:
data = f.readframes(chunk)
# 将数据转换为数组
# r_data = np.fromstring(data, dtype=np.short)
if len(data) == 0:
break
stream.write(data)
# 关闭声卡设备
stream.close()
pdev.terminate()
print('play wave success!')
play wave success!
录音并保存文件
import wave
import numpy as np
import pyaudio
chunk = 160
sample_rate = 8000
channle = 1
record_total = 8000 * 10 * 2
record_count= 0
pdev = pyaudio.PyAudio()
stream_in = pdev.open(format = pdev.get_format_from_width(2),
channels = 1,
rate = sample_rate,
input = True,
frames_per_buffer = chunk)
stream_out = pdev.open(format = pdev.get_format_from_width(2),
channels = 1,
rate = sample_rate,
output = True,
frames_per_buffer = chunk)
record = wave.open('record.wav', 'wb')
record.setnchannels(1)
record.setsampwidth(2)
record.setframerate(sample_rate)
while record_total > record_count :
record_data = stream_in.read(chunk)
record.writeframes(record_data)
stream_out.write(record_data)
record_count += len(record_data)
stream_in.close()
stream_out.close()
pdev.terminate()
print('record success!')
record success!