Need help getting the duration of an audio file

Joined
Dec 14, 2021
Messages
28
Reaction score
2
I have this code I need help making the audio.duration work. Here's the code:

JavaScript:
function addTrack(tkFile) {
    var trackSource = URL.createObjectURL(tkFile.files[0]);
    var trackLth;
    var trackName = tkFile.files[0].name;
    
    const div = document.createElement("div");
    div.className = "track";
    
    const audio = document.createElement("audio");
    var reader = new FileReader();
        reader.onload = function (e) {
            audio.controls = true;
            audio.src = trackSource;
            audio.innerHTML = "Your browser does not support the audio element.";
            audio.onloadedmetadata = function() {
            trackLth = getHHMMSSFromSeconds(parseInt(audio.duration));
        };
    }
    reader.readAsDataURL(tkFile.files[0]);
    div.appendChild(audio);
    
    //There's more here but it all is just adding stuff to the HTML, not important to the audio creation
}

Here is the file selector, on the HTML file:

HTML:
<label for="trackFile">Select a file: (Only Audio Files)</label>
<input type="file" id="trackFile" name="trackFile" onchange="addTrack(this)" accept="audio/*">

Also, you don't need getHHMMSSFromSeconds(), as all it does is format seconds into a HH:MM:SS format.

Make sure to give me the context of your answer.
 
Joined
Mar 11, 2022
Messages
227
Reaction score
32
Code:
audio..load(); 
audio.addEventListener('canplaythrough',function(e){
    cosole.log('DURATION\n'+audio.duration);
    });
 
Joined
Mar 11, 2022
Messages
227
Reaction score
32
for example in your filereader onload function
Code:
 var reader = new FileReader();
        reader.onload = function (e) {
            audio.controls = true;
            audio.src = trackSource;

            audio.innerHTML = "Your browser does not support the audio element.";
audio.load();
audio.addEventListener('canplaythrough',function(e){
              trackLth = getHHMMSSFromSeconds(parseInt(audio.duration));
    });
           }
 
Joined
Dec 14, 2021
Messages
28
Reaction score
2
for example in your filereader onload function
Code:
 var reader = new FileReader();
        reader.onload = function (e) {
            audio.controls = true;
            audio.src = trackSource;

            audio.innerHTML = "Your browser does not support the audio element.";
audio.load();
audio.addEventListener('canplaythrough',function(e){
              trackLth = getHHMMSSFromSeconds(parseInt(audio.duration));
    });
           }
That's the thing, it isn't working, I keep getting a return of undefined, meaning it is not getting the duration, hence why it isn't working. I would like some actual help, not someone saying stuff that could work. Are you even testing if it would work in my code?

Also, I asked for context. You really didn't provide any context.

After all, context means the circumstances that form the setting for something and in terms of which it can be fully understood and assessed.

You only gave me code, I am also trying to learn stuff, as a good response usually would have that context of how it works.
 
Joined
Mar 11, 2022
Messages
227
Reaction score
32
The thing is. You are lazy. Because you want us to write you that code. I wont go through your code because you told us that everything works beside the duration. So i only focused on that. If it's not working, than there is something fishy on your code. Right?

Try this (COPY AND RUN)
Code:
<input type="file" accept="audio/*" onchange="getDuration(this);" />
<script>
function getDuration(d){
var reader = new FileReader();
reader.onload = function (e) {
            var audio=new Audio(this.result);
            audio.load();
            audio.play();
            audio.addEventListener('canplaythrough',function(e){
             alert('DURATION IS '+audio.duration);
    });
        };
 reader.readAsDataURL(d.files[0]);
}
</script>

Tell me if you see a duration number or not.
 
Joined
Mar 11, 2022
Messages
227
Reaction score
32
About context. Fair enough. Here you go (i mean, a googlesearch for "Filereader") would answer your questions way better. But okay.

Code:
//FILEREADER is a class that comes with a lot of mighty stuff. Google it.
var reader = new FileReader();

//now that the Filereader is called by "reader", "reader" is our Filereaderclass. One of this class functions is onload.

reader.onload = function (e) { //a file, (audio, video) has to be loaded before we have access to it's stuff as the dataURL (bich is a base64 String of the file.)
//If everything is loaded, we can take that file and can use it as source (src) in an audio element. I use the Audioobject for this example.
var audio=new Audio(this.result);
//Now i want my audioobject to load the source, because we need the duration. Duration is given only, if the sourcefile is loaded.
audio.load();
//And play it. You may skip that. I did it only fot testing reasons
audio.play();

//now, ad our audio.load() is setted, we may check if it canplaythrough (All modern browsers supports that. But of course, you may write your own crossbrowser solution)

//add an eventListener (when event canplaythrough happend than do function
audio.addEventListener('canplaythrough',function(e){
             alert('DURATION IS '+audio.duration);
    });
 };

//And now last but not least, we tell our reader wich dile we need as DataUrl
 reader.readAsDataURL(d.files[0]);

Anyway. Your whole concept needs to be improved.

You want to do a kind of mp3 player right? So you don't need a audio element for each file. One is enough.
Store all the informations in an object.

Example:
Code:
var myList=new Array(); //ARRAY to store our objects
var reader = new FileReader();
reader.onload = function (e) {
           var obj={name:d.files[0].name,source:this.result}; //NEW OBJECT
            var audio=new Audio(this.result);
            audio.load();
            audio.addEventListener('canplaythrough',function(e){
             obj.duration=audio.duration;
            delete audio; //we don't need that anymore
            myList.push(obj); //push the object into our array
    });
        };
 reader.readAsDataURL(d.files[0]);

Now you can work with myList. All your uploads are inside. Including file name (e.g. Shakira.mp3), Duration and source.
Create a for loop and add some divs according to your myList.length. innerHTML the duration and filename and add the source on it.
Code:
myDiv.source=myList[i].source;
myDiv.onclick=function(){
myAudioElement.src=this.source.
myAudioElement.play();

}

Untested, but it should be something like that. I mean, if you really struggle with that, don't you think you should start with more simple easier stuff?
 
Last edited:

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top