JavaScript返回文本+;播放声音
所以我有一个基于游戏的小应用程序(石头剪纸),但我想返回带有赢家和音效的文本。。。 所以我有两个小mp3文件,分别是paddle.mp3和fail.mp3 我怎样才能返回文本并播放文件:(?我尝试了一些事情,但它告诉我“未定义”或其他错误…:(或者它返回文本,但我听不到声音。)JavaScript返回文本+;播放声音,javascript,html,playsound,Javascript,Html,Playsound,所以我有一个基于游戏的小应用程序(石头剪纸),但我想返回带有赢家和音效的文本。。。 所以我有两个小mp3文件,分别是paddle.mp3和fail.mp3 我怎样才能返回文本并播放文件:(?我尝试了一些事情,但它告诉我“未定义”或其他错误…:(或者它返回文本,但我听不到声音。) var compare = function(choice1) { var winSound = document.getElementById('./sounds/Applause.mp3'); v
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);
};
var比较=函数(选项1){
var winSound=document.getElementById('./sounds/paird.mp3');
var lostSound=document.getElementById('./sounds/Fail.mp3');
var computerChoice=Math.random();
如果(计算机选择<0.34){
computerChoice=“rock”;
}否则,如果(computerChoice您不需要将声音与文本一起返回。因此您可以替换此行
result = 'You are the winner.' + winSound.play();
与:
此外,您似乎没有正确加载音频。您可能希望输入类似于)的内容。winSound.play()不返回字符串,但会产生播放声音的副作用。此外,您将结果分配给变量,而不是返回它。因此
result = 'You are the winner.' + winSound.play();
写:
winSound.play();
return 'You are the winner.';
您可以创建音频对象:
var audio = new Audio();
然后将src指定给您要在回调中播放的声音,然后播放:
audio.src = './sounds/Applause.mp3';
audio.load();
audio.play();
return(text);
您可能希望预先缓存声音,这样就不会有延迟。您可以创建/
audio.src = './sounds/Applause.mp3';
audio.load();
audio.play();
return(text);