20

Im my audio player I need to get the duration of my audio track. I need a function that gets src of the audio and returns its duration. Here is what I am trying to do but does not work:

function getDuration(src){
    var audio = new Audio();
    audio.src = "./audio/2.mp3";
    var due;
    return getVal(audio);
}
function getVal(audio){
    $(audio).on("loadedmetadata", function(){
        var val = audio.duration;
        console.log(">>>" + val);
        return val;
    });
}

I tried to split into two functions but it does not work. It would be great if it was as on working function.

Any idea?

7
  • 1
    You are trying to return a value from an asynchronous callback. This won't work.
    – Lee Taylor
    Jan 7, 2016 at 4:46
  • given the issue identified above, is the loadedmetadata function called? do you get any console errors? Jan 7, 2016 at 4:47
  • @JaromandaX well in the second function I get the value correctly but somehow it does not return it to the first function.
    – TheGuy
    Jan 7, 2016 at 4:49
  • 1
    so your issue is exactly as pointed out by @LeeTaylor Jan 7, 2016 at 4:50
  • 1
    @TheGuy - learn to write asynchronous code ... use callbacks or promises - without knowing how getDuration function is going to be used, I can only guess what you need to do Jan 7, 2016 at 4:51

1 Answer 1

32

because you're relying on an event to fire, you can't return a value in getDuration or getVal

instead, you want to use a callback function, like this (callbacks)

The example assume you want to put the duration into a span written like this

<span id="duration"></span>

function getDuration(src, cb) {
    var audio = new Audio();
    $(audio).on("loadedmetadata", function(){
        cb(audio.duration);
    });
    audio.src = src;
}
getDuration("./audio/2.mp3", function(length) {
    console.log('I got length ' + length);
    document.getElementById("duration").textContent = length;
});

Any code that needs to "know" the length should be inside the callback function (where console.log is)


using Promises

function getDuration(src) {
    return new Promise(function(resolve) {
        var audio = new Audio();
        $(audio).on("loadedmetadata", function(){
            resolve(audio.duration);
        });
        audio.src = src;
    });
}
getDuration("./audio/2.mp3")
.then(function(length) {
    console.log('I got length ' + length);
    document.getElementById("duration").textContent = length;
});

using Events - note 'myAudioDurationEvent' can obviously be (almost) anything you want

function getDuration(src, obj) {
    return new Promise(function(resolve) {
        var audio = new Audio();
        $(audio).on("loadedmetadata", function(){
            var event = new CustomEvent("myAudioDurationEvent", {
                detail: {
                    duration: audio.duration,

                }
            });
            obj.dispatchEvent(event);
        });
        audio.src = src;
    });
}
var span = document.getElementById('xyz'); // you'll need to provide better logic here
span.addEventListener('myAudioDurationEvent', function(e) {
    span.textContent = e.detail.duration;
});
getDuration("./audio/2.mp3", span);

although, this can be done similarly with callback or promise by passing in a destination to a modified getDuration function in those solutions as well - my point about using event listeners was more appropriate if one span for example was updated with duration multiple times - this solution still only does each span only once, so can be achieved with the other methods just as easily


given the new information in the comments for this answer, I believe this to be the better solution

function getDuration(src, destination) {
    var audio = new Audio();
    $(audio).on("loadedmetadata", function(){
        destination.textContent = audio.duration;
    });
    audio.src = src;
}

and then invoke getDuration as needed like this

var span = createOrGetSomeSpanElement();
getDuration("./audio/2.mp3", span);

createOrGetSomeSpanElement returns the destination element to use in the getDuration function - how this is done is up to you, seeing as you create a playlist in a loop, I'm guessing you have some element created to receive the audio length already created - it's hard to answer a half asked question sometimes

12
  • Thanks for your code. Still im not sure if it match with my requirement. So based on this it is not possible to have a value to do something like: <span> getDuration('./music.mp3') </span> and get respond like <span>249.2122</span>? As far as I understand, I have to modify my span inside the callback function.
    – TheGuy
    Jan 7, 2016 at 5:09
  • yes, because you can't put javascript code directly inside a span - let me amend the answer with an example Jan 7, 2016 at 5:11
  • 1
    as the "answer" will be asynchronous, you don't know when you will have this "single final value" - so any code that requires this value will need to be written in such a way to account for its asynchronous nature Jan 7, 2016 at 5:15
  • 1
    There is actually a third way this can done, using events - events would be more appropriate for dynamically updating the displayed duration every time you call getDuration with a new src Jan 7, 2016 at 5:26
  • 1
    @TheGuy - I've added an event example - but please read the last paragraph - events are not necessarily a better solution to your use case Jan 7, 2016 at 12:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.