js获取本地或网络mp3音乐时长的2种方式

js获取本地或网络mp3音乐时长的2种方式

js获取本地或网络mp3音乐时长的2种方式

项目中我们可能要读取本地或网络mp3音乐声音的时长,怎么办,有2种方式可以获取

一、Audio标签

获取音频文件持续时间的最简单方法是通过嵌入音频标记,用于在文档中嵌入声音内容。它可能包含一个或多个音频源,使用src属性或嵌套在音频标记上的<source>元素表示。

1、获取本地

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>BFW NEW PAGE</title>


    <style>
    </style>
</head>
<body>
    <input type="file" id="fileinput" />
    <script type="text/javascript">
      
// Create a non-dom allocated Audio element
var audio = document.createElement('audio');

// Add a change event listener to the file input
document.getElementById("fileinput").addEventListener('change', function(event){
    var target = event.currentTarget;
    var file = target.files[0];
    var reader = new FileReader();
  
    if (target.files && file) {
        var reader = new FileReader();

        reader.onload = function (e) {
            audio.src = e.target.result;
            audio.addEventListener('loadedmetadata', function(){
                // Obtain the duration in seconds of the audio file (with milliseconds as well, a float value)
                var duration = audio.duration;
            
                // example 12.3234 seconds
               alert("这段音乐的时长诶" + duration + " 秒");
                // Alternatively, just display the integer value with
                // parseInt(duration)
                // 12 seconds
            },false);
        };

        reader.readAsDataURL(file);
    }
}, false); 
    </script>
</body>
</html>

2、获取网络

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>BFW NEW PAGE</title>

    <script type="text/javascript">

        // Create an instance of AudioContext
        var au = document.createElement('audio');

        // Define the URL of the MP3 audio file
        au.src = "http://repo.bfw.wiki/bfwrepo/sound/5c89fd22dea6948307.mp3";

        // Once the metadata has been loaded, display the duration in the console
        au.addEventListener('loadedmetadata', function() {
            // Obtain the duration in seconds of the audio file (with milliseconds as well, a float value)
            var duration = au.duration;

            // example 12.3234 seconds
             alert("这段音乐的时长诶" + duration + " 秒");
            // Alternatively, just display the integer value with
            // parseInt(duration)
            // 12 seconds
        }, false);

    </script>

</head>
<body>

</body>
</html>

二、JS AudioContext

这个api比较直接,方便,推荐使用,在读取文件之前要创建audioContext

1、本地

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>BFW NEW PAGE</title>


    <style>
    </style>
</head>
<body>
    <input type="file" id="fileinput" />
    <script type="text/javascript">
        document.getElementById("fileinput").addEventListener('change', function() {

            // Obtain the uploaded file, you can change the logic if you are working with multiupload
            var file = this.files[0];

            // Create instance of FileReader
            var reader = new FileReader();

            // When the file has been succesfully read
            reader.onload = function (event) {

                // Create an instance of AudioContext
                var audioContext = new (window.AudioContext || window.webkitAudioContext)();

                // Asynchronously decode audio file data contained in an ArrayBuffer.
                audioContext.decodeAudioData(event.target.result, function(buffer) {
                    // Obtain the duration in seconds of the audio file (with milliseconds as well, a float value)
                    var duration = buffer.duration;

                    // example 12.3234 seconds
                   alert("这段音乐的时长诶" + duration + " 秒");
                    // Alternatively, just display the integer value with
                    // parseInt(duration)
                    // 12 seconds
                });
            };

            // In case that the file couldn't be read
            reader.onerror = function (event) {
                console.error("An error ocurred reading the file: ", event);
            };

            // Read file as an ArrayBuffer, important !
            reader.readAsArrayBuffer(file);
        }, false);
    </script>
</body>
</html>


2、网络

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>BFW NEW PAGE</title>

    <script type="text/javascript">
       
            // Request URL of the Audio File
            var mp3file = "http://repo.bfw.wiki/bfwrepo/sound/5c89fd22dea6948307.mp3";

            // Create an instance of AudioContext
            var audioContext = new (window.AudioContext || window.webkitAudioContext)();

            // Open an Http Request
            var request = new XMLHttpRequest();
            request.open('GET', mp3file, true);
            request.responseType = 'arraybuffer';
            request.onload = function() {
                audioContext.decodeAudioData(request.response, function(buffer) {
                    // Obtain the duration in seconds of the audio file (with milliseconds as well, a float value)
                    var duration = buffer.duration;

                    // example 12.3234 seconds
                    alert("这段音乐的时长诶" + duration + " 秒");
                    // Alternatively, just display the integer value with
                    // parseInt(duration)
                    // 12 seconds
                });
            };

            // Start Request
            request.send();
      
    </script>
   
</head>
<body>

</body>
</html>


{{collectdata}}

网友评论0