资源简介
python代码实现录音,可以生成标准格式的wav文件,方便使用,可以进一步实现调用该百度API实现转录
代码片段和文件信息
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from pyaudio import PyAudio paInt16
import numpy as np
from datetime import datetime
import wave
class recoder:
NUM_SAMPLES = 2000 #pyaudio内置缓冲大小
SAMPLING_RATE = 8000 #取样频率
LEVEL = 500 #声音保存的阈值
COUNT_NUM = 20 #NUM_SAMPLES个取样之内出现COUNT_NUM个大于LEVEL的取样则记录声音
SAVE_LENGTH = 8 #声音记录的最小长度:SAVE_LENGTH * NUM_SAMPLES 个取样
TIME_COUNT = 60 #录音时间,单位s
Voice_String = []
def savewav(selffilename):
wf = wave.open(filename ‘wb‘)
wf.setnchannels(1)
wf.setsampwidth(2)
wf.setframerate(self.SAMPLING_RATE)
wf.writeframes(np.array(self.Voice_String).tostring())
# wf.writeframes(self.Voice_String.decode())
wf.close()
def recoder(self):
pa = PyAudio()
stream = pa.open(format=paInt16 channels=1 rate=self.SAMPLING_RATE input=True
frames_per_buffer=self.NUM_SAMPLES)
save_count = 0
save_buffer = []
time_count = self.TIME_COUNT
while True:
time_count -= 1
# print time_count
# 读入NUM_SAMPLES个取样
string_audio_data = stream.read(self.NUM_SAMPLES)
# 将读入的数据转换为数组
audio_data = np.fromstring(string_audio_data dtype=np.short)
#
评论
共有 条评论