一个mp3文件的时长

19

如何在不使用外部库的情况下确定给定 mp3 文件的长度(以秒为单位)?(高度赞赏 Python 代码)


5
在资源管理器中打开包含文件夹,显示播放时间列,截图,进行OCR文字识别,文本搜索......提交到"The Daily WTF/joke"。 - BCS
6个回答

26

你可以使用pymad。它是一个外部库,但不要陷入“非自己开发”的陷阱。你不想使用外部库的特定原因吗?

import mad

mf = mad.MadFile("foo.mp3")
track_length_in_milliseconds = mf.total_time()    

在这里发现 这里.

--

如果您真的不想使用外部库,请看看此处并查看他如何完成。警告:这很复杂。


我同意推荐使用外部库。我从未使用过它(或Python)。但我曾尝试用C++编写一个能简单播放MP3的程序。那并没有成功,但我已足够了解文件的长度。我考虑重新设计那段代码... - Matt Blaine
这里有一个帖子,但是非常复杂。(而且是用 C++ 而不是 Python)。一点也不简单。 - Matt Blaine
1
提醒一下,据我观察,它只适用于某些平台。最新版本在安装时会崩溃,因为缺少其中一个设置文件,它建议我通过运行第二个带有Linux命令的文件来生成该文件。 - trevorKirkby

11
为了谷歌的追随者们,这里有一些更多的外部库:
- mpg321 -t - ffmpeg -i - midentify(基本上是mplayer)参见使用mplayer确定音频/视频文件的长度 - mencoder(传递无效参数,它会输出错误消息,但也会给出有关所讨论文件的信息,例如 $ mencoder inputfile.mp3 -o fake) - mediainfo程序 http://mediainfo.sourceforge.net/en - exiftool - Linux的"file"命令 - mp3info - sox
参考资料:

(将此设为维基页面,供其他人添加内容)。

还有一些库:.net: naudio, java: jlayer, c: libmad

干杯!


这些ffmpeg和mpg321也可以处理http链接作为文件位置,不幸的是后者会自动播放文件,但我对ffmpeg非常满意 :) - Kami

8

使用Python解析MP3二进制数据以计算某些内容

听起来似乎是一个很高的要求。我不懂Python,但这里有一些代码,它是从我曾经尝试编写的另一个程序中重构出来的。

注意: 这是C++代码(抱歉,这是我拥有的语言)。而且,原样情况下,它只能处理恒定比特率的MPEG 1音频层3文件。这应该涵盖大多数情况,但我不能保证在所有情况下都能正常工作。希望这能满足您的需求,并且希望将其重构为Python比从头开始更容易。

// determines the duration, in seconds, of an MP3;
// assumes MPEG 1 (not 2 or 2.5) Audio Layer 3 (not 1 or 2)
// constant bit rate (not variable)

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

//Bitrates, assuming MPEG 1 Audio Layer 3
const int bitrates[16] = {
         0,  32000,  40000,  48000,  56000,  64000,  80000,   96000,
    112000, 128000, 160000, 192000, 224000, 256000, 320000,       0
  };


//Intel processors are little-endian;
//search Google or see: http://en.wikipedia.org/wiki/Endian
int reverse(int i)
{
    int toReturn = 0;
    toReturn |= ((i & 0x000000FF) << 24);
    toReturn |= ((i & 0x0000FF00) << 8);
    toReturn |= ((i & 0x00FF0000) >> 8);
    toReturn |= ((i & 0xFF000000) >> 24);
    return toReturn;
}

//In short, data in ID3v2 tags are stored as
//"syncsafe integers". This is so the tag info
//isn't mistaken for audio data, and attempted to
//be "played". For more info, have fun Googling it.
int syncsafe(int i)
{
 int toReturn = 0;
 toReturn |= ((i & 0x7F000000) >> 24);
 toReturn |= ((i & 0x007F0000) >>  9);
 toReturn |= ((i & 0x00007F00) <<  6);
 toReturn |= ((i & 0x0000007F) << 21);
 return toReturn;     
}

//How much room does ID3 version 1 tag info
//take up at the end of this file (if any)?
int id3v1size(ifstream& infile)
{
   streampos savePos = infile.tellg(); 

   //get to 128 bytes from file end
   infile.seekg(0, ios::end);
   streampos length = infile.tellg() - (streampos)128;
   infile.seekg(length);

   int size;
   char buffer[3] = {0};
   infile.read(buffer, 3);
   if( buffer[0] == 'T' && buffer[1] == 'A' && buffer[2] == 'G' )
     size = 128; //found tag data
   else
     size = 0; //nothing there

   infile.seekg(savePos);

   return size;

}

//how much room does ID3 version 2 tag info
//take up at the beginning of this file (if any)
int id3v2size(ifstream& infile)
{
   streampos savePos = infile.tellg(); 
   infile.seekg(0, ios::beg);

   char buffer[6] = {0};
   infile.read(buffer, 6);
   if( buffer[0] != 'I' || buffer[1] != 'D' || buffer[2] != '3' )
   {   
       //no tag data
       infile.seekg(savePos);
       return 0;
   }

   int size = 0;
   infile.read(reinterpret_cast<char*>(&size), sizeof(size));
   size = syncsafe(size);

   infile.seekg(savePos);
   //"size" doesn't include the 10 byte ID3v2 header
   return size + 10;
}

int main(int argCount, char* argValues[])
{
  //you'll have to change this
  ifstream infile("C:/Music/Bush - Comedown.mp3", ios::binary);

  if(!infile.is_open())
  {
   infile.close();
   cout << "Error opening file" << endl;
   system("PAUSE");
   return 0;
  }

  //determine beginning and end of primary frame data (not ID3 tags)
  infile.seekg(0, ios::end);
  streampos dataEnd = infile.tellg();

  infile.seekg(0, ios::beg);
  streampos dataBegin = 0;

  dataEnd -= id3v1size(infile);
  dataBegin += id3v2size(infile);

  infile.seekg(dataBegin,ios::beg);

  //determine bitrate based on header for first frame of audio data
  int headerBytes = 0;
  infile.read(reinterpret_cast<char*>(&headerBytes),sizeof(headerBytes));

  headerBytes = reverse(headerBytes);
  int bitrate = bitrates[(int)((headerBytes >> 12) & 0xF)];

  //calculate duration, in seconds
  int duration = (dataEnd - dataBegin)/(bitrate/8);

  infile.close();

  //print duration in minutes : seconds
  cout << duration/60 << ":" << duration%60 << endl;

  system("PAUSE");
  return 0;
}

1
这对我现在正在构建的某些东西非常完美,因为我不需要VBR支持。我所需要改变的只是比特率,因为它假定文件是32k(从LAME输出),而实际上是56k。 - alxp

7

只需使用mutagen

$pip install mutagen

在Python shell中使用:

from mutagen.mp3 import MP3
audio = MP3(file_path)
print audio.info.length

最佳答案。它可以通过PIP轻松安装,无需其他要求,仅提供存储在文件元数据中的信息。 - Zvika

3
此外,您还可以查看audioread(一些Linux发行版,包括Ubuntu,已有软件包),https://github.com/sampsyo/audioread
audio = audioread.audio_open('/path/to/mp3')
print audio.channels, audio.samplerate, audio.duration

0

您可以计算文件中帧的数量。每个帧都有一个起始码,尽管我无法回忆起起始码的确切值,也没有MPEG规格放在手边。每个帧都有一定的长度,对于MPEG1第二层来说大约为40ms。

这种方法适用于CBR文件(恒定比特率),而VBR文件的工作方式则完全不同。

从下面的文档中:

对于第 I 层文件,请使用以下公式:

FrameLengthInBytes = (12 * BitRate / SampleRate + Padding) * 4

对于第 II 和 III 层文件,请使用以下公式:

FrameLengthInBytes = 144 * BitRate / SampleRate + Padding

有关MPEG音频帧头的信息


我认为长度是26毫秒。 - Ori Pessach

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接