You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python调用ExifTool处理音频字节流时缺失文件元数据的问题咨询

Python调用ExifTool处理音频字节流时缺失文件元数据的问题咨询

我最近遇到一个困扰:用Python读取音频文件的字节流后,通过subprocess调用ExifTool提取元数据,结果里缺了文件名、文件大小、修改/访问/创建时间这些关键信息,但直接在命令行用ExifTool处理原文件时就能拿到完整数据。

先贴一下相关代码和输出,方便大家理解问题:

定义的Metadata枚举和处理方法

from enum import Enum
from typing import Literal
import subprocess

class Metadata(Enum):
    bit_rate_kbps: int
    sample_rate: int
    channel_mode: Literal['mono', 'audio']
    file_name: str # includes extension
    file_size: int # mb
    file_ext: Literal['wav']

    @classmethod
    def get_metadata_from_bytes(cls, audio: bytes):

        command = ['exiftool', '-json', '-']
        try:
            # Start the exiftool process
            process = subprocess.Popen(
                command,
                stdin=subprocess.PIPE,  # Pass data via stdin
                stdout=subprocess.PIPE,  # Capture stdout
                stderr=subprocess.PIPE,   # Capture stderr
            )

            # Send the bytes to exiftool and capture output
            stdout, stderr = process.communicate(input=audio)

            if process.returncode == 0:
                print("Exiftool Output (Bytes):")
                print(stdout.decode('utf-8'))  # Decode output to text
            else:
                print("Exiftool Error (Bytes):")
                error_message = stderr.decode('utf-8')  # Decode errors to text
                raise RuntimeError(f"Exiftool failed with error: {error_message}")

        except FileNotFoundError:
            print("Error: exiftool is not installed or not in the system PATH.")
        except RuntimeError as e:
            print(f"Subprocess Error: {e}")
        except Exception as e:
            print(f"Unexpected Error: {e}")

调用方法后的输出

[{
  "SourceFile": "-",
  "ExifToolVersion": 13.10,
  "FileModifyDate": "0000:00:00 00:00:00",
  "FileAccessDate": "0000:00:00 00:00:00",
  "FileCreateDate": "0000:00:00 00:00:00",
  "FilePermissions": "p---------",
  "FileType": "MP3",
  "FileTypeExtension": "mp3",
  "MIMEType": "audio/mpeg",
  "MPEGAudioVersion": 1,
  "AudioLayer": 3,
  "AudioBitrate": "64 kbps",
  "SampleRate": 48000,
  "ChannelMode": "Stereo",
  "MSStereo": "Off",
  "IntensityStereo": "Off",
  "CopyrightFlag": false,
  "OriginalMedia": false,
  "Emphasis": "None",
  "ID3Size": 313,
  "EncoderSettings": "Lavf61.7.100"
}]

直接命令行处理原文件的输出(生成的original_sample.txt)

ExifTool Version Number         : 13.10
File Name                       : original_sample.mp3
Directory                       : .
File Size                       : 25 MB
File Modification Date/Time     : 2024:12:28 05:57:46+01:00
File Access Date/Time           : 2024:12:31 20:31:54+01:00
File Creation Date/Time         : 2024:12:31 19:06:31+01:00
File Permissions                : -rw-rw-rw-
File Type                       : MP3
File Type Extension             : mp3
MIME Type                       : audio/mpeg
MPEG Audio Version              : 1
Audio Layer                     : 3
Audio Bitrate                   : 64 kbps
Sample Rate                     : 48000
Channel Mode                    : Stereo
MS Stereo                       : Off
Intensity Stereo                : Off
Copyright Flag                  : False
Original Media                  : False
Emphasis                        : None
ID3 Size                        : 313
Encoder Settings                : Lavf61.7.100
Duration                        : 0:51:22 (approx)

我读取文件的方式

def test_get_metadata_from_bytes():
    with open('test/polyvoice/original_sample.mp3', 'rb') as file:
        file_bytes = file.read()
        metadata = Metadata.get_metadata_from_bytes(file_bytes)
        assert True

我怀疑是不是open()读取字节流的时候,把文件本身的系统元数据(比如修改日期、访问日期这些)给丢掉了?另外我也试过在Python调用ExifTool时指定-FileName、-FileSize这些参数,但输出还是只有那些本来就能拿到的字段,没新增缺失的内容。有没有大佬能帮忙解释下原因,或者给个解决思路呀?

备注:内容来源于stack exchange,提问作者Dani Baba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 12:04:51