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?

David Heisnam
  • 2,463
  • 1
  • 21
  • 32

1 Answers1

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');
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
  • 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"); ? – David Heisnam Mar 23 '14 at 15:42
  • @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()`](http://api.jquery.com/attr/#attr2) whereas `Element`s have [`setAttribute()`](https://developer.mozilla.org/en-US/docs/Web/API/element.setAttribute). Though, generally, you'll want to manipulate [properties rather than attributes](http://stackoverflow.com/questions/5874652/prop-vs-attr). – Jonathan Lonowski Mar 23 '14 at 16:05
  • You've been of great help. Thanks a lot Jonathan Lonowski! – David Heisnam Mar 23 '14 at 20:08