Reputation: 1646
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
Upvotes: 0
Views: 2131
Reputation: 2230
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!
Upvotes: 1
Reputation: 1390
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();
Upvotes: -1
Reputation: 11376
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
Upvotes: 2