Sirwilliam85
Sirwilliam85

Reputation: 53

How can i dynamically load/play/pause multiple-source HTML5 audio on click?

I have a content slider, set to play / stop on each click.

The problem: I want it to pause on second click. Right now it won't pause. Any ideas?

See site here: http://dev.alsoknownas.ca/music/ (audio branding section on homepage).

Here's the code:

**Edited to reflect the code suggested by Lloyd below:

<audio id="player"></audio>

Here's the script:

$(document).ready(function(){
$("span.1").attr("data-src","song.mp3");
$("span.2").attr("data-src","song2.mp3");
$("span.3").attr("data-src","song3.mp3");
$("span.4").attr("data-src","song4.mp3");
$("span.5").attr("data-src","song5.mp3");
});

$("span.1,span.2,span.3,span.4,span.5").click(function () {
  var player = document.getElementById("player");
  player.src = this.getAttribute("data-src");
  player.play();
});

Upvotes: 2

Views: 4183

Answers (2)

Lloyd
Lloyd

Reputation: 8406

for this markup:

<audio id="player"></audio>

<span class="1">one</span>
<span class="2">two</span>

use this script:

$("span.1")
    .attr("data-src-mp3","song1.mp3")
    .attr("data-src-ogg","song1.ogg");
$("span.2")
    .attr("data-src-mp3","song2.mp3")
    .attr("data-src-ogg","song2.ogg");

$("span[data-src-mp3]").click(function () {
    var player = document.getElementById("player"),
        $this = $(this);

    if ($this.hasClass("selected")) {
        if (player.paused) {
            player.play();
        } else {
            player.pause();
        }
    } 
    else {
        $("span[data-src-mp3].selected").removeClass("selected");
        $this.addClass("selected");
        $(player)
            .empty()
            .append($("<source>").attr("src", $this.attr("data-src-mp3")))
            .append($("<source>").attr("src", $this.attr("data-src-ogg")))
        player.play();
    }
});

Live Demo: http://jsfiddle.net/75lb/8cGBx/

Upvotes: 1

Amar Palsapure
Amar Palsapure

Reputation: 9680

Try this,

Instead of doing

$('audio').bind('play','pause', function() {

Do

$('audio').bind('play pause', function(event) {

According to your code, by default audio is paused, when user clicks, it starts playing, and on next click it pauses.

Hope this works for you.

Upvotes: 0

Related Questions