Python:如何使用pyaudio为Google Cloud Speech API获取原始音频文件

时间:2017-01-08 13:09:20

标签: python google-cloud-speech

我正在使用linux下面链接中给出的程序。

https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/speech/cloud-client/quickstart.py

我面临的问题是如何使用pyaudio通过麦克风录制我自己的原始音频文件,以使用上述程序获取我录制的文本。

我有下面的pyaudio程序,但它给了我wav文件。但我想保存谷歌云语音API的原始音频文件。我不想将wav转换为原始音频文件。我直接想用pyaudio保存原始音频文件。

import pyaudio
import wave

FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
CHUNK = 1024
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "file.wav"

audio = pyaudio.PyAudio()

# start Recording
 stream = audio.open(format=FORMAT, channels=CHANNELS,
            rate=RATE, input=True,
            frames_per_buffer=CHUNK)
 print "recording..."
 frames = []

 for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
 data = stream.read(CHUNK)
 frames.append(data) 
 print "finished recording"


 # stop Recording
 stream.stop_stream()
 stream.close()
 audio.terminate()

 waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
 waveFile.setnchannels(CHANNELS)
 waveFile.setsampwidth(audio.get_sample_size(FORMAT))
 waveFile.setframerate(RATE)
 waveFile.writeframes(b''.join(frames))
 waveFile.close()

1 个答案:

答案 0 :(得分:2)

我找到了答案。很抱歉发布了这个问题。我是编程新手..

import pyaudio
import wave

FORMAT = pyaudio.paInt16

CHANNELS = 1
RATE = 16000
CHUNK = int(RATE / 10)
RECORD_SECONDS = 5

audio = pyaudio.PyAudio()

# start Recording
stream = audio.open(format=FORMAT, channels=CHANNELS,
            rate=RATE, input=True,
            frames_per_buffer=CHUNK)
print "recording..."
frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)
print "finished recording"


# stop Recording
stream.stop_stream()
stream.close()
audio.terminate()



file = open("newfile.raw", "w")
file.write(b''.join(frames))
file.close()