How to get the size and duration of an mp3 file?

前端 未结 6 885
夕颜
夕颜 2021-01-12 07:13

I need to calculate the total length of an mp3 file.

Currently I am using a PHP class which I found @ http://www.zedwood.com/article/php-calculate-duration-of-mp3.

6条回答
  •  借酒劲吻你
    2021-01-12 07:19

    Perhaps the simplest solution is to use the audio html element to get the time duration and to obtain the size directly from the file returned by the FileReader object. A code example of this approach is shown below.

    One down side of this and all the other solutions presented so far is the 10-20 second delay it takes for the audio tag's durationchanged event to fire when loading large, eg > 200MB files. Clearly there is a faster way to get this info because the duration is shown immediately when the file is entered into the browser as a 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);
    });
    

提交回复
热议问题