js获取本地或网络mp3音乐时长的2种方式
项目中我们可能要读取本地或网络mp3音乐声音的时长,怎么办,有2种方式可以获取
一、Audio标签
获取音频文件持续时间的最简单方法是通过嵌入音频标记,用于在文档中嵌入声音内容。它可能包含一个或多个音频源,使用src属性或嵌套在音频标记上的<source>元素表示。
<!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.addEventLi...
点击查看剩余70%
网友评论0