Quiero obtener la duración de un audio en una variable, aunque siempre devuelve NaN.
Revisé otras publicaciones y la mayoría de las respuestas hablan de tener que cargar los metadatos del archivo de audio, probé muchas de sus soluciones pero siempre devuelve NaN.
Ambos están devolviendo NaN:
audio.addEventListener('loadedmetadata', function(){ audio.setAttribute("data-time", audio.duration); }, false) console.log(audio.duration); audio.play(); audio.onloadedmetadata = function() { console.log(audio.duration); }; audio.play();El audio se reproduce sin problemas, y otros métodos funcionan, simplemente no puedo obtener la duración del audio.
¿Alguna idea?
tia
Hay un par de formas de alcanzar tu objetivo:
Configure su campo de entrada:
<input type="file" id="fileinput"/>El primero es de su archivo local:
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 console.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);El último enfoque es desde una url:
var mp3file = "https://example.com/myaudio.mp3"; // Create an instance of AudioContext var audioContext = new (window.AudioContext || window.webkitAudioContext)(); // Make 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 console.log("The duration of the song is of: " + duration + " seconds"); // Alternatively, just display the integer value with // parseInt(duration) // 12 seconds }); }; // Start Request request.send();Que tengas un lindo día
Una forma bastante simple y legible, suponiendo que ya tiene un objeto de file de una entrada:
const getDuration = (file) => { const reader = new FileReader(); reader.readAsArrayBuffer(file); reader.onloadend = (e) => { const ctx = new AudioContext(); const audioArrayBuffer = e.target.result; ctx.decodeAudioData(audioArrayBuffer, data => { // this is the success callback const duration = data.duration; console.log('Audio file duration: ' + duration); }, error => { // this is the error callback console.error(error); }); }; };