Question

I'm creating a custom HTML5 audio player. I have the following snippet in my script.

var curAudio = new Audio('Audio.mp3');
$("#play").on("click", function(e) {
    e.preventDefault();
    curAudio.play();
});
$("#next").on("click", function(e) {
    e.preventDefault();
    [UPDATE curAudio SRC here]
    curAudio.play();
});

This snippet is highly simplified and isn't very practical but good enough for my question which is, How do I update the src of the audio object dynamically? If I use

var curAudio = $("#audio");

I can easily change the src using

curAudio.attr("src", "newaudio.mp3");

But how do I do it with the former method?

Was it helpful?

Solution

You can set a different source with the Element's src property:

curAudio.src = 'http://.../newaudio.mp3';

This is what .prop() accomplishes for jQuery collections:

$("#audio").prop('src', 'http://.../newaudio.mp3');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top