点击播放声音,HTML / jQuery

时间:2014-01-09 16:27:13

标签: javascript jquery html audio web

我想在点击某些div时播放某些声音。它不起作用。然而,当我添加4 * xTone.setAttribute('autoplay','autoplay')时它会同时播放所有声音; (每个4个音调一个)。所以,我认为这有点缩小了。这是我的代码:

<body>

    <div id="header">Header</div>

    <script src="http://code.jquery.com/jquery-2.0.3.js"
    type="text/javascript"></script>

    <script>

        var eTone = document.createElement('audio');
        eTone.setAttribute('src', 'eTone.mp3');

        $('#eTone').click(function(){
            eTone.play();
        });

        var fTone = document.createElement('audio');
        fTone.setAttribute('src', 'fTone.mp3');

        $('#fTone').click(function(){
            fTone.play();
        });

        var gTone = document.createElement('audio');
        gTone.setAttribute('src', 'gTone.mp3');

        $('#gTone').click(function(){
            gTone.play();
        });

        var aTone = document.createElement('audio');
        aTone.setAttribute('src', 'aTone.mp3');

        $('#aTone').click(function(){
            aTone.play();
        });

    </script>

    <table id="musiccloud">
        <tr>
            <td><div id="eTone" class="rain"></div></td>
        </tr>
        <tr>
            <td><div id="fTone" class="rain"></div></td>
        </tr>
        <tr>
            <td><div id="gTone" class="rain"></div></td>
        </tr>
        <tr>
            <td><div id="aTone" class="rain"></div></td>
        </tr>
    </table>

</body>

如果点击每个div时,如何播放4种不同的音调?

1 个答案:

答案 0 :(得分:2)

我使用了类似的东西(调用div.click中的函数):

<script>
function play(cancion){
        var can = document.getElementsByTagName('audio')[cancion];
        can.play();
    }
function stop(){
        can = document.getElementsByTagName('audio')[0];
        can.pause();
        can = document.getElementsByTagName('audio')[1];
        can.pause();
        can = document.getElementsByTagName('audio')[2];
        can.pause();
    }

</script>
<audio id="song1">
    <source src="song1.mp3" type="audio/mpeg">
    <source src="song1.ogg" type="audio/ogg">
</audio>
<audio id="song2">
    <source src="song2.mp3" type="audio/mpeg">
    <source src="song2.ogg" type="audio/ogg">
</audio>

此外,如果您希望多媒体与更多网络浏览器兼容,您应该尝试使用jplayer