File size: 1,196 Bytes
f7b44ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import base64
import numpy as np
from io import BytesIO

def decode(base64_str: str) -> bytes:
    binary_string = base64.b64decode(base64_str)
    return binary_string

def pcm_to_wav(pcm_data: bytes, num_channels: int, sample_rate: int, bits_per_sample: int) -> bytes:
    data_size = len(pcm_data)
    buffer = bytearray(44 + data_size)
    view = memoryview(buffer)

    def write_string(offset: int, string: str):
        for i, char in enumerate(string):
            view[offset + i] = ord(char)

    write_string(0, 'RIFF')
    view[4:8] = (36 + data_size).to_bytes(4, 'little')
    write_string(8, 'WAVE')
    write_string(12, 'fmt ')
    view[16:20] = (16).to_bytes(4, 'little')
    view[20:22] = (1).to_bytes(2, 'little')
    view[22:24] = num_channels.to_bytes(2, 'little')
    view[24:28] = sample_rate.to_bytes(4, 'little')
    view[28:32] = (sample_rate * num_channels * (bits_per_sample // 8)).to_bytes(4, 'little')
    view[32:34] = (num_channels * (bits_per_sample // 8)).to_bytes(2, 'little')
    view[34:36] = bits_per_sample.to_bytes(2, 'little')
    write_string(36, 'data')
    view[40:44] = data_size.to_bytes(4, 'little')
    view[44:] = pcm_data

    return bytes(buffer)