2017-04-25 1 views
0

현재 재생중인 mp3를 일시 중지하는 데 문제가 있습니다.JavaScript로 MP3 재생/일시 중지 문제

예를 들어,이 함수를 다음과 같이 실행하면 playSong(drake);은 내 if 문의 첫 번째 부분에서 코드를 실행하기 시작하고 "drake"개체에서 MP3를 재생하고 songValue = 2를 설정합니다. 문제는 두 번째로 실행하면 노래를 일시 중지하지 않지만 내 console.log는 콘솔에 표시되므로 두 번째 부분을 클릭하면 두 번째 부분이 실행됩니다. 몇 가지 이유로 노래를 일시 중지하십시오.

//object with mp3 audio 
var drake = { 
    value: 3, 
    name: 'Energy', 
    artist: 'Drake', 
    audio: 'energy.mp3', // 
    img: '<img style="width: 50%; margin-right: 25%; margin-left: 25%; margin-top: 10%;" src="http://www.getrichrapping.com/wp-content/uploads/2015/08/Drake-Energy.jpg">' 
}; 


songValue = 1; 

// plays and SHOULD pause a Song 
function playSong(object) { 
    var Song = new Audio(object.audio); 

    //plays the song 
    if (songValue == 1) { 

     Song.play(); 
     songValue = 2; 

     // SHOULD pause the song when the functions is runned the second time 
    } else if (songValue == 2) { 
     console.log("Is it working ?"); // String to test if the "else if" gets runned 
     Song.pause(); 
     songValue = 1; 

    } 
}; 
+0

여기서 songValue가 정의되고 있습니까? object.value? –

+0

오, 미안하지만 그것을 추가하는 것을 잊어 버렸습니다. 그냥 –

답변

0

두 가지 기능이 있어야합니다. 오디오 요소를 생성하기위한 것이고, 주어진 오디오 요소를 재생/일시 정지하기위한 것입니다.

당신의 문제 중 하나는 playSong()으로 전화 할 때마다 완전히 새로운 오디오 요소를 만드는 것입니다.

해결

var drake = { 
    value: 3, 
    name: 'Energy', 
    artist: 'Drake', 
    audio: 'energy.mp3', // 
    img: '<img style="width: 50%; margin-right: 25%; margin-left: 25%; margin-top: 10%;" src="http://www.getrichrapping.com/wp-content/uploads/2015/08/Drake-Energy.jpg">' 
}; 

var audioElement = playSong(drake); // load song and play it 

togglePlayPause(audioElement); // pause song 

function playSong(object) { 
    var Song = new Audio(object.audio); 
    Song.play(); 

    return Song; 
} 

function togglePlayPause(audioElement) { 
    if (audioElement.paused) { 
     audioElement.play(); 
    } else { 
     audioElement.pause(); 
    } 
} 

먼저 오디오 요소를 생성하고 playSong() 함수를 사용하여 변수에 저장한다. 그런 다음 오디오 요소를 togglePlayPause()으로 전달하여 재생 상태를 전환합니다.

예를 들어, 나는 노래를 연주하고 나서 즉시 togglePlayPause()을 호출하여 다시 일시 중지합니다.

또한 재생 상태를 별도의 변수로 유지할 필요가 없습니다. 방금 플레이어가 일시 중지 된 경우 true를 반환하는 오디오 요소에 .paused 속성을 사용했습니다. 별도의 변수가 정말로 필요하다면 drake 객체 내에 새로운 속성 .isPlaying으로 저장해야합니다.

https://jsfiddle.net/5k38da10/

0

var Song = new Audio (object.audio)를 playSong 외부로 이동하십시오.

본질적으로 당신이 기능을 부를 때마다 새 오디오를 만드십시오!

물론 object가 전역이 아니므로 object.audio를 참조해야합니다.

더 좋은 방법은 다음과 같이 할 수 있습니다 :

//object with mp3 audio 
 
var drake = { 
 
    value: 3, 
 
    name: 'Energy', 
 
    artist: 'Drake', 
 
    audio: 'https://www.w3schools.com/html/horse.mp3', // 
 
    img: '<img style="width: 50%; margin-right: 25%; margin-left: 25%; margin-top: 10%;" src="http://www.getrichrapping.com/wp-content/uploads/2015/08/Drake-Energy.jpg">' 
 
}; 
 

 

 
songValue = 1; 
 

 
// plays and SHOULD pause a Song 
 
function playSong(object) { 
 

 
    //plays the song 
 
    if (songValue == 1) { 
 
    var player = document.getElementById('song'); 
 
    var sourceMp3 = document.getElementById('sourceMp3'); 
 

 
    sourceMp3.src = object.audio; 
 

 
    player.load(); //just start buffering (preload) 
 
    player.play(); //start playing 
 

 
    songValue = 2; 
 

 
    // SHOULD pause the song when the functions is runned the second time 
 
    } else if (songValue == 2) { 
 
    console.log("Is it working ?"); // String to test if the "else if" gets runned 
 
    var player = document.getElementById('song'); 
 

 
    if (!player.paused) 
 
     player.pause(); 
 
    songValue = 1; 
 

 
    } 
 
};
<audio id="song" controls="controls"> 
 
    <source id="sourceMp3" src="" type="audio/mp3" /> 
 
    Your browser does not support the audio element. 
 
</audio> 
 

 
<p> 
 
    <button onclick='playSong(drake)'> Play Song </button> 
 
</p>

참조 된 바이올린 : http://jsfiddle.net/jm6ky/2/

업데이트 바이올린 :에 http://jsfiddle.net/c6jgjewg/2/

+0

고맙습니다.하지만 var 내의 "object"노래가 정의되지 않았습니다. 다른 오디오를 재생하려고하기 때문에 필요합니다. –

+0

오디오를 잡으려고합니다. 일부 자바 스크립트 코드를 통해 인스턴스 - getElementById 아마! – Digvijay

+0

죄송합니다. 무슨 뜻인지 모르겠다. –

0

당신은 당신에게 오디오 객체를 저장해야합니다 당신의 이런 기본 객체

if (object.song == undefined){ 
    object.song = new Audio(object.audio); 
} 

대신 변수 노래

당신은 사용자 object.song.paused(boolean) 노래가 일시 중지 알고 여부를 다시 노래를 시작하는 수의 object.song를 사용합니다.

관련 문제