124 lines
4.4 KiB
Python
124 lines
4.4 KiB
Python
"""音訊播放:以送出的取樣數計算播放位置(比 pygame.mixer 準),支援變速與打擊音效"""
|
|
import threading
|
|
|
|
import numpy as np
|
|
|
|
try:
|
|
import sounddevice as sd
|
|
except Exception: # 沒有音訊裝置(例如 CI)時仍可載入、計算波形
|
|
sd = None
|
|
|
|
SAMPLE_RATE = 44100
|
|
|
|
|
|
def load_audio(path):
|
|
"""讀 wav/mp3/flac/ogg → float32 stereo ndarray (n, 2)"""
|
|
import miniaudio
|
|
dec = miniaudio.decode_file(path, output_format=miniaudio.SampleFormat.FLOAT32,
|
|
nchannels=2, sample_rate=SAMPLE_RATE)
|
|
return np.frombuffer(dec.samples, dtype=np.float32).reshape(-1, 2).copy()
|
|
|
|
|
|
def make_click(freq=1800.0, ms=30):
|
|
n = int(SAMPLE_RATE * ms / 1000)
|
|
t = np.arange(n) / SAMPLE_RATE
|
|
return (np.sin(2 * np.pi * freq * t) * np.exp(-t * 180) * 0.6).astype(np.float32)
|
|
|
|
|
|
class Player:
|
|
def __init__(self, samples):
|
|
self.samples = samples
|
|
self.pos = 0.0 # 播放位置(取樣,可為小數:變速時)
|
|
self.speed = 1.0
|
|
self.playing = False
|
|
self.hit_times = [] # 打擊音效時間點(ms,已排序)
|
|
self.hitsound = True
|
|
self._click = make_click()
|
|
self._clicks = [] # 進行中的打擊音效 [(offset_in_click)]
|
|
self._lock = threading.Lock()
|
|
self._stream = None
|
|
self.latency = 0.0
|
|
if sd is not None:
|
|
try:
|
|
self._stream = sd.OutputStream(samplerate=SAMPLE_RATE, channels=2, dtype="float32",
|
|
callback=self._callback, latency="low")
|
|
self._stream.start()
|
|
self.latency = self._stream.latency
|
|
except Exception:
|
|
self._stream = None
|
|
|
|
@property
|
|
def length_ms(self):
|
|
return len(self.samples) / SAMPLE_RATE * 1000
|
|
|
|
def position_ms(self):
|
|
"""目前「聽到」的位置:扣掉輸出延遲"""
|
|
with self._lock:
|
|
p = self.pos
|
|
heard = p / SAMPLE_RATE * 1000 - (self.latency * 1000 * self.speed if self.playing else 0)
|
|
return max(0.0, heard)
|
|
|
|
def seek(self, ms):
|
|
with self._lock:
|
|
self.pos = max(0.0, min(len(self.samples) - 1, ms / 1000 * SAMPLE_RATE))
|
|
self._clicks.clear()
|
|
|
|
def toggle(self):
|
|
self.playing = not self.playing
|
|
|
|
def set_hit_times(self, times):
|
|
with self._lock:
|
|
self.hit_times = sorted(times)
|
|
|
|
def close(self):
|
|
if self._stream is not None:
|
|
self._stream.stop()
|
|
self._stream.close()
|
|
|
|
def _callback(self, out, frames, time_info, status):
|
|
out.fill(0)
|
|
if not self.playing:
|
|
return
|
|
with self._lock:
|
|
start = self.pos
|
|
idx = start + np.arange(frames) * self.speed
|
|
i0 = idx.astype(np.int64)
|
|
valid = i0 < len(self.samples) - 1
|
|
if valid.any():
|
|
i0v = i0[valid]
|
|
frac = (idx[valid] - i0v)[:, None]
|
|
out[valid] = self.samples[i0v] * (1 - frac) + self.samples[i0v + 1] * frac
|
|
self.pos = start + frames * self.speed
|
|
if self.pos >= len(self.samples) - 1:
|
|
self.pos = len(self.samples) - 1
|
|
self.playing = False
|
|
|
|
if self.hitsound and self.hit_times:
|
|
t0 = start / SAMPLE_RATE * 1000
|
|
t1 = self.pos / SAMPLE_RATE * 1000
|
|
lo = np.searchsorted(self.hit_times, t0)
|
|
hi = np.searchsorted(self.hit_times, t1)
|
|
for ht in self.hit_times[lo:hi]:
|
|
at = int((ht - t0) / 1000 * SAMPLE_RATE / self.speed)
|
|
self._clicks.append(-at)
|
|
alive = []
|
|
for off in self._clicks:
|
|
a = max(0, -off)
|
|
c0 = max(0, off)
|
|
n = min(frames - a, len(self._click) - c0)
|
|
if n > 0:
|
|
out[a:a + n] += self._click[c0:c0 + n, None]
|
|
if off + frames < len(self._click):
|
|
alive.append(off + frames)
|
|
self._clicks = alive
|
|
|
|
|
|
def waveform(samples, bin_ms=10):
|
|
"""每 bin_ms 一個峰值(0~1),用於畫波形"""
|
|
mono = np.abs(samples).max(axis=1)
|
|
step = int(SAMPLE_RATE * bin_ms / 1000)
|
|
n = len(mono) // step
|
|
peaks = mono[: n * step].reshape(n, step).max(axis=1)
|
|
m = peaks.max() or 1.0
|
|
return peaks / m
|