尝试随机播放随机歌曲(研究音乐最终:))

时间:2013-05-28 00:07:06

标签: php javascript jquery html5 audio

  

以下是文件。现在我不断从警报中收到一条消息,指出跟踪变量是未定义的。好像PHP工作,因为如果我直接进入php链接,并手动输入GET变量,我会得到返回的歌曲。此外,我正在寻找一种方法来获得一首歌的随机10秒剪辑(就像我的音乐老师测试我们的方式)。我想到的方法是将持续时间除以10并将其乘以一个随机数,然后使用setineterval来查看currenttime()是否比初始音频时间多10秒。

//index.php
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Music Final Quiz</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <audio src="" id="player"></audio>
    <button id="change_track">Play A Different Track</button>
    <script src="jquery.js"></script>
    <script src="script.js"></script>
</body>
</html>

//script.js
var player = document.getElementById("player");
var changeTrack = document.getElementById("change_track");
var previousNumber = null;
var timeStart = null;

function loadTrack(){
    var randomNumber = Math.floor(Math.random()*11);
    if(randomNumber != 0 && randomNumber != previousNumber){
        previousNumber = randomNumber;
    }else{
        randomNumber = 1;
    }
    var track = $().get("generate_song.php?track_number=" + randomNumber);
    player.src = track;
    player.load();
    // player.currentTime() = (player.duration/10) * Math.floor(Math.random()*11);
    player.play();
    alert(track);
}

window.addEventListener("load", loadTrack);
changeTrack.addEventListener("click",loadTrack);

//generate_song.php
$directory = "Audio_Files";
$files = scandir($directory);
$requested_song = $_GET["track_number"];

echo $files[$requested_song + 1]."<br/>";

1 个答案:

答案 0 :(得分:0)

player.currentTime是属性,不是函数,因此它应该是:

player.currentTime = (player.duration/10) * Math.floor(Math.random()*11);

对于间隔部分,我会添加间隔并检查歌曲是否暂停:

    function loadTrack(){
        var randomNumber = Math.floor(Math.random()*11);
        if(randomNumber != 0 && randomNumber != previousNumber){
            previousNumber = randomNumber;
        }else{
            randomNumber = 1;
        }
        var track = $().get("generate_song.php?track_number=" + randomNumber);
        player.src = track;
        player.load();
        player.currentTime = (player.duration/10) * Math.floor(Math.random()*11);
        player.play();
        playTenSeconds = setInterval(function(){
            if(player.paused === false){
                player.pause();
                alert(track);
                clearInterval(playTenSeconds);
            }else{
                player.play();
            }
        }, 10);
    }