7
9
## writing the data to standard out.
9
11
## To test it out do the following:
10
## python recordtest.py > out.raw # talk to the microphone
12
## python recordtest.py out.raw # talk to the microphone
11
13
## aplay -r 8000 -f S16_LE -c 1 out.raw
16
# Footnote: I'd normally use print instead of sys.std(out|err).write,
17
# but we're in the middle of the conversion between python 2 and 3
18
# and this code runs on both versions without conversion
17
# Open the device in nonblocking capture mode. The last argument could
18
# just as well have been zero for blocking mode. Then we could have
19
# left out the sleep call in the bottom of the loop
20
inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE,alsaaudio.PCM_NONBLOCK)
22
# Set attributes: Mono, 8000 Hz, 16 bit little endian samples
25
inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
27
# The period size controls the internal number of frames per period.
28
# The significance of this parameter is documented in the ALSA api.
29
# For our purposes, it is suficcient to know that reads from the device
30
# will return this many frames. Each frame being 2 bytes long.
31
# This means that the reads below will return either 320 bytes of data
32
# or 0 bytes of data. The latter is possible because we are in nonblocking
34
inp.setperiodsize(160)
39
# Read data from device
43
# actual data read. Write it to stdout
44
sys.stdout.write(data)
26
sys.stderr.write('usage: recordtest.py [-c <card>] <file>\n')
29
if __name__ == '__main__':
33
opts, args = getopt.getopt(sys.argv[1:], 'c:')
41
f = open(args[0], 'wb')
43
# Open the device in nonblocking capture mode. The last argument could
44
# just as well have been zero for blocking mode. Then we could have
45
# left out the sleep call in the bottom of the loop
46
inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NONBLOCK, card)
48
# Set attributes: Mono, 44100 Hz, 16 bit little endian samples
51
inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
53
# The period size controls the internal number of frames per period.
54
# The significance of this parameter is documented in the ALSA api.
55
# For our purposes, it is suficcient to know that reads from the device
56
# will return this many frames. Each frame being 2 bytes long.
57
# This means that the reads below will return either 320 bytes of data
58
# or 0 bytes of data. The latter is possible because we are in nonblocking
60
inp.setperiodsize(160)
65
# Read data from device