如何使用JavaScript在浏览器中检索MP3 / WAV音频文件的持续时间

本文概述

  • A.使用音频标签
  • B.使用JS AudioContext
作为许多需要使用音频文件的Web应用程序的常规功能, 音频的持续时间是必须知道的关键, 特别是在那些不需要音频的所有元数据属性的应用程序上。在本文中, 我们将向你介绍如何在浏览器上使用2种差异方法轻松地获取音频文件的持续时间, 以编程方式使用Embed Audio标签或通过JavaScript的AudioContext API接口。
如果你手边没有任何音频文件, 则可以从此处的Puma Studios等网站快速下载一些无版权歌曲。
A.使用音频标签获取音频文件持续时间的最简单方法是通过embed Audio标签, 该标签用于将声音内容嵌入文档中。它可能包含一个或多个音频源, 这些音频源使用src属性或嵌套在音频标签上的< source> 元素表示。
A.1从本地文件读取
作为第一种选择, 你可以在本地读取音频文件并通过此方法获取音频的持续时间:
// Create a non-dom allocated Audio elementvar audio = document.createElement('audio'); // Add a change event listener to the file inputdocument.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 = http://www.srcmini.com/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 secondsconsole.log("The duration of the song is of: " + duration + " seconds"); // Alternatively, just display the integer value with// parseInt(duration)// 12 seconds}, false); }; reader.readAsDataURL(file); }}, false);

A.2从Web URL读取
另外, 如果你想从远程源(服务器)获取音频文件的持续时间, 则比其他实现更容易, 更短:
// Create a non-dom allocated Audio elementvar au = document.createElement('audio'); // Define the URL of the MP3 audio fileau.src = "https://mydomain.com/myaudio.mp3"; // Once the metadata has been loaded, display the duration in the consoleau.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 secondsconsole.log("The duration of the song is of: " + duration + " seconds"); // Alternatively, just display the integer value with// parseInt(duration)// 12 seconds}, false);

B.使用JS AudioContext【如何使用JavaScript在浏览器中检索MP3 / WAV音频文件的持续时间】检索歌曲持续时间的第一个选项是通过AudioContext接口。该API表示由链接在一起的音频模块构建的音频处理图, 每个音频模块由AudioNode表示。音频上下文既控制其包含的节点的创建, 也控制音频处理或解码的执行。你需要先创建AudioContext, 然后再执行其他操作, 因为所有事情都在上下文中发生。
我们将通过2个示例, 向你展示如何使用此界面获取持续时间, 该示例是从本地来源或Web URL中读取音频文件的:
B.1从本地文件读取
为了知道用户在文件类型输入中选择的音频文件的持续时间, 我们基本上需要在标记中具有fileinput, 在这种情况下, 我们的id将是fileinput:
< input type="file" id="fileinput"/>

然后, 我们将事件侦听器附加到输入, 因此, 当用户选择文件时, 将触发回调。在此回调中, 我们将获取第一个上载的文件, 并将其存储到变量中。我们将创建JavaScript的FileReader类的实例。此类使Web应用程序可以使用File或Blob对象指定要读取的文件或数据, 从而异步读取存储在用户计算机上的文件(或原始数据缓冲区)的内容。然后, 在FileReader的onload事件上附加一个回调, 该回调将包含重要的代码以获取音频文件的持续时间。
创建AudioContext API的实例, 然后运行将该第一个参数接收到结果事件的结果对象作为第一个参数的encodeAudioData方法。此方法还接收提供音频缓冲区对象的回调, 从中可以获取音频的持续时间:
// Add a change event listener to the file inputdocument.getElementById("fileinput").addEventListener('change', function(){// Obtain the uploaded file, you can change the logic if you are working with multiuploadvar file = this.files[0]; // Create instance of FileReadervar reader = new FileReader(); // When the file has been succesfully readreader.onload = function (event) {// Create an instance of AudioContextvar 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 secondsconsole.log("The duration of the song is of: " + duration + " seconds"); // Alternatively, just display the integer value with// parseInt(duration)// 12 seconds}); }; // In case that the file couldn't be readreader.onerror = function (event) {console.error("An error ocurred reading the file: ", event); }; // Read file as an ArrayBuffer, important !reader.readAsArrayBuffer(file); }, false);

B.2从Web URL读取
或者, 如果Audio文件位于你的服务器或第三方服务器中, 则yoy可以简单地使用AJAX请求检索该文件并读取它, 并将responseType设置为arraybuffer, 因此你也可以轻松地获得以下信息:
// Request URL of the Audio Filevar mp3file = "https://mydomain.com/myaudio.mp3"; // Create an instance of AudioContextvar audioContext = new (window.AudioContext || window.webkitAudioContext)(); // Open an Http Requestvar 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 secondsconsole.log("The duration of the song is of: " + duration + " seconds"); // Alternatively, just display the integer value with// parseInt(duration)// 12 seconds}); }; // Start Requestrequest.send();

编码愉快!

    推荐阅读