0

In association with this audio element:

<audio controls id="testTone" preload="metadata">
    <source src="autoharp/tone0.ogg" type="audio/ogg">
</audio>

This code logs the duration of the element:

var au = document.getElementById("testTone");
    au.onloadedmetadata = function() {
console.log(au.duration)
};

What I'd like is to get that au.duration number into a variable.

One thing I tried was having the function return au.duration and then:

var hmmm = au.onloadedmetadata();
console.log(hmmm); 

Which just gave me NaN. Alas. Any suggestions?

drenl
  • 1,321
  • 4
  • 18
  • 32
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Kaiido Jun 19 '17 at 01:52
  • @Kaiido perhaps? I definitely know nothing about Ajax. I'm new to coding so I presume this is some sort of classic rookie mistake I am making... – drenl Jun 19 '17 at 02:47
  • Well it's not only about ajax, but about how asynchronous code works in general. I think the linked answer is a good starting point to understand it, but more basically, `onloadedmetadata` is an Event handler. This means that the function you pass in will only be called when the event will fire (t = ???) All the code set after this declaration will actually be executed before. Which means that you can't get the will-be value before the event really fired. So you've got to construct your code in a way that you will ensure using this value, only when you'll have received it. i.e an `callback`. – Kaiido Jun 19 '17 at 02:54
  • Ok. I'll definitely read up on this, thanks. Do you have any suggestions on how to rephrase the code? While asynchronous may be the larger issue, it sure seems like it's "own question" to me... – drenl Jun 19 '17 at 03:05
  • Well it all depend on what you want to do with this info, and moreover **when**. If you just want to e.g display this value, inside the `onloadedmetadata` event handler, you can do `yourElement.textContent = this.duration;`. If it's a more complex task, then call `yourMoreComplexTask(this.duration)` inside this event handler. – Kaiido Jun 19 '17 at 03:08
  • For what it's worth, the second response here (from user801985) is what I am trying to do: https://stackoverflow.com/questions/7451508/html5-audio-playback-with-fade-in-and-fade-out – drenl Jun 19 '17 at 03:14

0 Answers0