-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbeatcli.py
178 lines (161 loc) · 5.06 KB
/
beatcli.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
"""
Module Name: beatcli.py
Author: Peter Meier
Email: peter.meier@audiolabs-erlangen.de
Date: 2024-10-01
Version: 0.0.1
Description: A Real-Time Beat Tracking Dashboard for the Terminal.
License: MIT License (https://opensource.org/licenses/MIT)
"""
import argparse
import datetime
import threading
import numpy as np
import sounddevice as sd
from pythonosc import udp_client
from realtimeplp import RealTimeBeatTracker
# TODO: Add --learn mode for mapping OSC signals.
# Output all OSC channels in a row with 1 second delay between.
# Argparse
parser = argparse.ArgumentParser(description="Beat (C)ommand (L)ine (I)nterface.")
parser.add_argument(
"-l",
"--list-devices",
action="store_true",
help="show list of audio devices and exit",
)
parser.add_argument(
"--device",
metavar="ID",
type=int,
help="(%(default)s) device id for sounddevice input",
)
parser.add_argument(
"--channel",
default=1,
metavar="NUMBER",
type=int,
help="(%(default)s) channel number for sounddevice input",
)
parser.add_argument(
"--samplerate",
default=44100,
metavar="FS",
type=int,
help="(%(default)s) samplerate for sounddevice",
)
parser.add_argument(
"--blocksize",
default=512,
metavar="SAMPLES",
type=int,
help="(%(default)s) blocksize for sounddevice",
)
parser.add_argument(
"--tempo",
nargs=2,
metavar=("LOW", "HIGH"),
default=[60, 180],
type=int,
help="(%(default)s) tempo range in BPM",
)
parser.add_argument(
"--lookahead",
default=0,
metavar="FRAMES",
type=int,
help="(%(default)s) number of frames (samplerate / blocksize) to lookahead"
" in time and get the next beat earlier to compensate for latency",
)
parser.add_argument(
"--kernel",
default=6,
metavar="SIZE",
type=int,
help="(%(default)s) kernel size in seconds",
)
parser.add_argument(
"--ip", default="0.0.0.0", type=str, help="(%(default)s) ip address for OSC client"
)
parser.add_argument(
"--port", default=5005, type=int, help="(%(default)s) port for OSC client"
)
args = parser.parse_args()
# List devices
if args.list_devices:
print(sd.query_devices())
parser.exit(0)
low, high = args.tempo
if high <= low:
parser.error("HIGH must be greater than LOW")
# Sounddevice Settings
sd.default.blocksize = args.blocksize
sd.default.samplerate = args.samplerate
sd.default.latency = 0 # in seconds
sd.default.channels = args.channel # number of channels (both in and out)
sd.default.device = (args.device, args.device) # (in_device_id, out_device_id)
device = sd.query_devices(args.device, "input")
# OSC Client
client = udp_client.SimpleUDPClient(args.ip, args.port)
beat = RealTimeBeatTracker.from_args(
N=2 * args.blocksize,
H=args.blocksize,
samplerate=args.samplerate,
N_time=args.kernel,
Theta=np.arange(low, high + 1, 1),
lookahead=args.lookahead,
)
# Global Variables
stability = []
tempo = []
def callback(indata, _frames, _time, status):
"""Audio callback."""
if status:
print(status)
# counting from 0: index of last channel = number of channels - 1
beat_detected = beat.process(indata[:, args.channel - 1])
# OSC messages on framerate level
# shift value range from [-1,1] to [0,1] for DAW (like Ableton)
client.send_message("/alpha-lfo", (beat.cs.alpha_lfo + 1) / 2) # [-1,1] to [0,1]
client.send_message("/gamma-lfo", (beat.cs.gamma_lfo + 1) / 2) # [-1,1] to [0,1]
client.send_message("/beta-conf", beat.cs.beta_confidence)
client.send_message("/gamma-conf", beat.cs.gamma_confidence)
# OSC / console output on beat level
if beat_detected:
# send OSC messages
client.send_message("/stability", beat.plp.stability)
client.send_message("/tempo", int(beat.plp.current_tempo))
# print to console
print(
f"OSC to {args.ip}:{args.port}:",
f'time={datetime.datetime.now().strftime("%H:%M:%S.%f")[:-3]}',
f"tempo={beat.plp.current_tempo}",
f"stability={beat.cs.beta_confidence:.3f}",
)
tempo.append(beat.plp.current_tempo)
stability.append(beat.cs.beta_confidence)
if __name__ == "__main__":
# Print Arguments
print("Beat (C)ommand (L)ine (I)nterface:", vars(args))
# Thread Event for keeping sounddevice running
event = threading.Event()
# Start Sounddevice Input Stream
with sd.InputStream(
callback=callback, samplerate=args.samplerate, finished_callback=event.set
):
try:
event.wait()
except KeyboardInterrupt:
print("")
print("--- beat statistics ---")
print(f"{len(tempo)} beats transmitted")
print(
f"tempo min/avg/max/stddev = "
f"{min(tempo):.2f}/{np.mean(tempo):.2f}/"
f"{max(tempo):.2f}/{np.std(tempo):.2f}"
)
print(
f"stability min/avg/max/stddev = "
f"{min(stability):.3f}/{np.mean(stability):.3f}/"
f"{max(stability):.3f}/{np.std(stability):.3f}"
)