Learning Python(5)---基本语音处理

打开音频文件

Import wave
filePath = “hello.wav”
file = wave.open(filePath, ‘rb’)

或者使用上下文管理器

With contexlib.closing(wave.open(filePath, ‘rb’)) as wf:
         Doing something with wf

在执行过程离开with语句体时自动执行object.close()

 

获得音频参数

Params = file.getparams()
Nchannels, sampwidth, framerate, nframes = params[:4]

其中:Nchannels:声道数;Sampwidth:量化位数,表示使用多少byte来表达一次采样采集的数据

;Framerate:采样频率;Nframes:采样点数。

或者

Nchannels = file.getnchannels()
Sampwidth = file.getsampwidth()
Framerate = file.getframerate()
Nframes = file.getnframes()

 

读取音频数据

strData = file.readframes(nframes)  #读取音频字符串格式
#import numpy as np
waveData = np.frambuffer (strData, dtype = np.int16) #将字符串转化为int
waveData = waveData * 1.0/(max(abs(waveData)))

写入数据到音频文件

File = wave.open(path, ‘wb’)
File.setnchannels(1)
File.setsampwidth(2)
File.setframerate(sample_rate)
File.writeframes(frames)

需要注意的是 data有两种数据格式,int 或者 str,音频文件读取和写入的格式都是str。

所以要注意格式的转换。

格式转换

wave_data = wave_file.readframes(wave_file.getnframes())   
wave_data = np.fromstring(wave_data, np.int16)

或者

wave_data = wave_data.astype(np.int16)

读取完数据之后,对数据进行处理之前,需要对数据进行格式转换,因为sampwidth = 2,

所以数据的宽度是两个字节,即为int16。

显示音频图像

时域

#Import matplotlib.pyplot as plt
time = np.arange(0,nframes)*(1.0 / framerate)
plt.plot(time, waveData)  #设置横纵坐标数据
plt.xlabel(“Time(s)”)
plt.ylabel(“Amplitude”)  #设置横纵坐标数据名称
plt.tittle(“single channel wavedate”)  #设置表格名称
plt.grid(“on”)      #设置显示标尺

语音采集

    pa=PyAudio()
    stream=pa.open(format = paInt16,channels=1,
                   rate=framerate,input=True,
                   frames_per_buffer=NUM_SAMPLES)
    wav_data=[]
    count=0
    while count<TIME*20:#控制录音时间
        string_audio_data = stream.read(NUM_SAMPLES)#一次性录音采样字节大小
        wav_data.append(string_audio_data)
        count+=1
        print('.')
    save_wave_file('01.wav',wav_data)
    stream.close()

音频播放

def wavplay(filename):
    CHUNK = 1024
    f = wave.open(filename, "rb")
    p = pyaudio.PyAudio()
    stream = p.open(format = p.get_format_from_width(f.getsampwidth()),
                   channels = f.getnchannels(),
                   rate = f.getframerate(),
                   output = True)

    i = 0;
    while i * CHUNK < f.getnframes():
        data = f.readframes(CHUNK)
        stream.write(data)
        i = i+1
    stream.stop_stream()
    stream.close()
    p.terminate()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CHAO_^

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值