0

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?

1 Answer 1

1

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');
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your reply. Do var curAudio = new Audio("audio.mp3"); and var curAudio = $("#audiotag"); behave the same way? Can they be manipulated the same way like, for example, by using curAudio.attr("src", "newaudio.mp3"); ?
@DavidHeisnam Yes and no. Setting an attribute with either will behave the same, but each have their own method for doing that. jQuery collections have .attr() whereas Elements have setAttribute(). Though, generally, you'll want to manipulate properties rather than attributes.
You've been of great help. Thanks a lot Jonathan Lonowski!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.