source: python/demos/demo_tapthebeat.py @ 929d76c

feature/autosinkfeature/cnnfeature/cnn_orgfeature/constantqfeature/crepefeature/crepe_orgfeature/pitchshiftfeature/pydocstringsfeature/timestretchfix/ffmpeg5
Last change on this file since 929d76c was c4fc0f2, checked in by Paul Brossier <piem@piem.org>, 7 years ago

python/demos/demo_tapthebeat.py: prefix unused arguments with _

  • Property mode set to 100755
File size: 2.0 KB
Line 
1#! /usr/bin/env python
2
3""" A simple demo using aubio and pyaudio to play beats in real time
4
5Note you will need to have pyaudio installed: `pip install pyaudio`.
6
7Examples:
8    ./demo_tapthebeat.py ~/Music/track1.ogg
9
10When compiled with ffmpeg/libav, you should be able to open remote streams. For
11instance using youtube-dl (`pip install youtube-dl`):
12
13    ./demo_tapthebeat.py `youtube-dl -xg https://youtu.be/zZbM9n9j3_g`
14
15"""
16
17import sys
18import time
19import pyaudio
20import aubio
21import numpy as np
22
23win_s = 1024                # fft size
24hop_s = win_s // 2          # hop size
25
26# parse command line arguments
27if len(sys.argv) < 2:
28    print("Usage: %s <filename> [samplerate]" % sys.argv[0])
29    sys.exit(1)
30
31filename = sys.argv[1]
32
33samplerate = 0
34if len( sys.argv ) > 2: samplerate = int(sys.argv[2])
35
36# create aubio source
37a_source = aubio.source(filename, samplerate, hop_s)
38samplerate = a_source.samplerate
39
40# create aubio tempo detection
41a_tempo = aubio.tempo("default", win_s, hop_s, samplerate)
42
43# create a simple click sound
44click = 0.7 * np.sin(2. * np.pi * np.arange(hop_s) / hop_s * samplerate / 3000.)
45
46# pyaudio callback
47def pyaudio_callback(_in_data, _frame_count, _time_info, _status):
48    samples, read = a_source()
49    is_beat = a_tempo(samples)
50    if is_beat:
51        samples += click
52        #print ('tick') # avoid print in audio callback
53    audiobuf = samples.tobytes()
54    if read < hop_s:
55        return (audiobuf, pyaudio.paComplete)
56    return (audiobuf, pyaudio.paContinue)
57
58# create pyaudio stream with frames_per_buffer=hop_s and format=paFloat32
59p = pyaudio.PyAudio()
60pyaudio_format = pyaudio.paFloat32
61frames_per_buffer = hop_s
62n_channels = 1
63stream = p.open(format=pyaudio_format, channels=n_channels, rate=samplerate,
64        output=True, frames_per_buffer=frames_per_buffer,
65        stream_callback=pyaudio_callback)
66
67# start pyaudio stream
68stream.start_stream()
69
70# wait for stream to finish
71while stream.is_active():
72    time.sleep(0.1)
73
74# stop pyaudio stream
75stream.stop_stream()
76stream.close()
77# close pyaudio
78p.terminate()
Note: See TracBrowser for help on using the repository browser.