There are many module you can use to do this.
1. PyAudio
import pyaudio
import wave
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"
p = pyaudio.PyAudio()
stream = p.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("* done recording")
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
2. PyMedia
import time, sys
import pymedia.audio.sound as sound
import pymedia.audio.acodec as acodec
def voiceRecorder( secs, name ):
f= open( name, 'wb' )
cparams= { 'id': acodec.getCodecId( 'mp3' ),
'bitrate': 128000,
'sample_rate': 44100,
'channels': 2 }
ac= acodec.Encoder( cparams )
snd= sound.Input( 44100, 2, sound.AFMT_S16_LE )
snd.start()
while snd.getPosition()<= secs:
s= snd.getData()
if s and len( s ):
for fr in ac.encode( s ):
f.write( fr )
else:
time.sleep( .003 )
snd.stop()
if __name__ == "__main__":
if len( sys.argv )!= 3:
print 'Usage: voice_recorder '
else:
voiceRecorder( int( sys.argv[ 1 ] ), sys.argv[ 2 ] )
3. alsaaudio
import sys
import time
import getopt
import alsaaudio
def usage():
sys.stderr.write('usage: recordtest.py [-c ] \n')
print 'haha4'
sys.exit(2)
if __name__ == '__main__':
print 'haha1'
card = 'default'
opts, args = getopt.getopt(sys.argv[1:], 'c:')
for o, a in opts:
if o == '-c':
card = a
if not args:
usage()
f = open(args[0], 'wb')
inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NONBLOCK, card)
inp.setchannels(1)
inp.setrate(44100)
inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
inp.setperiodsize(48)
print 'haha2'
loops = 100
while loops > 0:
print 'haha3'
loops -= 1
l, data = inp.read()
print len(data)
print l
if l:
f.write(data)
time.sleep(.001)
No comments:
Post a Comment