History

python/demos/demo_tapthebeat.py: play beats using pyaudio

Paul Brossier committed 9 years ago

Commit 21eb4c21 parent d6befbe1 file · +78 −0Browse files

Showing the changes to python (1 of 1 file). Show all

Unified · Split

python/demos/demo_tapthebeat.py+78−0
@@ -0,0 +1,78 @@
1+#! /usr/bin/env python
2+
3+""" A simple demo using aubio and pyaudio to play beats in real time
4+
5+Note you will need to have pyaudio installed: `pip install pyaudio`.
6+
7+Examples:
8+ ./demo_tapthebeat.py ~/Music/track1.ogg
9+
10+When compiled with ffmpeg/libav, you should be able to open remote streams. For
11+instance using youtube-dl (`pip install youtube-dl`):
12+
13+ ./demo_tapthebeat.py `youtube-dl -xg https://youtu.be/zZbM9n9j3_g`
14+
15+"""
16+
17+import sys
18+import time
19+import pyaudio
20+import aubio
21+import numpy as np
22+
23+win_s = 1024 # fft size
24+hop_s = win_s // 2 # hop size
25+
26+# parse command line arguments
27+if len(sys.argv) < 2:
28+ print("Usage: %s <filename> [samplerate]" % sys.argv[0])
29+ sys.exit(1)
30+
31+filename = sys.argv[1]
32+
33+samplerate = 0
34+if len( sys.argv ) > 2: samplerate = int(sys.argv[2])
35+
36+# create aubio source
37+a_source = aubio.source(filename, samplerate, hop_s)
38+samplerate = a_source.samplerate
39+
40+# create aubio tempo detection
41+a_tempo = aubio.tempo("default", win_s, hop_s, samplerate)
42+
43+# create a simple click sound
44+click = 0.7 * np.sin(2. * np.pi * np.arange(hop_s) / hop_s * samplerate / 3000.)
45+
46+# pyaudio callback
47+def 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
59+p = pyaudio.PyAudio()
60+pyaudio_format = pyaudio.paFloat32
61+frames_per_buffer = hop_s
62+n_channels = 1
63+stream = 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
68+stream.start_stream()
69+
70+# wait for stream to finish
71+while stream.is_active():
72+ time.sleep(0.1)
73+
74+# stop pyaudio stream
75+stream.stop_stream()
76+stream.close()
77+# close pyaudio
78+p.terminate()

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t