Created
July 23, 2024 10:28
-
-
Save curegit/d55159030c74092a45cb59dd33b2ddd5 to your computer and use it in GitHub Desktop.
拍の位置を考慮してトラックを断片化する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import itertools | |
import os | |
import shutil | |
import soundfile as sf | |
import librosa | |
import librosa.beat | |
import librosa.effects | |
beat = 4 | |
with open("01. What An Amazing Swing.wav", "rb") as fp: | |
data, samplerate = sf.read(fp) | |
x = data.transpose((1, 0)) | |
print(f"{x.dtype=}", f"{x.shape=}", f"{samplerate=}Hz") | |
y, (start, end) = librosa.effects.trim(x) | |
mono = librosa.to_mono(y) | |
tempo, beats = librosa.beat.beat_track(y=mono, sr=samplerate, units="samples") | |
shutil.rmtree("segments", ignore_errors=True) | |
os.makedirs("segments", exist_ok=True) | |
bs = list(map(int, beats)) | |
ts = [0] + [(l + r) // 2 for l, r in zip(bs, bs[1:])] | |
ss = [t[0] for t in itertools.batched(ts, n=beat)] | |
xs = list(zip(ss, ss[1:] + [len(mono)])) | |
kn = len(str(len(xs) + 1)) | |
ops = {"subtype": "PCM_24"} | |
sf.write(f"segments/a-{0:0{kn}}-start.wav", data[:start], samplerate, **ops) | |
for i, (l, r) in enumerate(xs, 1): | |
print(l, r) | |
fr = y[:, l:r] | |
sf.write(f"segments/a-{i:0{kn}}.wav", fr.transpose((1, 0)), samplerate, **ops) | |
sf.write(f"segments/a-{i + 1:0{kn}}-end.wav", data[end:], samplerate, **ops) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment