在 div 内创建多个音频标签并播放 MP3

Creating the multiple Audio Tag inside the div and play MP3

我有 ajax 数据,我从我的数据库中获取 base64 Mp3 数据,成功后我可以使用音频标签播放 mp3,但是当我从数据库中获取多个 base64 数据时,我必须创建多个音频标签,并且我必须 link base64 到每个音频标签。下面是我的代码:

 ///Html
<div id="container">
 <audio id="audio"  controls="controls" autobuffer="autobuffer" autoplay="autoplay"></audio>
</div>

///Ajax call getting the base64 from DB and adding has source to audio tag
 $.ajax({
    type: "POST",
    dataType: "json",
    url:  'xxxx/xxxx/xxxxx',
    data: xxxxxx,
    success: function (data) {
        if (data[0].Base64 != null) {
            $.each(data, function (key, value) {
            alert(key + ": " + value);
            $("#audio").html("<source src=\"data:audio/Mp3;base64," + value.Base64 + "\"/>"); });
        } else {
            alert("No Data")
        }
    }
 });

在您的 each() 循环中,您可以为每个条目创建新的 DOM 对象并将其附加到您的 #container:

var audio = $('<audio><source src="data:audio/Mp3;base64,' + value.Base64 + '"/>');
$("#container").append(audio);

试试这个....

<div id="boxes">
    <li id="nyan" class="audioclick"><audio src="song.mp3"/></li>
    <li id="duck" class="audioclick"><audio src="duck.mp3"/></li>
    <li id="duck" class="audioclick"><audio src="cat.mp3"/></li>
</div>

$(function(){
    $('#boxes').on('click','audioclick',function(){
        var $eq = $(this).eq(),
            audio = $('audio').get($eq);

        if (audio.paused){
            audio.play();
        } else {
            audio.pause();
        }
    });
});

您可以遵循这种结构:

///Ajax call getting the base64 from DB and adding has source to audio tag
 $.ajax({
    type: "POST",
    dataType: "json",
    url:  'xxxx/xxxx/xxxxx',
    data: xxxxxx,
    success: function (data) {
        if (data[0].Base64 != null) {
            $.each(data, function (key, value) {
            alert(key + ": " + value);
            $("#container").append("<audio source src=\"data:audio/Mp3;base64," + value.Base64 + " controls='controls' autobuffer='autobuffer' autoplay='autoplay'></audio>"); });
        } else {
            alert("No Data")
        }
    }
 });
 ///Html
<div id="container">

</div>