Raspberry Pi将Pyaudio Wav转换为Flac 48000hz + Google Speech

时间:2013-11-21 20:56:20

标签: python audio raspberry-pi pyaudio avconv

我正面临以下问题:

我用Pyaudio录制声音并将其保存为Wav。 Wav文件是48000hz(没有其他速率工作(采样率错误,但这是另一个故事)) Wav文件听起来不错,现在我想将wav转换为flac,将其发送到谷歌语音API。

问题是avconf将我的48khz输入wav转换为8khz flac(使用-ar 48000)。 flac文件只是白噪声,我已经尝试了很多,但即便谷歌也没有答案;)

注意:对于我来说,使用16Khz的其他麦克风完全没问题。 Pyaudios采样率误差和avconv问题都没有。

这是代码:

录音:

   chunk = 2048
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 48000
THRESHOLD = 525 #The threshold intensity that defines silence signal (lower than).
SILENCE_LIMIT = 3 #Silence limit in seconds. The max ammount of seconds where only silence is recorded. When this time passes the recording finishes and the file is delivered.

#open stream
p = pyaudio.PyAudio()

stream = p.open(format = FORMAT,
                channels = CHANNELS,
                rate = RATE,
                input = True,
                frames_per_buffer = chunk)

print "* listening. CTRL+C to finish manually."
all_m = []
data = ''
rel = RATE/chunk
slid_win = deque(maxlen=SILENCE_LIMIT*rel)
started = False

while (True):
    data = stream.read(chunk)
    slid_win.append (abs(audioop.avg(data, 2)))

    if(True in [ x>THRESHOLD for x in slid_win]):
        if(not started):
            print "starting record"
        started = True
        all_m.append(data)
    elif (started==True):
        print "finished"
        #the limit was reached, finish capture and deliver
        filename = save_speech(all_m,p)
        result=stt_google_wav(filename)
        #reset all
        started = False
        #slid_win = deque(maxlen=SILENCE_LIMIT*rel)
        #all_m= []
        print "Google STT Done"
        stream.close()
        p.terminate()
        return result

def save_speech(data, p):
filename = 'output_'+str(int(time.time()))
# write data to WAVE file
data = ''.join(data)
wf = wave.open(filename+'.wav', 'wb')
wf.setnchannels(1)
wf.setsampwidth(p.get_sample_size(pyaudio.paInt16))
wf.setframerate(48000)
wf.writeframes(data)
wf.close()
print "finished saving wav: %s" % filename
return filename

转换为Flac:

os.system("avconv -i "+ filename+".wav  -y -ar 48000 "+ filename+ ".flac")

编辑1:

Flac实际上是48khz,我不知道为什么mplayer告诉我flac是8khz,我在我的电脑上播放它并且flac是完美的,无论如何google api似乎有问题,因为它什么也没有返回。 我假设Rasberry上的mplayer的白噪声问题与谷歌Api的问题有关,但我不知道它可能是什么。

Wav文件:

output_1385413929.wav: RIFF (little-endian) data, WAVE audio, Microsoft PCM, 16 bit, mono 48000 Hz

Flac文件:

output_1385413929.flac: FLAC audio bitstream data, 16 bit, mono, 48 kHz, 204800 samples

解决: 我不知道为什么,我打开我的pi并想要测试一下然后突然它没有改变任何东西。

Ty的帮助。 来自德国的问候, FLO

1 个答案:

答案 0 :(得分:1)

我同意 - 为我做好准备:

me@raspberrypi /mnt/share/Audio/xxxxxx $ file sample_audio.wav 
sample_audio.wav: RIFF (little-endian) data, WAVE audio, Microsoft PCM, 16 bit, stereo 8000 Hz
me@raspberrypi /mnt/share/Audio/xxxxxx $ file sample_audio.flac 
sample_audio.flac: FLAC audio bitstream data, 16 bit, stereo, 48 kHz, 9131406 samples