source: python/demos/demo_pyaudio.py @ 7436353

feature/autosinkfeature/cnnfeature/crepefix/ffmpeg5
Last change on this file since 7436353 was 62336bb, checked in by Paul Brossier <piem@piem.org>, 8 years ago

python/demos/demo_pyaudio.py: add some comments, avoid overwriting aubio.pitch

  • Property mode set to 100755
File size: 1.9 KB
Line 
1#! /usr/bin/env python
2
3# Use pyaudio to open the microphone and run aubio.pitch on the stream of
4# incoming samples. If a filename is given as the first argument, it will
5# record 5 seconds of audio to this location. Otherwise, the script will
6# run until Ctrl+C is pressed.
7
8# Examples:
9#    $ ./python/demos/demo_pyaudio.py
10#    $ ./python/demos/demo_pyaudio.py /tmp/recording.wav
11
12import pyaudio
13import sys
14import numpy as np
15import aubio
16
17# initialise pyaudio
18p = pyaudio.PyAudio()
19
20# open stream
21buffer_size = 1024
22pyaudio_format = pyaudio.paFloat32
23n_channels = 1
24samplerate = 44100
25stream = p.open(format=pyaudio_format,
26                channels=n_channels,
27                rate=samplerate,
28                input=True,
29                frames_per_buffer=buffer_size)
30
31if len(sys.argv) > 1:
32    # record 5 seconds
33    output_filename = sys.argv[1]
34    record_duration = 5 # exit 1
35    outputsink = aubio.sink(sys.argv[1], samplerate)
36    total_frames = 0
37else:
38    # run forever
39    outputsink = None
40    record_duration = None
41
42# setup pitch
43tolerance = 0.8
44win_s = 4096 # fft size
45hop_s = buffer_size # hop size
46pitch_o = aubio.pitch("default", win_s, hop_s, samplerate)
47pitch_o.set_unit("midi")
48pitch_o.set_tolerance(tolerance)
49
50print("*** starting recording")
51while True:
52    try:
53        audiobuffer = stream.read(buffer_size)
54        signal = np.fromstring(audiobuffer, dtype=np.float32)
55
56        pitch = pitch_o(signal)[0]
57        confidence = pitch_o.get_confidence()
58
59        print("{} / {}".format(pitch,confidence))
60
61        if outputsink:
62            outputsink(signal, len(signal))
63
64        if record_duration:
65            total_frames += len(signal)
66            if record_duration * samplerate < total_frames:
67                break
68    except KeyboardInterrupt:
69        print("*** Ctrl+C pressed, exiting")
70        break
71
72print("*** done recording")
73stream.stop_stream()
74stream.close()
75p.terminate()
Note: See TracBrowser for help on using the repository browser.