[javascript] change <audio> src with javascript

I have multiple audio files that I want to stream based on the user selects. How do I do that? This is what I have so far and it doesn't seem to work.

*UPDATE: Made a few changes and now its claiming that audio.load(); is not a function. Can anyone tell me why that is? The Code is updated to reflect the changes.

JavaScript:

function updateSource(){ 
    var audio = document.getElementById('oggSource');
    audio.src = 
        'audio/ogg/' + 
        document.getElementById('song1').getAttribute('data-value');
    audio.load();
}

HTML:

<audio id="audio" controls="controls">
    <source id="oggSource" src="" type="audio/ogg"></source>
    <source id="mp3Source" type="audio/mp3"></source>
        Your browser does not support the audio format.
</audio>

<ul style="list-style: none">
    <li>Sunday May 27, 2012
        <ul style="display: none">
            <li id="song1" data-value="song1.ogg">
                <button onclick="updateSource();">Item1</button>
            </li>
            <li>Item2</li>
            <li>Item3</li>
        </ul>
    </li>
</ul>

Item2 and Item3 I will want to play a different audio file when they are clicked on.

This question is related to javascript html html5-audio

The answer is


Try this snippet

_x000D_
_x000D_
list.onclick = function(e) {_x000D_
  e.preventDefault();_x000D_
_x000D_
  var elm = e.target;_x000D_
  var audio = document.getElementById('audio');_x000D_
_x000D_
  var source = document.getElementById('audioSource');_x000D_
  source.src = elm.getAttribute('data-value');_x000D_
_x000D_
  audio.load(); //call this to just preload the audio without playing_x000D_
  audio.play(); //call this to play the song right away_x000D_
};
_x000D_
<ul style="list-style: none">_x000D_
  <li>Audio Files_x000D_
    <ul id="list">_x000D_
      <li><a href="#" data-value="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.oga">Death_Becomes_Fur.oga</a></li>_x000D_
      <li><a href="#" data-value="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.mp4">Death_Becomes_Fur.mp4</a></li>_x000D_
      <li><a href="#" data-value="http://media.w3.org/2010/11/rrs006.oga">rrs006.oga</a></li>_x000D_
      <li><a href="#" data-value="http://media.w3.org/2010/05/sound/sound_90.mp3">sound_90.mp3</a></li>_x000D_
    </ul>_x000D_
  </li>_x000D_
</ul>_x000D_
_x000D_
<audio id="audio" controls="controls">_x000D_
  <source id="audioSource" src=""></source>_x000D_
  Your browser does not support the audio format._x000D_
</audio>
_x000D_
_x000D_
_x000D_

JSFiddle http://jsfiddle.net/jm6ky/2/


Here is how I did it using React and CJSX (Coffee JSX) based on Vitim.us solution. Using componentWillReceiveProps I was able to detect every property changes. Then I just check whether the url has changed between the future props and the current one. And voilĂ .

@propTypes =
    element: React.PropTypes.shape({
         version: React.PropTypes.number
         params:
             React.PropTypes.shape(
                 url: React.PropTypes.string.isRequired
                 filename: React.PropTypes.string.isRequired
                 title: React.PropTypes.string.isRequired
                 ext: React.PropTypes.string.isRequired
             ).isRequired
     }).isRequired

componentWillReceiveProps: (nextProps) ->
    element = ReactDOM.findDOMNode(this)
    audio = element.querySelector('audio')
    source = audio.querySelector('source')

    # When the url changes, we refresh the component manually so it reloads the loaded file
    if nextProps.element.params?.filename? and
    nextProps.element.params.url isnt @props.element.params.url
        source.src = nextProps.element.params.url
        audio.load()

I had to do it this way, because even a change of state or a force redraw didn't work.


with jQuery:

 $("#playerSource").attr("src", "new_src");

    var audio = $("#player");      

    audio[0].pause();
    audio[0].load();//suspends and restores all audio element

    if (isAutoplay) 
        audio[0].play();

Try this:

Replace:

audio.load();

with:

audio.play();

If you are storing metadata in a tag use data attributes eg.

<li id="song1" data-value="song1.ogg"><button onclick="updateSource()">Item1</button></li>

Now use the attribute to get the name of the song

var audio = document.getElementById('audio');
audio.src='audio/ogg/' + document.getElementById('song1').getAttribute('data-value');
audio.load();

change this

audio.src='audio/ogg/' + document.getElementById(song1.ogg);

to

audio.src='audio/ogg/' + document.getElementById('song1');

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to html5-audio

How to make audio autoplay on chrome HTML5 record audio to file HTML5 Audio stop function change <audio> src with javascript How to play a notification sound on websites? How to play audio? html 5 audio tag width Custom CSS for <audio> tag? HTML5 Audio Looping Sound effects in JavaScript / HTML5