HTML音频-单击可随机播放

时间:2018-12-13 18:38:48

标签: javascript php html5 audio

我想基于HTML 5和PHP创建一个简单的随机播放音频播放器。我有4个不同的声音文件(每个文件的长度为1秒)。

我的目的是随机更改声音文件,但是目前我需要在下一个文件播放之前重新加载页面。

    <?php
$audioFile1 = '<source src="path/SoundFile1.wav" type="audio/mpeg">';
$audioFile2 = '<source src="path/SoundFile2.wav" type="audio/mpeg">';
$audioFile3 = '<source src="path/SoundFile3.wav" type="audio/mpeg">';
$audioFile4 = '<source src="path/SoundFile4.wav" type="audio/mpeg">';
$audioFiles = array( $audioFile1, $audioFile2, $audioFile3, $audioFile4 );
shuffle( $audioFiles );
?>

<audio controls class="iru-tiny-player" data-title="Shuffle">
    <?php print $audioFiles[0]; ?>
</audio>

在结束当前文件之后,是否有一种方法可以随机播放下一个文件?

2 个答案:

答案 0 :(得分:0)

我将混洗的路径打印到JS数组中,然后侦听<audio>元素的ended事件,然后将源的src属性更改为下一轨道:

const shuffledPaths = [
  'https://freewavesamples.com/files/Alesis-Sanctuary-QCard-Tines-Aahs-C4.wav',
  'https://freewavesamples.com/files/Roland-JV-2080-Pick-Bass-C2.wav',
  'https://freewavesamples.com/files/Bass-Drum-2.wav'
];

// You should probably use more specific selectors, this is for the sample
const player = document.querySelector('audio');
const source = document.querySelector('source');

let currentIndex = -1;

function goNext() {
  // Grab the next path and put it in the source's src attribute
  currentIndex = (currentIndex + 1) % shuffledPaths.length;
  source.setAttribute('src', shuffledPaths[currentIndex]);

  // Load the corresponding track and play it
  player.load();
  player.play();
}

// Play the following track when the current one ended
player.addEventListener('ended', goNext);

// Play the first track
goNext();
<audio controls class="iru-tiny-player" data-title="Shuffle">
  <source type="audio/mpeg">
</audio>

请注意,我使它循环播放,但是如果愿意,可以很容易地与currentIndex一起使用以使其在结尾处停止。

答案 1 :(得分:0)

您只需更改代码即可使用js。

<?php
    $audioFile1 = 'path/SoundFile1.wav';
    $audioFile2 = 'path/SoundFile2.wav';
    $audioFile3 = 'path/SoundFile3.wav';
    $audioFile4 = 'path/SoundFile4.wav';
    $audioFiles = array($audioFile1, $audioFile2, $audioFile3, $audioFile4);
    shuffle($audioFiles);
?>

<audio id="audio" controls class="iru-tiny-player" data-title="Shuffle" src="<?php print $audioFiles[0] ?>" type="audio/mpeg"></audio>

<script type="text/javascript">
    document.getElementById('audio').addEventListener("ended",function() {
        var fileArr = ['<?= $audioFile2 ?>', '<?= $audioFile2 ?>', '<?= $audioFile4 ?>'];
        var min=0;
        var max= (fileArr.length -1);
        var random = Math.floor(Math.random() * (+max - +min) + +min);
        this.src = fileArr[random];
        this.play();
    });
</script>
相关问题