Thursday, July 11, 2013

linux command reminder

1.Save the output of terminal to a file.
$ my_program ... | tee my_program.log

Monday, July 8, 2013

Record from mic by Python

There are many module you can use to do this.


1. PyAudio

import pyaudio
import wave

CHUNK = 1024 
FORMAT = pyaudio.paInt16 #paInt8
CHANNELS = 2 
RATE = 44100 #sample rate
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) #buffer

print("* recording")

frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data) # 2 bytes(16 bits) per channel

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' )
  # Minimum set of parameters we need to create Encoder

  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()
  
  # Loop until recorded position greater than the limit specified

  while snd.getPosition()<= secs:
    s= snd.getData()
    if s and len( s ):
      for fr in ac.encode( s ):
        # We definitely should use mux first, but for

        # simplicity reasons this way it'll work also

        f.write( fr )
    else:
      time.sleep( .003 )
  
  # Stop listening the incoming sound from the microphone or line in

  snd.stop()

# -------------------------------------------------------------------
# Record stereo sound from the line in or microphone 
# and save it as mp3 file
# Specify length and output file name
# http://pymedia.org/

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')
    # Open the device in nonblocking capture mode. The last argument could
    # just as well have been zero for blocking mode. Then we could have
    # left out the sleep call in the bottom of the loop
    
    inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NONBLOCK, card)
    
    # Set attributes: Mono, 44100 Hz, 16 bit little endian samples
    
    inp.setchannels(1)
    inp.setrate(44100)
    inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
    
    # The period size controls the internal number of frames per period.
    # The significance of this parameter is documented in the ALSA api.
    # For our purposes, it is suficcient to know that reads from the device
    # will return this many frames. Each frame being 2 bytes long.
    # This means that the reads below will return either 320 bytes of data
    # or 0 bytes of data. The latter is possible because we are in nonblocking
    # mode.
    
    inp.setperiodsize(48)

    print 'haha2'
    loops = 100
    while loops > 0:
        print 'haha3'
        loops -= 1
        # Read data from device
        l, data = inp.read()
        print len(data)
        print l
        if l:
            f.write(data)
            time.sleep(.001)

How to get the maximum and minimum sampling rate for your audio cards in Linux

Source from :  voxForge

1. Sound Card or Integrated Audio

    $arecord --list-devices

try an sample rate very large or very small and you can get the message from your error message.

    $ arecord -f dat -r 60000 -D hw:0,0 -d 5 test.wav

2. USB Microphone or USB audio pod

   $  arecord -f S16_LE -r 60000 -D hw:1,0 -d 5 testS16_LE.wav

the same way mentioned above.

Wednesday, July 3, 2013