| """MP3 encode via PyAV/libmp3lame. ffmpeg CLI is not installed on this cluster; |
| PyAV 18 bundles libmp3lame, so this is the only available CBR MP3 path. |
| 160 kbps CBR, mono, 48 kHz.""" |
| import io, numpy as np |
| try: |
| import av |
| _HAVE_AV = True |
| except ImportError: |
| _HAVE_AV = False |
|
|
| def encode_mp3(wav, sr=48000, bitrate=160000): |
| """wav: float32 mono numpy in [-1,1] -> bytes of a 160 kbps CBR mono mp3.""" |
| if not _HAVE_AV: |
| raise RuntimeError("MP3 encoding needs PyAV (libmp3lame); this env has none") |
| buf = io.BytesIO() |
| c = av.open(buf, "w", format="mp3") |
| st = c.add_stream("libmp3lame", rate=sr) |
| st.bit_rate = bitrate |
| st.bit_rate_tolerance = 0 |
| st.codec_context.layout = "mono" |
| x = np.clip(np.asarray(wav, dtype=np.float32), -1.0, 1.0) |
| x = (x * 32767.0).astype(np.int16).reshape(1, -1) |
| fr = av.AudioFrame.from_ndarray(x, format="s16", layout="mono") |
| fr.sample_rate = sr; fr.pts = 0 |
| for p in st.encode(fr): c.mux(p) |
| for p in st.encode(None): c.mux(p) |
| c.close() |
| return buf.getvalue() |
|
|
| def decode_mp3(b): |
| if not _HAVE_AV: |
| import soundfile as sf |
| x, sr = sf.read(io.BytesIO(b), dtype="float32") |
| if x.ndim > 1: x = x.mean(1) |
| return x.astype(np.float32), sr |
| c = av.open(io.BytesIO(b)) |
| st = c.streams.audio[0] |
| nch = st.channels or 1 |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| fr = [] |
| for f in c.decode(audio=0): |
| a = f.to_ndarray() |
| if nch > 1: |
| if a.ndim == 2 and a.shape[0] == nch: |
| a = a.mean(0) |
| else: |
| a = a.reshape(-1, nch).mean(1) |
| else: |
| a = a.reshape(-1) |
| fr.append(a) |
| sr = st.rate; c.close() |
| x = np.concatenate(fr) if fr else np.zeros(0, np.float32) |
| if x.dtype == np.int16: x = x.astype(np.float32)/32768.0 |
| return x.astype(np.float32), sr |
|
|