【问题标题】:python check audio file type, MP3 or FLACpython 检查音频文件类型,MP3 或 FLAC
【发布时间】:2015-07-31 02:14:07
【问题描述】:

我想检查音频文件是否是 MP3 或 FLAC

os.path.splitext

如果文件没有写入扩展名或有人传递带有假扩展名的文件,则可以正常工作,但没有好处

我试过了,但它只是返回 None

sndhdr.what(file)

我也尝试过使用魔法,但它返回的 'application/octet-stream' 并没有多大用处。

magic.from_file(file, mime=True)

我读过 Mutagen 可能对此有好处,但到目前为止找不到任何将音频编码输出为 MP3 或 FLAC 的函数

【问题讨论】:

    标签: python audio mp3 flac


    【解决方案1】:

    试试图书馆filetypefiletype on pypifiletype on github.

    (另一个答案提到fleep。我试过了。但不幸的是,它看起来不再维护了。它不能识别所有类型的mp3,例如。filetype 正在积极维护并识别所有 mp3 格式)

    安装文件类型

    pip install filetype
    

    使用文件类型来识别您的文件。它使用文件签名,即文件开头的魔术字节。

    import filetype
    
    kind = filetype.guess('path/to/sample.mp3')
    if kind is None:
        print('Cannot guess file type!')
    else:
        print('File extension: %s' % kind.extension)
        print('File MIME type: %s' % kind.mime)
    
    

    注意,有一个问题

    似乎filetype repo 在积极维护的同时发布速度很慢。我在 GitHub 上提出了一个关于缓慢发布的问题 here

    这意味着要获取库的新位(例如要匹配的更多文件签名),您可能希望直接从 git repo 安装。

    用 pip 做到这一点:

    pip install -e git+https://github.com/h2non/filetype.py
    

    用 pipenv 做到这一点:

    pipenv install -e git+https://github.com/h2non/filetype.py#egg=filetype
    

    -e 表示以可编辑模式安装。这是here 的建议。)

    【讨论】:

      【解决方案2】:

      要查找包括音频、视频、txt 等在内的文件格式,您可以使用 fleeppython库查看音频文件格式:

      首先你需要安装库:

      pip install fleep
      

      这是一个测试代码:

      import fleep
      
      with open("vida.flac", "rb") as file:
          info = fleep.get(file.read(128))
      
      print(info.type)
      print(info.extension)
      print(info.mime) 
      

      结果如下:

      ['audio']
      ['flac']
      ['audio/flac']
      

      即使文件没有扩展名或有人传递带有假扩展名的文件,它也会检测并返回。

      这里我已经将 vida.wav 文件复制到 dar.txt 并删除了扩展名

      import fleep
      
      with open("dar", "rb") as file:
          info = fleep.get(file.read(128))
      
      print(info.type)
      print(info.extension) 
      print(info.mime) 
      

      结果还是一样。

      ['audio']
      ['flac']
      ['audio/flac']
      

      感谢图书馆的作者 https://github.com/floyernick/fleep-py

      【讨论】:

        【解决方案3】:

        您可以读取 mp3 和 flac 的文件规范,然后可以实现一个检查器,将 mp3 读取和解析为二进制文件。具有类似目标的可修改示例是 here

        【讨论】:

          【解决方案4】:

          这可能会帮助您入门

          21.9。 sndhdr — 确定声音文件的类型

          https://docs.python.org/2/library/sndhdr.html

          【讨论】:

          • 我之前确实看过这个,但是当通过它时,我的测试 mp3 文件 sndhdr.what(file) 它没有返回
          • sndhdr 仅适用于某些文件格式:The value for type indicates the data type and will be one of the strings 'aifc', 'aiff', 'au', 'hcom', 'sndr', 'sndt', 'voc', 'wav', '8svx', 'sb', 'ub', or 'ul'. src: [docs.python.org/3.5/library/sndhdr.html]
          猜你喜欢
          • 2012-10-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-05-31
          • 2015-03-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多