source: python/demos/demo_alsa.py @ c23e591

feature/autosinkfeature/cnnfeature/cnn_orgfeature/constantqfeature/crepefeature/crepe_orgfeature/pitchshiftfeature/pydocstringsfeature/timestretchfix/ffmpeg5sampler
Last change on this file since c23e591 was 9492ec88, checked in by Paul Brossier <piem@piem.org>, 8 years ago

python/demos/demo_alsa.py: add example using alsaaudio (closes #72)

  • Property mode set to 100755
File size: 1.3 KB
Line 
1#! /usr/bin/env python
2
3import alsaaudio
4import numpy as np
5import aubio
6
7# constants
8samplerate = 44100
9win_s = 2048
10hop_s = win_s // 2
11framesize = hop_s
12
13# set up audio input
14recorder = alsaaudio.PCM(type=alsaaudio.PCM_CAPTURE)
15recorder.setperiodsize(framesize)
16recorder.setrate(samplerate)
17recorder.setformat(alsaaudio.PCM_FORMAT_FLOAT_LE)
18recorder.setchannels(1)
19
20# create aubio pitch detection (first argument is method, "default" is
21# "yinfft", can also be "yin", "mcomb", fcomb", "schmitt").
22pitcher = aubio.pitch("default", win_s, hop_s, samplerate)
23# set output unit (can be 'midi', 'cent', 'Hz', ...)
24pitcher.set_unit("Hz")
25# ignore frames under this level (dB)
26pitcher.set_silence(-40)
27
28print("Starting to listen, press Ctrl+C to stop")
29
30# main loop
31while True:
32    try:
33        # read data from audio input
34        _, data = recorder.read()
35        # convert data to aubio float samples
36        samples = np.fromstring(data, dtype=aubio.float_type)
37        # pitch of current frame
38        freq = pitcher(samples)[0]
39        # compute energy of current block
40        energy = np.sum(samples**2)/len(samples)
41        # do something with the results
42        print("{:10.4f} {:10.4f}".format(freq,energy))
43    except KeyboardInterrupt:
44        print("Ctrl+C pressed, exiting")
45        break
Note: See TracBrowser for help on using the repository browser.