0

这是文件。现在,我不断从警报中收到一条消息,即 track 变量未定义。似乎 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/>";
4

1 回答 1

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);
    }
于 2013-05-28T07:58:01.620 回答