2017-09-29 3 views
1

이것은 첫 번째 게시물이며 답변을 조금 검색했지만 해결책을 찾지 못했습니다.자바 스크립트 onClick을 사용하여 소리를 시작/중지

기본적으로 내가하고 싶은 것은 onClick = ""javascript 함수 인 playSound (사운드)로 오디오를 시작하고 중지하는 것입니다. 여기까지 내가 끝낸 것이있다. 지금은 클릭 할 때 오디오가 재생되지 않지만 'song1.play()'라는 단일 코드를 테스트하면 사운드가 재생되지만 다시 클릭하면 분명히 멈추지 않습니다. 바라기를 이것은 너무 어렵지 않다.

function playSound(sound){ 
     var song1=document.getElementById(sound); 
     var isPlaying = true; 
     if (!isPlaying){ 
      isPlaying == true; 
      song1.play(); 
     } 
     else{ 
      isPlaying == false; 
      song1.pause(); 
     } 
    } 

답변

0

isPlaying 변수를 변수에 할당하는 대신 true 및 false와 비교했습니다. 이것은 지금 작동해야합니다.

function playSound(sound){ 
    var song1=document.getElementById(sound); 
    var isPlaying = true; 
    if (!isPlaying){ 
     isPlaying = true; 
     song1.play(); 
    } 
    else{ 
     isPlaying = false; 
     song1.pause(); 
    } 
} 
0

대신 ==

= 사용해야 = 할당 연산자이고 == 비교 연산자로.

0

2 개의 작은 수정.

a) var isPlaying = true;은 "OnClick"을 여러 번 호출 할 때 해당 값을 유지하기 위해 전역 적으로 선언해야합니다.

b) 'isPlaying'변수의 할당 문에서 을 =으로 변경해야합니다.

var isPlaying = true; 
function playSound(sound){ 
      var song1=document.getElementById(sound); 
      if (!isPlaying){ 
       isPlaying = true; 
       song1.play(); 
      } 
      else{ 
       isPlaying = false; 
       song1.pause(); 
      } 
     } 
0

소리가 paused 속성을 사용하여 일시 정지 된 경우 당신은 확인할 수 있습니다

function playSound(sound) { 
 
    var song1 = document.getElementById(sound); 
 
    song1.volume = .25; // setting the volume to 25% because the sound is loud 
 
    if (song1.paused) { // if song1 is paused 
 
    song1.play(); 
 
    } else { 
 
    song1.pause(); 
 
    } 
 
}
<audio id="sound"> 
 
    <source src="https://www.w3schools.com/TagS/horse.mp3" type="audio/mp3"> 
 
</audio> 
 
<button onclick="playSound('sound')">Play/Pause</button>

+0

안녕하세요, 감사합니다. html 내에서 스크립트를 작성하면 일부 기능이 작동하지 않게됩니다. 나는이 파일을 별도의 js 파일에 넣고 html에 연결했다. 완벽하게 작동했다. –