File size: 1,024 Bytes
20459fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
"""resample.py IN.wav OUT.wav RATE [--mono]: resample a 16-bit wav with PyAV (libswresample)."""
import sys, wave
import numpy as np
import av

src, dst, rate = sys.argv[1], sys.argv[2], int(sys.argv[3])
mono = '--mono' in sys.argv
w = wave.open(src); sr, ch = w.getframerate(), w.getnchannels()
x = np.frombuffer(w.readframes(w.getnframes()), dtype='<i2').reshape(-1, ch)
layout_in = 'stereo' if ch == 2 else 'mono'
layout_out = 'mono' if mono else layout_in
frame = av.AudioFrame.from_ndarray(x.reshape(1, -1).copy(), format='s16', layout=layout_in)
frame.sample_rate = sr
rs = av.AudioResampler(format='s16', layout=layout_out, rate=rate)
chunks = [f.to_ndarray() for f in rs.resample(frame)] + [f.to_ndarray() for f in rs.resample(None)]
y = np.concatenate(chunks, axis=1).reshape(-1)
out = wave.open(dst, 'wb'); out.setnchannels(1 if mono else ch); out.setsampwidth(2); out.setframerate(rate)
out.writeframes(y.astype('<i2').tobytes()); out.close()
print(f"{dst}: {len(y) // (1 if mono else ch) / rate:.2f}s @ {rate}")