0

I am trying to dynamically change the value of the src of my HTML audio player and for some reason I can't change it and it stuck on it's placeholder value. This is my HTML element:

    <audio controls preload="none" style="width:480px;">
    <source id="mp3" src="placeholder" type="audio/mp3" />
    </audio>

And this is my Javascript:

var tempMp3 = "http://www.someurl.org/somefile.mp3";
$("#mp3").attr("src", tempMp3);

Anybody knows what silly mistake am i doing here?

Cheers

Pavel Zagalsky
  • 1,620
  • 7
  • 22
  • 52

3 Answers3

2

The code looks ok, maybe like @Nick Dugger says you are trying to change the DOM element when isn't ready yet

A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).load(function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready.

First option

Try putting the code inside this $(document).ready()

$( document ).ready(function() {
    var tempMp3 = "http://www.someurl.org/somefile.mp3";
    $("#mp3").attr("src", tempMp3);
});

Second Option

Another option could be place the <script> tag on the end of the <body> tag

Ethaan
  • 11,291
  • 5
  • 35
  • 45
  • Although probably the solution, `$( document ).ready` is often abused. Also, can you explain to OP *why* he needs this? – ndugger Feb 13 '15 at 21:37
  • 1
    For the record, I do not condone the use of `$( document ).ready` and suggest firing javascript at the end of the body. – ndugger Feb 13 '15 at 21:41
  • This one did the trick but I still have another issue that stems from failing to move this tempMp3 string between 2 functions. Thanks for the help! – Pavel Zagalsky Feb 13 '15 at 21:46
  • hi @PavelZagalsky if you have another different issue, could you please make another SO Question and up vote this one? since the problem here was solved – Ethaan Feb 13 '15 at 22:06
  • I will do so indeed. Many thanks @Ethaan and everybody who helped – Pavel Zagalsky Feb 13 '15 at 22:15
1

Try a bit of plain JavaScript:

var audio=document.getElementById("my_audio_element");
audio.src="source.mp3";
audio.play();

This works for me. HTML5 Audio is still sort of shaky and isn't implemented the same across all major browsers. If you're trying to get it to play on mobile, that's even trickier. Your code looks fine to me, though. Hope this helps!

Frank
  • 2,050
  • 6
  • 22
  • 40
-1

After you change the source, be sure to run the .load() function on the audio element to load the change.

Example (assuming the id "audio" is set the audio element):

var tempMp3 = "http://www.someurl.org/somefile.mp3";
$("#mp3").attr("src", tempMp3);
$("#audio").load();
$("#audio").play();
Mwr247
  • 1,300
  • 10
  • 16