这样分割mp3文件安全吗?

问题描述 投票:0回答:1

我有一个

mp3
文件,想将其分成几个文件(“块”)。我想出了这段代码(我从 django 那里偷来了这个想法):

from pathlib import Path


class FileWrapper:
    def __init__(self, file) -> None:
        self.file = file

    def chunks(self, chunk_size):
        chunk_size = chunk_size
        try:
            self.file.seek(0)
        except (AttributeError, Exception):
            pass

        while True:
            data = self.file.read(chunk_size)
            if not data:
                break
            yield data


with open("./test2.mp3", "rb+") as src:
    wrapper_file = FileWrapper(src)
    for chunk_ind, chunk in enumerate(wrapper_file.chunks(chunk_size=100 * 1024)):
        out_file_path = Path("./", f"test2_{chunk_ind}.mp3")
        with open(out_file_path, "wb+") as destination:
            destination.write(chunk)

而且,你知道,它工作正常,但我很害怕并且怀疑,这种方法有时可以工作,但有时它可能会“刹车”导致“块”。那么,这样可以吗?或者我需要更深入地了解

mp3
文件是如何制作的?

python django
1个回答
1
投票

从技术上讲,您以块的形式读取 MP3 文件并将其分割的方法是可行的,但它可能会产生损坏或不足的音频部分。某些结构(例如帧和标头)被编码在 MP3 文件中,在切片时必须观察它们。简单地将 MP3 分割成字节大小的片段可能会损害音频的完整性,这可能会导致帧减半等问题。

使用

pydub
库是一种更可靠的分割 MP3 文件的方法,该库专为在更高级别处理音频文件而设计,并为您处理编码细节。

© www.soinside.com 2019 - 2024. All rights reserved.