HTML5 오디오 404 오류시 다른 파일 재생

(HTML5 오디오 404 오류 대안에서 넘어옴)

1 개요[ | ]

HTML5 Audio 404 오류 대안
HTML5 오디오 파일 없을 때 대체방안
HTML5 오디오 404 오류시 다른 파일 재생
  • audio 태그에 연결되는 src에 해당 파일이 없을 때 404 오류가 발생한다.
  • 해당 파일이 없을 때 대신 다른 파일을 재생하고 싶다.

2 방법 1: syntaxhighlight 추가[ | ]

  • audio에 syntaxhighlight를 추가하면 브라우저가 알아서 다음 syntaxhighlight를 재생한다.
테스트환경: (동작함) 크롬 40.0, (동작안함) 인터넷익스플로러 11.0
<script src="//code.jquery.com/jquery.min.js"></script>
<script>
$(function() {
	$('.play-myaudio').click(function() {
		$('#myaudio')[0].play();
	});
});
</script>
 
<audio id="myaudio">
	<syntaxhighlight src='not-exist.ogg'>
	<syntaxhighlight src="http://upload.wikimedia.org/wikipedia/commons/f/fa/B-major.ogg">
</audio>

<button class='play-myaudio'>오디오 재생</button>
실행결과 (크롬 40.0 콘솔)
audio-error-skip.php:1 GET http://zetawiki.com/ex/js/not-exist.ogg
→ 오류는 발생하지만 버튼을 눌러보면 B-major.ogg가 재생된다.

3 방법 2: onerror 추가[ | ]

<script src="//code.jquery.com/jquery.min.js"></script>
<script>
$(function() {
	var myaudio = new Audio();
	myaudio.onended = function() {
		console.log( '재생 완료' );	
	}
	myaudio.onerror = function() {
		console.log( this.src + ' 파일 없어서 대신 POP.WAV를 재생' );
		var alternative_src = 'http://free-sounds.net/sound-files/special-effects/POP.WAV';
		if( this.src == alternative_src) {
			console.log( 'POP.WAV도 없음!' );
			return;
		}
		this.src = alternative_src;
		this.play();
	}

	play_audio = function(url) {
		console.log( url + ' 파일 재생' );
		myaudio.src = url;
		myaudio.play();
	};
});
</script>
 
<button onclick="play_audio('not-exist.wav');">not-exist.wav 오디오 재생</button>
<button onclick="play_audio('http://free-sounds.net/sound-files/special-effects/ANGELS_F.WAV');">ANGELS_F.WAV 오디오 재생</button>

4 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}