我的目标是在按下按钮时录制声音。
第一步是实际录制音频。以下脚本就像魅力一样:
import alsaaudio, wave, numpy
inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, "default:CARD=C525")
inp.setchannels(1)
inp.setrate(44100)
inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
inp.setperiodsize(1024)
w = wave.open('test.wav', 'w')
w.setnchannels(1)
w.setsampwidth(2)
w.setframerate(44100)
while True:
l, data = inp.read()
a = numpy.fromstring(data, dtype='int16')
print numpy.abs(a).mean()
w.writeframes(data)
test.wav文件像魅力一样播放,声音被正确录制。
现在我只想在按下按钮时录制音频。我正在使用带有按钮的GrovePi。按钮效果很好。它检测到按下的按钮,它会生成.wav文件,但它生成的音频文件包含纯静态。
import time
import grovepi
import alsaaudio
import os
import wave
import numpy
button = 4 #grovepi D4
grovepi.pinMode(button,"INPUT")
inputSoundDevice = "default:CARD=C525"
path = os.path.realpath(__file__).rstrip(os.path.basename(__file__))
def start():
print "started"
while True:
if grovepi.digitalRead(button) == 1:
inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, inputSoundDevice)
inp.setchannels(1)
inp.setrate(44100)
inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
inp.setperiodsize(1024)
time.sleep(.5)
print "inp setup"
w = wave.open('test.wav', 'w')
w.setnchannels(1)
w.setsampwidth(2)
w.setframerate(44100)
print "wave setup"
while(grovepi.digitalRead(button) == 1):
l, data = inp.read()
a = numpy.fromstring(data, dtype='int16')
print numpy.abs(a).mean()
w.writeframes(data)
time.sleep(.5)
w.close()
inp = None
print "closed"
start()
有人能指出我正确的方向来解决这个问题吗?我无法想出这个。
测试: 这些操作产生相同的静态音频文件:
numpy错误
File "buttonWhilePressedLight.py", line 43, in <module>
start()
File "buttonWhilePressedLight.py", line 34, in start
a = numpy.fromstring(data, dtype='int16')
ValueError: string size must be a multiple of element size
&#34; print l&#34;在numpy注释掉的循环中
started
inp setup
wave setup
940
-32
940
-32
940
<-etc,etc,etc->
closed