擅长:python、mysql、java
<p>我建议使用FFprobe(附带FFmpeg)。</p>
<p>查马斯给出的答案非常接近,但最终对我来说失败了。</p>
<p>如前所述,我使用的是Python3.5和3.6,这对我很有用。</p>
<pre><code>import subprocess
def get_duration(file):
"""Get the duration of a video using ffprobe."""
cmd = 'ffprobe -i {} -show_entries format=duration -v quiet -of csv="p=0"'.format(file)
output = subprocess.check_output(
cmd,
shell=True, # Let this run in the shell
stderr=subprocess.STDOUT
)
# return round(float(output)) # ugly, but rounds your seconds up or down
return float(output)
</code></pre>
<p>如果你想把这个函数放到一个类中,并在Django(1.8-1.11)中使用它,只需改变一行,然后把这个函数放到你的类中,如下所示:</p>
<pre><code>def get_duration(file):
</code></pre>
<p>致:</p>
<pre><code>def get_duration(self, file):
</code></pre>
<p><strong>注意:</strong>使用相对路径在本地对我有效,但生产服务器需要绝对路径。您可以使用<code>os.path.abspath(os.path.dirname(file))</code>获取视频或音频文件的路径。</p>