sam12345324 commited on
Commit
f7b44ba
·
verified ·
1 Parent(s): 278831f

Create utils.py

Browse files
Files changed (1) hide show
  1. utils.py +33 -0
utils.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import numpy as np
3
+ from io import BytesIO
4
+
5
+ def decode(base64_str: str) -> bytes:
6
+ binary_string = base64.b64decode(base64_str)
7
+ return binary_string
8
+
9
+ def pcm_to_wav(pcm_data: bytes, num_channels: int, sample_rate: int, bits_per_sample: int) -> bytes:
10
+ data_size = len(pcm_data)
11
+ buffer = bytearray(44 + data_size)
12
+ view = memoryview(buffer)
13
+
14
+ def write_string(offset: int, string: str):
15
+ for i, char in enumerate(string):
16
+ view[offset + i] = ord(char)
17
+
18
+ write_string(0, 'RIFF')
19
+ view[4:8] = (36 + data_size).to_bytes(4, 'little')
20
+ write_string(8, 'WAVE')
21
+ write_string(12, 'fmt ')
22
+ view[16:20] = (16).to_bytes(4, 'little')
23
+ view[20:22] = (1).to_bytes(2, 'little')
24
+ view[22:24] = num_channels.to_bytes(2, 'little')
25
+ view[24:28] = sample_rate.to_bytes(4, 'little')
26
+ view[28:32] = (sample_rate * num_channels * (bits_per_sample // 8)).to_bytes(4, 'little')
27
+ view[32:34] = (num_channels * (bits_per_sample // 8)).to_bytes(2, 'little')
28
+ view[34:36] = bits_per_sample.to_bytes(2, 'little')
29
+ write_string(36, 'data')
30
+ view[40:44] = data_size.to_bytes(4, 'little')
31
+ view[44:] = pcm_data
32
+
33
+ return bytes(buffer)