자바 스크립트로 오디오를 재생 하시겠습니까?
HTML5와 자바 스크립트로 게임을 만들고 있습니다.
Javascript를 통해 게임 오디오를 재생하려면 어떻게해야합니까?
HTML 요소를 엉망으로 만들고 싶지 않은 경우 :
var audio = new Audio('audio_file.mp3');
audio.play();
var audio = new Audio('https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3');
audio.play();
이것은 요소HTMLAudioElement
와 동일한 방식으로 오디오를 재생 하는 인터페이스를 사용합니다 .<audio>
더 많은 기능이 필요하면 howler.js 라이브러리를 사용했고 간단하고 유용하다는 것을 알았습니다.
<script src="https://cdnjs.cloudflare.com/ajax/libs/howler/2.1.1/howler.min.js"></script>
<script>
var sound = new Howl({
src: ['https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3'],
volume: 0.5,
onend: function () {
alert('Finished!');
}
});
sound.play()
</script>
간단합니다. audio
요소를 가져 와서 play()
메서드를 호출하면 됩니다.
document.getElementById('yourAudioTag').play();
이 예제를 확인하십시오 : http://www.storiesinflight.com/html5/audio.html
이 사이트load()
에서는 pause()
, 및 audio
요소 의 몇 가지 다른 속성 과 같이 수행 할 수있는 다른 멋진 작업에 대해 알아 봅니다.
http://www.schillmania.com/projects/soundmanager2/
SoundManager 2는 IE 6+를 포함한 모든 최신 브라우저에서 사운드를 재생할 수있는 사용하기 쉬운 API를 제공합니다. 브라우저가 HTML5를 지원하지 않으면 플래시에서 도움을받습니다. 엄격한 HTML5를 원하고 플래시는 필요하지 않은 경우 해당 설정이 있습니다.preferFlash=false
iPad, iPhone (iOS4) 및 기타 HTML5 지원 장치 + 브라우저에서 100 % 플래시없는 오디오를 지원합니다.
사용은 다음과 같이 간단합니다.
<script src="soundmanager2.js"></script>
<script>
// where to find flash SWFs, if needed...
soundManager.url = '/path/to/swf-files/';
soundManager.onready(function() {
soundManager.createSound({
id: 'mySound',
url: '/path/to/an.mp3'
});
// ...and play it
soundManager.play('mySound');
});
</script>
실제 데모는 다음과 같습니다. http://www.schillmania.com/projects/soundmanager2/demo/christmas-lights/
이것은 꽤 오래된 질문이지만 유용한 정보를 추가하고 싶습니다. 주제 선발자는 그가라고 언급했습니다 "making a game"
. 따라서 게임 개발을 위해 오디오가 필요한 모든 사람에게는 <audio>
태그 나 HTMLAudioElement
. Web Audio API 사용을 고려해야한다고 생각합니다 .
웹의 오디오에는 더 이상 플러그인이 필요하지 않지만 오디오 태그는 정교한 게임 및 대화 형 응용 프로그램을 구현하는 데 상당한 제한이 있습니다. Web Audio API는 웹 애플리케이션에서 오디오를 처리하고 합성하기위한 고급 JavaScript API입니다. 이 API의 목표는 최신 게임 오디오 엔진에있는 기능과 최신 데스크톱 오디오 프로덕션 응용 프로그램에있는 일부 믹싱, 처리 및 필터링 작업을 포함하는 것입니다.
Jquery로 쉽게
// 사전로드없이 오디오 태그 설정
<audio class="my_audio" controls preload="none">
<source src="audio/my_song.mp3" type="audio/mpeg">
<source src="audio/my_song.ogg" type="audio/ogg">
</audio>
//로드 할 jquery 추가
$(".my_audio").trigger('load');
// 재생 및 중지를위한 메소드 작성
function play_audio(task) {
if(task == 'play'){
$(".my_audio").trigger('play');
}
if(task == 'stop'){
$(".my_audio").trigger('pause');
$(".my_audio").prop("currentTime",0);
}
}
// 오디오 제어 방법 결정
<button onclick="play_audio('play')">PLAY</button>
<button onclick="play_audio('stop')">STOP</button>
편집하다
@stomy의 질문을 해결하기 위해이 접근 방식을 사용하여 재생 목록 을 재생하는 방법은 다음과 같습니다.
개체에 노래 설정 :
playlist = {
'song_1' : 'audio/splat.mp3',
'song_2' : 'audio/saw.mp3',
'song_3' : 'audio/marbles.mp3',
'song_4' : 'audio/seagulls.mp3',
'song_5' : 'audio/plane.mp3'
}
이전과 같이 트리거 및 재생 기능을 사용하십시오.
$(".my_audio").trigger('load');
function play_audio(task) {
if(task == 'play'){
$(".my_audio").trigger('play');
}
if(task == 'stop'){
$(".my_audio").trigger('pause');
$(".my_audio").prop("currentTime",0);
}
}
첫 번째 노래를 동적으로로드 :
keys = Object.keys(playlist);
$('.my_audio').append("<source id='sound_src' src=" + playlist[keys[0]] + " type='audio/mpeg'>");
현재 노래가 끝나면 오디오 소스를 재생 목록의 다음 노래로 재설정합니다.
count = 0;
$('.my_audio').on('ended', function() {
count++;
$("#sound_src").attr("src", playlist[keys[count]])[0];
$(".my_audio").trigger('load');
play_audio('play');
});
숨겨진 오디오를 추가하고 재생하십시오.
function playSound(url){
var audio = document.createElement('audio');
audio.style.display = "none";
audio.src = url;
audio.autoplay = true;
audio.onended = function(){
audio.remove() //Remove when played.
};
document.body.appendChild(audio);
}
new Audio('./file.mp3').play()
다음 오류가 발생하는 경우 :
잡히지 않은 (약속에서) DOMException : 사용자가 먼저 문서와 상호 작용하지 않았기 때문에 play ()가 실패했습니다.
이는 사용자가 먼저 웹 사이트와 상호 작용해야 함을 의미합니다 (오류 메시지에 나와 있음). 이 경우 사용자가 click
웹 사이트와 상호 작용할 수 있도록 또는 다른 이벤트 리스너 만 사용해야 합니다.
오디오를 자동으로로드하고 사용자가 먼저 문서와 상호 작용하는 것을 원하지 않는 경우 setTimeout
.
setTimeout(() => {
document.getElementById('mySound').play();
}, 500)
<audio id="mySound" src="sound.mp3"></audio>
0.5 초 후에 사운드가 시작됩니다.
아래와 같은 HTML 태그가있는 경우 매우 간단한 솔루션 :
<audio id="myAudio" src="some_audio.mp3"></audio>
다음과 같이 JavaScript를 사용하여 재생하십시오.
document.getElementById('myAudio').play();
var song = new Audio();
song.src = 'file.mp3';
song.play();
I used this method to play a sound...
var audioElement;
if(!audioElement) {
audioElement = document.createElement('audio');
audioElement.innerHTML = '<source src="' + '/audio/sound.mp3'+ '" type="audio/mpeg" />'
}
audioElement.play();
I had some issues related to audio promise object returns and some issues related to user interaction with sounds I end up using this small object,
I would recommend to implement the play sounds the closest to the interaction event user is using.
var soundPlayer = {
audio: null,
muted: false,
playing: false,
_ppromis: null,
puse: function () {
this.audio.pause();
},
play: function (file) {
if (this.muted) {
return false;
}
if (!this.audio && this.playing === false) {
this.audio = new Audio(file);
this._ppromis = this.audio.play();
this.playing = true;
if (this._ppromis !== undefined) {
this._ppromis.then(function () {
soundPlayer.playing = false;
});
}
} else if (!this.playing) {
this.playing = true;
this.audio.src = file;
this._ppromis = soundPlayer.audio.play();
this._ppromis.then(function () {
soundPlayer.playing = false;
});
}
}
};
And implement it as follow:
<button onclick="soundPlayer.play('https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3');">Play</button>
if you want to play your audio whenever the page is opened then do like this.
<script>
function playMusic(){
music.play();
}
</script>
<html>
<audio id="music" loop src="sounds/music.wav" autoplay> </audio>
</html>
and call this playMusic() whenever you need in your game code.
You can use Web Audio API for playing sounds. There are quite some audio libraries out there like howler.js, soundjs etc. If you don't worry about old browsers then you can also check on http://musquitojs.com/. It provides a simple API to create and play sounds.
For example, to play a sound all you've to do is.
import $buzz from 'musquito';
const buzz = $buzz('gunfire.mp3');
buzz.play();
The library also supports Audio Sprites.
This is some JS i came up with on a baby AI project im working with. i hope this is able to help you out.
<!DOCTYPE html>
<html>
<head>
<title>
js prompt AI
</title>
<style>
#button {
border: 1px solid black;
border-radius: 10px;
font-size: 22px;
height:65px;
width:100px;
text-align: center;
line-height: 65px;
}
</style>
</head>
<body>
<audio id="myAudio" src="./how_are_you.m4a"></audio>
<p>To Interact with the AI please click the button</p>
<div id=button>click</div>
<script>
var button = document.getElementById("button");
function playBack() {
button.addEventListener("click", function (){
var talk = prompt("If you wish for the AI to respond type hi");
var myAudio = document.getElementById("myAudio");
if(talk === "hi") {
myAudio.play();
}
}) ;
}
playBack();
</script>
</body>
</html>
Just use this:
<video controls="" autoplay="" name="media"><source src="Sound URL Here" type="audio/mpeg" /></video>
Or, to make it simpler:
<video controls="" autoplay="" name="media">
<source src="Sound URL Here" type="audio/mpeg" />
</video>
Sample:
<video controls="" autoplay="" name="media">
<source src="https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3" type="audio/mpeg">
</video>
Have NO IDEA if this works on other browsers other than Chrome 73!!
I had some issues with playing audio, especially since Chrome has updated that the user has to interact with the document first.
However, across almost all solutions I found is that the JS code has to actively set listeners (e.g. button clicks) to receive user events in order to play the audio.
In my case I just wanted my game to play BGM as soon as the player interacts with it, so I made myself a simple listener that keeps checking whether the web page is being interacted or not.
const stopAttempt = setInterval(() => {
const audio = new Audio('your_audio_url_or_file_name.mp3');
const playPromise = audio.play();
if (playPromise) {
playPromise.then(() => {
clearInterval(stopAttempt)
}).catch(e=>{
console.log('' + e);
})
}
}, 100 )
참고URL : https://stackoverflow.com/questions/9419263/playing-audio-with-javascript
'Nice programing' 카테고리의 다른 글
JavaScript 함수를 매개 변수로 전달 (0) | 2020.10.02 |
---|---|
속성 값을 기준으로 JavaScript 개체 정렬 (0) | 2020.10.02 |
모의 메서드가 전달 된 인수를 반환하도록 만들기 (0) | 2020.10.02 |
벡터에 벡터 추가 (0) | 2020.10.02 |
사용자가 입력을 멈출 때까지 .keyup () 핸들러를 지연시키는 방법은 무엇입니까? (0) | 2020.10.02 |