2013-08-14 5 views
0

그래서 게임 (바위 종이 가위)을 기반으로하는 작은 앱이 있지만 승자와 사운드 효과로 텍스트를 반환하고 싶습니다 ... 그래서 2 개의 작은 mp3 파일이 있습니다. applause.mp3 and fail.mp3 어떻게하면 텍스트를 반환하고 파일을 재생할 수 있습니다 :(? 나는 tryed 몇 가지지만, "정의되지 않은"또는 다른 오류를 알려줍니다 ... :(또는 어쩌면 그것은 텍스트를 반환합니다 내가 couldnt 소리를 듣고 .. 당신은 텍스트와 함께 소리를 반환 할 필요가 없습니다JavaScript 반환 텍스트 + playsound

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); 
}; 

답변

1

당신은 오디오 객체를 생성 :

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

return(text); 

지체가 없도록 미리 소리를 쳐주십시오.

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

자바 스크립트를

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을

HTML :

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 참조)을 사용하려고했을 것입니다.

0

winSound.play()는 문자열을 반환하지 않지만 사운드를 재생하는 부작용이 있습니다. 또한 결과를 리턴하지 않고 변수에 지정합니다. 그래서 대신

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

쓰기 :

var audio = new Audio(); 

그런 다음 당신은 당신의 콜백에서 재생하고, 재생하고자하는 소리에 SRC를 할당 :

winSound.play(); 
return 'You are the winner.'; 
0

당신은 abhitalks가 권장하는대로 <audio> 태그를 만들거나 HTML 소스에 하나를 추가 할 수 있습니다 full code/result page