duração do tempo de um arquivo mp3
Pergunta
O que é a maneira mais simples para determinar o comprimento (em segundos) de um determinado arquivo mp3, sem usar bibliotecas externas ? (Fonte python muito apreciada)
Solução
Você pode usar pymad . É uma biblioteca externa, mas não caia na armadilha não foi inventado aqui. Alguma razão especial que você não quer quaisquer bibliotecas externas?
import mad
mf = mad.MadFile("foo.mp3")
track_length_in_milliseconds = mf.total_time()
aqui .
-
Se você realmente não quiser usar uma biblioteca externa, dê uma olhada aqui e verificação a forma como ele fez isso. Aviso:. É complicado
Outras dicas
Por amor google seguidores, aqui estão algumas libs mais externos:
mpg321 -t
ffmpeg -i
midentify (mplayer basicamente) ver com o MPlayer para determinar o comprimento de arquivo de áudio / vídeo
mencoder (passá-lo parâmetros inválidos, ele vai cuspir uma mensagem de erro, mas também dar-lhe informações sobre o arquivo em questão, ex $ mencoder inputfile.mp3 -o falso)
mediainfo programa http://mediainfo.sourceforge.net/en
exiftool
o linux comando "file"
mp3info
sox
refs: https://superuser.com/questions/36871/linux-command- linha-utilidade-to-determinar-mp3 bitrate
http://www.ruby-forum.com/topic/139468
comprimento mp3 em milissegundos
(tornando este um wiki para que outros possam adicionar).
e libs: NET: NAudio, java: JLayer, c: libmad
Felicidades!
Simples, MP3 análise blob binário para calcular alguma coisa, em Python
Isso soa como uma tarefa bem difícil. Eu não sei Python, mas aqui está um código que eu reformulado a partir de outro programa, uma vez eu tentei escrever.
Nota: É em C ++ (desculpe, é o que eu tenho). Além disso, tal como está, ele vai apenas lidar com taxa de bits constante MPEG 1 Audio Layer 3 arquivos. Que deve cobertura mais, mas eu não posso dar nenhuma garantia quanto a este trabalho em todas as situações. Esperemos que este faz o que quiser, e espero que refatoração-lo em Python é mais fácil do que fazê-lo a partir do zero.
// 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;
}
simplesmente usar mutagen
$pip install mutagen
usá-lo em shell python:
from mutagen.mp3 import MP3
audio = MP3(file_path)
print audio.info.length
Também dê uma olhada audioread (algumas distribuições Linux, incluindo o Ubuntu têm pacotes), https://github.com/ sampsyo / audioread
audio = audioread.audio_open('/path/to/mp3')
print audio.channels, audio.samplerate, audio.duration
Você pode contar o número de quadros no arquivo. Cada quadro tem um código de início, embora eu não posso lembrar o valor exato do código de início e eu não tenho MPEG especificações, que ao redor. Cada trama tem um certo comprimento, cerca de 40 ms para a camada MPEG1 II.
Este método funciona para CBR-arquivos (Constant Bit Rate), como VBR-arquivos de trabalho é uma história completamente diferente.
A partir do documento abaixo:
Para Camada I arquivos nos esta fórmula:
FrameLengthInBytes = (12 * BitRate / SampleRate + Enchimento) * 4
Para Camada II & III arquivos usar esta fórmula:
FrameLengthInBytes = 144 * BitRate / SampleRate + Padding