[e7da8ba] | 1 | #! /usr/bin/env python |
---|
| 2 | |
---|
[62336bb] | 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 | |
---|
[e7da8ba] | 12 | import pyaudio |
---|
| 13 | import sys |
---|
| 14 | import numpy as np |
---|
[62336bb] | 15 | import aubio |
---|
[e7da8ba] | 16 | |
---|
| 17 | # initialise pyaudio |
---|
| 18 | p = pyaudio.PyAudio() |
---|
| 19 | |
---|
| 20 | # open stream |
---|
| 21 | buffer_size = 1024 |
---|
| 22 | pyaudio_format = pyaudio.paFloat32 |
---|
| 23 | n_channels = 1 |
---|
| 24 | samplerate = 44100 |
---|
| 25 | stream = p.open(format=pyaudio_format, |
---|
| 26 | channels=n_channels, |
---|
| 27 | rate=samplerate, |
---|
| 28 | input=True, |
---|
| 29 | frames_per_buffer=buffer_size) |
---|
| 30 | |
---|
| 31 | if len(sys.argv) > 1: |
---|
| 32 | # record 5 seconds |
---|
| 33 | output_filename = sys.argv[1] |
---|
| 34 | record_duration = 5 # exit 1 |
---|
[62336bb] | 35 | outputsink = aubio.sink(sys.argv[1], samplerate) |
---|
[e7da8ba] | 36 | total_frames = 0 |
---|
| 37 | else: |
---|
| 38 | # run forever |
---|
| 39 | outputsink = None |
---|
| 40 | record_duration = None |
---|
| 41 | |
---|
| 42 | # setup pitch |
---|
| 43 | tolerance = 0.8 |
---|
| 44 | win_s = 4096 # fft size |
---|
| 45 | hop_s = buffer_size # hop size |
---|
[62336bb] | 46 | pitch_o = aubio.pitch("default", win_s, hop_s, samplerate) |
---|
[e7da8ba] | 47 | pitch_o.set_unit("midi") |
---|
| 48 | pitch_o.set_tolerance(tolerance) |
---|
| 49 | |
---|
| 50 | print("*** starting recording") |
---|
| 51 | while 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 | |
---|
| 72 | print("*** done recording") |
---|
| 73 | stream.stop_stream() |
---|
| 74 | stream.close() |
---|
| 75 | p.terminate() |
---|