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
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()

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