0

所以我有一个基于游戏(石头剪刀布)的小应用程序,但我想返回带有获胜者和音效的文本......所以我有 2 个小 mp3 文件 applause.mp3 和 fail.mp3 我该怎么做返回文本并播放文件:(?我尝试了几件事,但它告诉我“未定义”或其他错误...... :(或者它返回给我的文本购买我听不到声音..

var compare = function(choice1) {
    var winSound = document.getElementById('./sounds/Applause.mp3');  
    var lostSound = document.getElementById('./sounds/Fail.mp3');
    var computerChoice = Math.random();
    if (computerChoice < 0.34) {
        computerChoice = "rock";
    } else if(computerChoice <= 0.67) {
        computerChoice = "paper";
    } else {
        computerChoice = "scissors";
    }
    if (choice1 === computerChoice) {
        return('The result is a tie!');
      }
    else if (choice1 === 'rock') {
        if (computerChoice === 'scissors') {
           result = 'You are the winner.' + winSound.play();
        } else {
            return 'Computer is the winner.';
        }
    }
    else if (choice1 === 'paper') {
        if (computerChoice === 'rock') {
            return 'You are the winner.';
        } else {
            return 'Computer is the winner.';
        }
    }
    else {
        if (computerChoice === 'rock') {
            return 'You are the winner.';
        } else {
            return 'Computer is the winner.';
        }
    }
};

var game = function(choice1) {
    document.getElementById('result').innerHTML = compare(choice1);
};
4

4 回答 4

1

您不需要将声音与文本一起返回。所以你可以替换这一行

       result = 'You are the winner.' + winSound.play();

和:

       winSound.play();
       result = 'You are the winner.';

此外,您似乎没有正确加载音频。您可能想<audio id="win-sound" src="./sounds/Applause.mp3"></audio>在您的 HTML 中添加类似的内容,然后使用document.getElementById('win-sound')(请参阅http://www.w3schools.com/html/html5_audio.asp)。

于 2013-08-14T10:55:45.973 回答
1

您创建一个音频对象:

var audio = new Audio();

然后将 src 分配给您要在回调中播放的声音,然后播放:

audio.src = './sounds/Applause.mp3';
audio.load();
audio.play();

return(text);

您可能需要事先缓存声音,以免延迟。

于 2013-08-14T10:57:30.743 回答
0

winSound.play() 不返回字符串,但有播放声音的副作用。此外,您将结果分配给变量而不是返回它。所以而不是

result = 'You are the winner.' + winSound.play();

写:

winSound.play();
return 'You are the winner.';
于 2013-08-14T10:56:31.587 回答
0

您可以按照abhitalks<audio>推荐的方式创建标签,也可以在 html 源代码中添加一个:

HTML

<audio id="player"></audio>

Javascript

var winSound = './sounds/Applause.mp3';
var lostSound = './sounds/Fail.mp3';
var player = document.getElementById('player'); //audio element
if (result == 'You are the winner.') {
    player.src = winSound;
} else if (result == 'Computer is the winner.') {
    player.src = lostSound;
} else {
    player.src = '';
}
player.load();
player.play();

JSFiddle:完整代码/结果页面

于 2013-08-14T12:07:48.697 回答