2013-07-15 24 views
3

我發現了另一個問題中的一些代碼片段,播放MP3只是使用jQuery play()和暫停():簡約play()和暫停()的音頻解決方案

<a href="#" rel="http://www.uscis.gov/files/nativedocuments/Track%2093.mp3" 
class="play">Play</a> 

<div class="pause">Stop</div> 

<script> 

$(document).ready(function() { 
    var audioElement = document.createElement('audio'); 
    var source = $('.play').attr('rel'); 

    audioElement.setAttribute('src', source); 
    //audioElement.setAttribute('autoplay', 'autoplay'); 
    audioElement.load() 
    $.get(); 
    audioElement.addEventListener("load", function() { 
    audioElement.play(); 
    }, true); 

    $('.play').click(function() { 
    audioElement.play(); 
    }); 


    $('.pause').click(function() { 
    audioElement.pause(); 
    }); 
}); 

我從音源「播放」鏈接的rel屬性。現在我想添加更多音頻鏈接,並使源相對於它們的rel屬性。

我試圖

var source = $(this).attr('rel'); 

也.find()和。每個(),但沒有到目前爲止的工作。我已經創建了一個jsfiddle兩個音頻鏈接,其中只有第一個音頻文件將被播放。 (小提琴鏈接到客戶端在其網站上使用的外部腳本,其中只有jquery 1.4.3被加載,但我想這可能無論如何,我只是不想使用音頻播放器插件,我的目標是簡約的解決方案)。

任何幫助將不勝感激!

回答

0

您可以更新腳本來創建每個容器一個音頻標籤:

$(document).ready(function() { 
    // For each container div 
    $(".container").each(function() { 
     // Create the HTML5 <audio> tag 
     var audioElement = document.createElement('audio'); 
     // Find the play/pause buttons 
     var $play = $(this).find(".play"); 
     var $pause = $(this).find(".pause"); 
     // Load the source from the play button 
     var source = $play.attr('rel'); 
     audioElement.setAttribute('src', source); 
     $.get(); 
     // Play the sound when loaded 
     audioElement.addEventListener("load", function() { 
      audioElement.play(); 
     }, true);   
     // When the user clicks on the play button, play the audio 
     $play.click(function() { 
      audioElement.play(); 
     }); 
     // When the user clicks on the pause button, pause it 
     $pause.click(function() { 
      audioElement.pause(); 
     }); 
    }); 
}); 

和更新的小提琴:http://jsfiddle.net/sY7UT/

+0

完美的作品!謝謝你:-) – Alani

+0

@Alani沒問題,請標記爲答案,如果它適合你:) – CodingIntrigue