실전 프로젝트에서 음원이 활성화 되면 음원이 재생 되고(play), 음원이 비활성화 되면 음원이 정지(pause) 되어야 해서 아래와 같이 코드를 작성 했습니다.
// 음원 재생 여부
const playBack = (status, asmrUrl) => {
const url = document.getElementById(asmrUrl);
const audio = new Audio(audioUrl1); // Audio 객체를 생성해서 음악을 재생한다.
if (status === "play") {
audio.loop = true; // 반복재생 여부
audio.volume = 0.5; // 볼륨
audio.play(); // 음원 재생
} else if (status === "pause") {
audio.pause(); // 음원 재생 중지
audio.currentTime = 0;
}
};
문제 발생
.play()는 작동이 잘 되는 데! .pause()는 작동이 되지 않고 있습니다. 구글링 해봤을 때는.. 코드의 문제가 없는 것 같다...요
https://www.w3schools.com/jsref/met_audio_pause.asp
HTML DOM Audio pause() Method
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
www.w3schools.com
https://wickedmagica.tistory.com/84
[JavaScript] Audio 객체를 이용한 음악 재생
■ 웹 브라우저에서 MP3 음악 틀기 -. HTML5부터는 플래시와 같은 플러그인을 사용하지 않아도 Audio 태그를 사용할 수 있게 되었다. -. 자바스크립트의 Audio 객체를 이용해서 음악을 플레이해 보자. #
wickedmagica.tistory.com
해결 방법
const select = async (asmrUrl) => {
let playList = []; // 선택된 음원만 play 할 배열 // 😀
if (play.includes(asmrUrl)) {
// 비활성화
let arr = [...play];
arr = arr.filter((item) => {
if (asmrUrl !== item) {
return item;
}
});
setPlay(arr);
playList = [...arr]; // 😀
// 선택한 음원 비활성화 style
const deleteItem = document.getElementById(asmrUrl);
deleteItem.style.backgroundColor = "gray";
} else {
// 활성화
if (play.length > 2) {
window.alert("음원은 3개까지만 담으실 수 있습니다.");
} else {
const arr = [...play, asmrUrl];
setPlay(arr);
playList = [...arr]; // 😀
// 선택한 음원 활성화 style
const selectItem = document.getElementById(asmrUrl);
selectItem.style.backgroundColor = "#dddddd";
}
}
// 배열에 있는 음원만 다시 재생.... // 😀
playList.forEach((item) => {
const audioPlayBack = new Audio(item);
audioPlayBack.loop = true;
audioPlayBack.volume = 0.5;
audioPlayBack.play(); // 음원 재생
});
};
pause 안쓰고.... 활성화 시킨 asmrUrl을 배열에 담아서 해당 배열에 있는 요소들을 play 하기로 했다..
'⛵ 항해 중 > 8-13주차 실전 프로젝트' 카테고리의 다른 글
[실전 프로젝트] 드롭다운 기능 만들기 (0) | 2022.01.02 |
---|---|
[실전 프로젝트] 로그인 전 다이어리 페이지 접근 시 팝업창 띄우기 / 음원 활성화/비활성화 구현 (0) | 2021.12.31 |
[실전 프로젝트] ASMR 페이지 구현 (0) | 2021.12.30 |
[실전 프로젝트] 다이어리 페이지 마무리, 네비게이션 바 만들기 (0) | 2021.12.29 |
[실전 프로젝트] 달력 + 해당 월의 일수 계산하기 (+ fill : 특정 값으로 배열 채우기) (0) | 2021.12.28 |
댓글