[英]How to get the size and duration of an mp3 file?
我需要計算一個 mp3 文件的總長度。
目前我正在使用一個 PHP 類,我發現它 @ http://www.zedwood.com/article/php-calculate-duration-of-mp3 。
如果 mp3 文件在同一服務器中,這將完美運行。
但是如果我有來自其他站點的 URL,它會拋出錯誤。 請幫我。
是否有任何 JavaScript J-Query 函數來獲取 mp3 文件的長度
<?php include("mp3.class.php");
$f = 'http://cdn.enjoypur.vc/upload_file/5570/5738/5739/7924/Blue%20Eyes%20-%20Yo%20Yo%20Honey%20Singh%20(PagalWorld.com)%20-192Kbps%20.mp3';
$m = new mp3file($f);
$a = $m->get_metadata();
if ($a['Encoding']=='Unknown')
echo "?";
else if ($a['Encoding']=='VBR')
print_r($a);
else if ($a['Encoding']=='CBR')
print_r($a);
unset($a);
?>
以下是使用 Web Audio API 獲取 mp3 時長的方法:
const mp3file = 'https://raw.githubusercontent.com/prof3ssorSt3v3/media-sample-files/master/doorbell.mp3' const audioContext = new (window.AudioContext || window.webkitAudioContext)() const request = new XMLHttpRequest() request.open('GET', mp3file, true) request.responseType = 'arraybuffer' request.onload = function() { audioContext.decodeAudioData(request.response, function(buffer) { let duration = buffer.duration console.log(duration) document.write(duration) } ) } request.send()
實際上有一個可以在客戶端運行的庫,試圖獲取足夠的 MP3 來讀取 ID3 標簽:
http://github.com/aadsm/JavaScript-ID3-Reader
或
試試
HTML 文件 API。
也許最簡單的解決方案是使用音頻 html 元素來獲取持續時間並直接從 FileReader 對象返回的文件中獲取大小。 這種方法的代碼示例如下所示。
一個不利的一面是目前為止提出的所有其他解決方案是音頻標簽的 durationchanged 事件在加載大文件(例如 > 200MB 文件)時觸發所需的 10-20 秒延遲。 顯然,有一種更快的方法可以獲取此信息,因為當文件作為 file:///.... URL 輸入瀏覽器時,會立即顯示持續時間。
function checkMp3SizeAndDuration()
{
var files = document.getElementById('upload-file').files;
var file = files[0];
if (file.size > MAX_FILE_SIZE) {
return;
}
var reader = new FileReader();
var audio = document.createElement('audio');
reader.onload = function (e) {
audio.src = e.target.result
audio.addEventListener('durationchange', function() {
console.log("durationchange: " + audio.duration);
},false);
audio.addEventListener('onerror', function() {
alert("Cannot get duration of this file.");
}, false);
};
reader.readAsDataURL(file);
});
由於無法找到快速且不需要一堆額外樣板代碼的東西,我調整了現有的服務器端 javascript 實用程序以直接在瀏覽器中運行。 演示代碼位於: https : //github.com/eric-gilbertson/fast-mp3-duration
一個非常有名的SPI,可以使用MP3 SPI ,代碼也很簡單
File file = new File("filename.mp3");
AudioFileFormat baseFileFormat = AudioSystem.getAudioFileFormat(file);
Map properties = baseFileFormat.properties();
Long duration = (Long) properties.get("duration");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.