wangzhibo
2026-10-08 220e4fab27b7f419b3e89e2f2d28ae789aac09d7
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import struct
 
def decode_opus_from_file(input_file):
    """
    从p3文件中解码 Opus 数据,并返回一个 Opus 数据包的列表以及总时长。
    """
    opus_datas = []
    total_frames = 0
    sample_rate = 16000  # 文件采样率
    frame_duration_ms = 60  # 帧时长
    frame_size = int(sample_rate * frame_duration_ms / 1000)
 
    with open(input_file, 'rb') as f:
        while True:
            # 读取头部(4字节):[1字节类型,1字节保留,2字节长度]
            header = f.read(4)
            if not header:
                break
 
            # 解包头部信息
            _, _, data_len = struct.unpack('>BBH', header)
 
            # 根据头部指定的长度读取 Opus 数据
            opus_data = f.read(data_len)
            if len(opus_data) != data_len:
                raise ValueError(f"Data length({len(opus_data)}) mismatch({data_len}) in the file.")
 
            opus_datas.append(opus_data)
            total_frames += 1
 
    # 计算总时长
    total_duration = (total_frames * frame_duration_ms) / 1000.0
    return opus_datas, total_duration
 
def decode_opus_from_bytes(input_bytes):
    """
    从p3二进制数据中解码 Opus 数据,并返回一个 Opus 数据包的列表以及总时长。
    """
    import io
    opus_datas = []
    total_frames = 0
    sample_rate = 16000  # 文件采样率
    frame_duration_ms = 60  # 帧时长
    frame_size = int(sample_rate * frame_duration_ms / 1000)
 
    f = io.BytesIO(input_bytes)
    while True:
        header = f.read(4)
        if not header:
            break
        _, _, data_len = struct.unpack('>BBH', header)
        opus_data = f.read(data_len)
        if len(opus_data) != data_len:
            raise ValueError(f"Data length({len(opus_data)}) mismatch({data_len}) in the bytes.")
        opus_datas.append(opus_data)
        total_frames += 1
 
    total_duration = (total_frames * frame_duration_ms) / 1000.0
    return opus_datas, total_duration