Spaces:
Running
Running
Upload audio.py
Browse files- lib/vc/audio.py +73 -0
lib/vc/audio.py
ADDED
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import traceback
|
3 |
+
|
4 |
+
import librosa
|
5 |
+
import numpy as np
|
6 |
+
import av
|
7 |
+
from io import BytesIO
|
8 |
+
|
9 |
+
|
10 |
+
def wav2(i, o, format):
|
11 |
+
inp = av.open(i, "rb")
|
12 |
+
if format == "m4a":
|
13 |
+
format = "mp4"
|
14 |
+
out = av.open(o, "wb", format=format)
|
15 |
+
if format == "ogg":
|
16 |
+
format = "libvorbis"
|
17 |
+
if format == "mp4":
|
18 |
+
format = "aac"
|
19 |
+
|
20 |
+
ostream = out.add_stream(format)
|
21 |
+
|
22 |
+
for frame in inp.decode(audio=0):
|
23 |
+
for p in ostream.encode(frame):
|
24 |
+
out.mux(p)
|
25 |
+
|
26 |
+
for p in ostream.encode(None):
|
27 |
+
out.mux(p)
|
28 |
+
|
29 |
+
out.close()
|
30 |
+
inp.close()
|
31 |
+
|
32 |
+
|
33 |
+
def audio2(i, o, format, sr):
|
34 |
+
inp = av.open(i, "rb")
|
35 |
+
out = av.open(o, "wb", format=format)
|
36 |
+
if format == "ogg":
|
37 |
+
format = "libvorbis"
|
38 |
+
if format == "f32le":
|
39 |
+
format = "pcm_f32le"
|
40 |
+
|
41 |
+
ostream = out.add_stream(format, channels=1)
|
42 |
+
ostream.sample_rate = sr
|
43 |
+
|
44 |
+
for frame in inp.decode(audio=0):
|
45 |
+
for p in ostream.encode(frame):
|
46 |
+
out.mux(p)
|
47 |
+
|
48 |
+
out.close()
|
49 |
+
inp.close()
|
50 |
+
|
51 |
+
|
52 |
+
def load_audio(file, sr):
|
53 |
+
file = (
|
54 |
+
file.strip(" ").strip('"').strip("\n").strip('"').strip(" ")
|
55 |
+
) # 防止小白拷路径头尾带了空格和"和回车
|
56 |
+
if os.path.exists(file) == False:
|
57 |
+
raise RuntimeError(
|
58 |
+
"You input a wrong audio path that does not exists, please fix it!"
|
59 |
+
)
|
60 |
+
try:
|
61 |
+
with open(file, "rb") as f:
|
62 |
+
with BytesIO() as out:
|
63 |
+
audio2(f, out, "f32le", sr)
|
64 |
+
return np.frombuffer(out.getvalue(), np.float32).flatten()
|
65 |
+
|
66 |
+
except AttributeError:
|
67 |
+
audio = file[1] / 32768.0
|
68 |
+
if len(audio.shape) == 2:
|
69 |
+
audio = np.mean(audio, -1)
|
70 |
+
return librosa.resample(audio, orig_sr=file[0], target_sr=16000)
|
71 |
+
|
72 |
+
except:
|
73 |
+
raise RuntimeError(traceback.format_exc())
|