여기에 사용자가 버튼을 누르면 배경 음악이 재생되는 버튼이 있습니다. 다시 누르면 음악이 일시 중지됩니다.
이것은 단일 mp3 파일에서 잘 작동하지만 변형을 위해 더 많은 노래를 추가하고 싶었습니다.
복잡한 음악 플레이어로 만들고 싶지 않습니다. 음악을 재생 / 일시 중지하는 단일 버튼과 bg1 이 완료되면 배열의 다음 버튼을 재생 합니다.
또한 연주 할 음악을 무작위로 선택할 수 있으면 좋겠어요.
지금까지 내 코드가 어떻게 생겼는지 살펴보십시오.
var myAudio = document.getElementById("myAudio");
var isPlaying = false;
function togglePlay() {
isPlaying ? myAudio.pause() : myAudio.play();
};
myAudio.onplaying = function() {
isPlaying = true;
};
myAudio.onpause = function() {
isPlaying = false;
};
<audio id="myAudio" src="bg1.mp3" preload="auto" loop></audio>
<a href="#" onclick="togglePlay()">Play Music</a>
여기 배열에 대한 평가판 스크립트가 있지만 직접 완료 할 수 없습니다.
let musicPlayer=[
`bg1.mp3`,
`bg2.mp3`,
`bg3.mp3`,
`bg4.mp3`
];
function playMusic(){
let index=Math.floor(Math.random()*musicPlayer.length);
let div=document.querySelector('#music');
마지막으로, 로딩 시간이 길어질 수있는 약 70 개의 mp3 파일 배열을 만들 계획입니다. 회전 할 때까지로드되지 않도록 만들 수 있습니다. lazy loading
오디오 파일 과 비슷한 가요?
정말 감사하겠습니다. 많은 감사드립니다!
나는 다음과 같이 그것을 다룰 것이다.
const audio = document.querySelector('#audio');
const audioButton = document.querySelector('#audioButton');
const audioUrls = [
"https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3"
];
const randomAudio = () => {
const index = Math.floor(Math.random() * audioUrls.length);
const audioUrl = audioUrls[index];
return audioUrl;
}
audioButton.addEventListener("click", () => {
audio.addEventListener("ended", () => {
const audioUrl = randomAudio();
const temp = new Audio();
temp.addEventListener("loadeddata", () => {
audio.src = audioUrl;
});
temp.src = audioUrl;
})
const audioUrl = randomAudio();
audio.addEventListener("loadeddata", () => {
audio.play();
});
audio.src = audioUrl;
})
<audio id="audio" src="" preload="auto" loop></audio>
<a id="audioButton" href="#">Play Music</a>
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다