LoginSignup
2
4

More than 3 years have passed since last update.

mp3ファイルの再生時間をpythonで計測する方法

Posted at

mp3ファイルの持続時間を取得する方法は2つあります。
一つは mutagenを使用する方法で、もう一つはpysoxを使用する方法です。
それぞれの方法には長所と短所があります。

mutagenを使った方法は、pysoxを使った方法よりも軽量で高速です。

mutagenはmp3ファイルのID3タグをチェックするだけなのはそのためです。一方、pysoxはSox CLIを使ってmp3ファイルのバイナリをチェックするようです。

pysoxの方法では、ID3情報を使わずに持続時間を判定する、つまりID3情報が無効なファイルや、ID3情報がないファイルを認識することができます。pysoxを使うことで、ID3情報を使わずにデュレーションを調べることができる、つまり、ID3情報が無効なファイルや、ID3情報がないファイルのデュレーションを検出することができます。

mutagenを使う方法

from mutagen.mp3 import MP3

def mutagen_length(path):
    try:
        audio = MP3(path)
        length = audio.info.length
        return length
    except:
        return None

length = mutagen_length(wav_path)
print("duration sec: " + str(length))
print("duration min: " + str(int(length/60)) + ':' + str(int(length%60)))

pysox を使う方法

Note: pysox needs SOX cli.

import sox

def sox_length(path):
    try:
        length = sox.file_info.duration(path)
        return length
    except:
        return None

length = sox_length(mp3_path)

print("duration sec: " + str(length))
print("duration min: " + str(int(length/60)) + ':' + str(int(length%60)))
2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4