HTML5 오디오 중지 기능
내 탐색에서 각 링크를 클릭 할 때 작은 오디오 클립을 재생하고 있습니다
HTML 코드 :
<audio tabindex="0" id="beep-one" controls preload="auto" >
<source src="audio/Output 1-2.mp3">
<source src="audio/Output 1-2.ogg">
</audio>
JS 코드 :
$('#links a').click(function(e) {
e.preventDefault();
var beepOne = $("#beep-one")[0];
beepOne.play();
});
지금까지 잘 작동합니다.
문제는 사운드 클립이 이미 실행 중이고 링크를 클릭하면 아무 일도 일어나지 않는 것입니다.
링크 클릭으로 이미 재생중인 사운드를 중지하려고했지만 HTML5의 오디오 API에 직접적인 이벤트가 없습니다.
다음 코드를 시도했지만 작동하지 않습니다.
$.each($('audio'), function () {
$(this).stop();
});
제발 어떤 제안?
대신 stop()
당신이 시도 할 수 있습니다 :
sound.pause();
sound.currentTime = 0;
이것은 원하는 효과를 가져야한다
먼저 오디오 요소의 ID를 설정해야합니다
당신의 js에서 :
var ply = document.getElementById('player');
var oldSrc = ply.src;
// 단지 오래된 소스를 기억하기 위해
ply.src = "";
// 플레이어를 멈추려면 소스를 아무것도 교체하지 않아야합니다
stop () 메소드를 수행하는 내 방법은 다음과 같습니다.
코드 어딘가 :
audioCh1: document.createElement("audio");
그런 다음 stop ()에서
this.audioCh1.pause()
this.audioCh1.src = 'data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAVFYAAFRWAAABAAgAZGF0YQAAAAA=';
이런 식으로 추가 요청을 생성하지 않고 이전 요청이 취소되고 오디오 요소가 깨끗한 상태입니다 (Chrome 및 FF에서 테스트 됨).
나는 같은 문제가 있었다. 멈춤 부 스트림을 중지해야하며, 이동 onplay 라이브 는 라디오 인 경우. 내가 본 모든 솔루션에는 단점이 있습니다 .
player.currentTime = 0
스트림을 계속 다운로드합니다.player.src = ''
인상error
이벤트
내 해결책 :
var player = document.getElementById('radio');
player.pause();
player.src = player.src;
그리고 HTML
<audio src="http://radio-stream" id="radio" class="hidden" preload="none"></audio>
내 자신의 자바 스크립트 기능에서 재생 / 일시 중지를 전환하기 위해-라디오 스트림을 처리하고 있기 때문에 리스너가 라디오 방송국과 동기화되지 않도록 버퍼를 지우고 싶었습니다.
function playStream() {
var player = document.getElementById('player');
(player.paused == true) ? toggle(0) : toggle(1);
}
function toggle(state) {
var player = document.getElementById('player');
var link = document.getElementById('radio-link');
var src = "http://192.81.248.91:8159/;";
switch(state) {
case 0:
player.src = src;
player.load();
player.play();
link.innerHTML = 'Pause';
player_state = 1;
break;
case 1:
player.pause();
player.currentTime = 0;
player.src = '';
link.innerHTML = 'Play';
player_state = 0;
break;
}
}
currentTime을 지우는 것만으로 Chrome에서 시간을 자르지 않고 소스도 지우고 다시로드해야합니다. 도움이되기를 바랍니다.
이 방법은 작동합니다 :
audio.pause();
audio.currentTime = 0;
But if you don't want to have to write these two lines of code every time you stop an audio you could do one of two things. The second I think is the more appropriate one and I'm not sure why the "gods of javascript standards" have not made this standard.
First method: create a function and pass the audio
function stopAudio(audio) {
audio.pause();
audio.currentTime = 0;
}
//then using it:
stopAudio(audio);
Second method (favoured): extend the Audio class:
Audio.prototype.stop = function() {
this.pause();
this.currentTime = 0;
};
I have this in a javascript file I called "AudioPlus.js" which I include in my html before any script that will be dealing with audio.
Then you can call the stop function on audio objects:
audio.stop();
FINALLY CHROME ISSUE WITH "canplaythrough":
I have not tested this in all browsers but this is a problem I came across in Chrome. If you try to set currentTime on an audio that has a "canplaythrough" event listener attached to it then you will trigger that event again which can lead to undesirable results.
So the solution, similar to all cases when you have attached an event listener that you really want to make sure it is not triggered again, is to remove the event listener after the first call. Something like this:
//note using jquery to attach the event. You can use plain javascript as well of course.
$(audio).on("canplaythrough", function() {
$(this).off("canplaythrough");
// rest of the code ...
});
BONUS:
Note that you can add even more custom methods to the Audio class (or any native javascript class for that matter).
For example if you wanted a "restart" method that restarted the audio it could look something like:
Audio.prototype.restart= function() {
this.pause();
this.currentTime = 0;
this.play();
};
As a side note and because I was recently using the stop method provided in the accepted answer, according to this link:
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Media_events
by setting currentTime manually one may fire the 'canplaythrough' event on the audio element. In the link it mentions Firefox, but I encountered this event firing after setting currentTime manually on Chrome. So if you have behavior attached to this event you might end up in an audio loop.
shamangeorge wrote:
by setting currentTime manually one may fire the 'canplaythrough' event on the audio element.
This is indeed what will happen, and pausing will also trigger the pause
event, both of which make this technique unsuitable for use as a "stop" method. Moreover, setting the src
as suggested by zaki will make the player try to load the current page's URL as a media file (and fail) if autoplay
is enabled - setting src
to null
is not allowed; it will always be treated as a URL. Short of destroying the player object there seems to be no good way of providing a "stop" method, so I would suggest just dropping the dedicated stop button and providing pause and skip back buttons instead - a stop button wouldn't really add any functionality.
It don't work sometimes in chrome,
sound.pause();
sound.currentTime = 0;
just change like that,
sound.currentTime = 0;
sound.pause();
This approach is "brute force", but it works assuming using jQuery is "allowed". Surround your "player" <audio></audio>
tags with a div (here with an id of "plHolder").
<div id="plHolder">
<audio controls id="player">
...
</audio>
<div>
Then this javascript should work:
function stopAudio() {
var savePlayer = $('#plHolder').html(); // Save player code
$('#player').remove(); // Remove player from DOM
$('#FlHolder').html(savePlayer); // Restore it
}
I believe it would be good to check if the audio is playing state and reset the currentTime property.
if (sound.currentTime !== 0 && (sound.currentTime > 0 && sound.currentTime < sound.duration) {
sound.currentTime = 0;
}
sound.play();
for me that code working fine. (IE10+)
var Wmp = document.getElementById("MediaPlayer");
Wmp.controls.stop();
<object classid="clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6"
standby="Loading áudio..." style="width: 100%; height: 170px" id="MediaPlayer">...
Hope this help.
What I like to do is completely remove the control using Angular2 then it's reloaded when the next song has an audio path:
<audio id="audioplayer" *ngIf="song?.audio_path">
Then when I want to unload it in code I do this:
this.song = Object.assign({},this.song,{audio_path: null});
When the next song is assigned, the control gets completely recreated from scratch:
this.song = this.songOnDeck;
The simple way to get around this error is to catch the error.
audioElement.play() returns a promise, so the following code with a .catch() should suffice manage this issue:
function playSound(sound) {
sfx.pause();
sfx.currentTime = 0;
sfx.src = sound;
sfx.play().catch(e => e);
}
Note: You may want to replace the arrow function with an anonymous function for backward compatibility.
참고URL : https://stackoverflow.com/questions/14834520/html5-audio-stop-function
'Programing' 카테고리의 다른 글
UIScrollView 내부의 UIWebView를 확대하려면 어떻게해야합니까? (0) | 2020.06.28 |
---|---|
변수가 정수인지 확인 (0) | 2020.06.28 |
프로그래밍 방식으로 UIImageView에 표시되는 이미지를 어떻게 변경할 수 있습니까? (0) | 2020.06.27 |
마스터와 슬레이브에 MySQL 복제의 경우 다른 데이터베이스가있는 경우 MySQL 데이터베이스를 다시 동기화하는 방법은 무엇입니까? (0) | 2020.06.27 |
기본 및 하위 클래스를 사용한 Python 단위 테스트 (0) | 2020.06.27 |