-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpyaudio_player_crossfade.py
More file actions
196 lines (157 loc) · 5.57 KB
/
pyaudio_player_crossfade.py
File metadata and controls
196 lines (157 loc) · 5.57 KB
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
from time import sleep
import ffmpegio
import pyaudio
from contextlib import contextmanager
from threading import Thread
from queue import Empty, Queue
from testfile_generator import testfiles
from ctypes import c_short
import numpy as np
def add_carrays(ArrayType, xbuf, ybuf):
# x = np.frombuffer(xbuf,'i2')
# y = np.frombuffer(ybuf,'i2')
# print(len(x))
# return (x+y).tobytes()
x = ArrayType.from_buffer_copy(xbuf)
y = ArrayType.from_buffer_copy(ybuf)
return bytes(ArrayType(*(xi + yi for xi, yi in zip(x, y))))
@contextmanager
def pyaudio_stream(
rate, channels, width=None, unsigned=False, format=None, *args, **kwargs
):
p = pyaudio.PyAudio()
if format is None:
if width is None:
raise ValueError("Either width or format must be specified.")
format = p.get_format_from_width(width, unsigned)
try:
stream = p.open(rate, channels, format, *args, **kwargs)
try:
stream.start_stream()
yield stream
stream.stop_stream()
finally:
stream.close()
finally:
p.terminate()
ar = 44100 # playback sampling rate
ac = 2 # number of channels
layout = "stereo"
width = 2 # signed 2-byte integer format
sample_fmt = "s16"
bps = width * ac # number of bytes per sample
tfade = 0.5 # cross-fade duration
curve = "qua" # fading pattern
nfade = round(tfade * ar) # number of samples with fade effect = number of samples in each read block
nblk = nfade * bps # number of bytes in each read block
que = Queue(2) # ffmpegio-pyaudio data path, double buffered
buf = b"" # buffer for pyaudio callback
ShortArray = c_short * (nfade * ac)
def file_reader(files):
# open ffmpegio's stream-reader
def process_file(file, fout_data):
# grab the duration
T = float(
ffmpegio.probe.audio_streams_basic(file, 0, ["duration"])[0]["duration"]
)
# form the filterchain
af = (
f"aformat={sample_fmt}:{ar}:{layout}"
f",afade=in:d={tfade}:curve={curve}"
f",afade=out:st={T-tfade}:d={tfade}:curve={curve}"
)
print(af)
# read data
with ffmpegio.open(
file,
"ra",
af=af,
blocksize=nfade,
sample_fmt=sample_fmt,
ac=ac,
ar=ar,
# show_log=True,
) as f:
# read first block and combine with fout_data
blk = f.read(nfade)["buffer"]
if blk is None:
# empty data?
return b""
# align the cross-fade blocks
nfin = 0 if blk is None else len(blk)
nfout = len(fout_data)
if nfout < nblk:
# last file shorter than tfade
fout_data = fout_data + b"\0" * (nblk - nfout)
if nfin < nblk:
# this file shorter than tfade
blk = b"\0" * (nblk - nfin) + (blk or b"")
# mix fade-out and fade-in blocks for the crossfade effect
last_blk = add_carrays(ShortArray, fout_data, blk)
# process the rest of the data blocks from the file
for frame in f:
if frame is None:
return last_blk
blk = frame["buffer"] # nblk bytes of data
n = len(blk)
if n < nblk:
# this is the last block of this file
# keep the last nblk bytes (nfade samples) and queue the earlier
if nblk - n:
que.put(last_blk[: n], True, T)
last_blk = last_blk[n :] + (blk or b"")
break # just in case
else:
que.put(last_blk, True, T)
last_blk = blk
# last nfade-sample block containes the fade-out effect
# return it so the block can be mixed with the fade-in block of
# the subsequent file
return last_blk
fout_data = b"\0" * nblk # fade-out block, initialize to all 0
for file in files:
fout_data = process_file(file, fout_data)
que.put(fout_data, True, tfade) # queue last fade-out block
que.put(None, True, 2 * tfade) # queue end-of-stream
return
ncount = 0
def pyaudio_callback(_, nblk, *__):
global buf, ncount
# if not enough data in buffer, replenish from the reader thread
nreq = nblk * bps # requested number of bytes
nbuf = len(buf)
while nbuf < nreq:
try:
# wait longer if buffer is empty (only first time?)
new_data = que.get(True, nblk / ar if nbuf else 1)
if new_data is None:
# end-of-stream reached
return (b"", pyaudio.paComplete)
buf = buf + new_data
nbuf = len(buf)
except Empty:
print(f"failed to read data from FFmpeg")
return (b"", pyaudio.paAbort)
# enough data in the local buffer
data = buf[:nreq]
buf = buf[nreq:]
# if last data, wait for end-of-stream None
if len(data) < nblk:
que.get(True, nblk / ar)
ncount += len(data)
return (data, pyaudio.paContinue)
nfiles = 4
with testfiles(nfiles, 2, 3) as files:
reader = Thread(target=file_reader, args=[files])
reader.start()
with pyaudio_stream(
rate=ar,
channels=ac,
width=width,
output=True,
stream_callback=pyaudio_callback,
) as stream:
# wait for stream to finish
while stream.is_active():
sleep(0.1)
reader.join()