HTML5를 사용하여 웹 뮤직 플레이어를 작성하는 방법
기능 소개
오디오 및 비디오 태그는 HTML5에서 출시되었으며, 이를 통해 다른 플러그인을 사용하지 않고도 오디오 및 비디오를 직접 재생할 수 있습니다. 다음으로 html5의 오디오 태그와 관련 속성 및 메서드를 사용하여 간단한 음악 플레이어를 만듭니다. HTML5 제작 웹 뮤직 플레이어에는 주로 다음 기능이 포함되어 있습니다.
1. 재생 및 일시 중지, 이전 및 다음 노래
2. 볼륨 및 재생 진행률 표시줄 조정
3. 목록에 따라 현재 노래 전환 최종 결과를 살펴보겠습니다.
이 뮤직 플레이어의 구조는 크게 노래 정보, 플레이어, 재생 목록의 세 부분으로 나뉩니다. 먼저 재생을 위해 플레이어에 3개의 오디오 태그를 넣습니다.
<audio id="music1">浏览器不支持audio标签 <source src="media/Beyond - 光辉岁月.mp3"></source> </audio> <audio id="music2">浏览器不支持audio标签 <source src="media/Daniel Powter - Free Loop.mp3"></source> </audio> <audio id="music3">浏览器不支持audio标签 <source src="media/周杰伦、费玉清 - 千里之外.mp3"></source> </audio>
아래 재생 목록도 3개의 오디오 태그에 해당합니다.
<div id="playList"> <ul> <li id="m0">Beyond-光辉岁月</li> <li id="m1">Daniel Powter-Free Loop</li> <li id="m2">周杰伦、费玉清-千里之外</li> </ul> </div> 接下来我们就开始逐步实现上面提到的功能吧,先来完成播放和暂停功能,在按下播放按钮时我们要做到进度条随歌曲进度前进,播放时间也逐渐增加,同时播放按钮变成暂停按钮,播放列表的样式也对应改变。
기능을 수행하기 전에 3개의 오디오 태그 ID를 가져와서 배열에 저장해야 합니다. . 이후 사용을 위해 .
var music1= document.getElementById("music1"); var music2= document.getElementById("music2"); var music3= document.getElementById("music3"); var mList = [music1,music2,music3];
재생 및 일시 중지:
이제 재생 버튼의 기능을 완료할 수 있습니다. 먼저 음악의 재생 상태를 표시하는 플래그를 설정한 다음 배열의 인덱스 인덱스에 대한 기본값을 설정합니다.
그런 다음 재생 상태를 설정하고 판단하고 해당 함수를 호출하고 목록에서 해당 항목의 플래그 값과 스타일을 수정합니다.
var flag = true; var index = 0; function playMusic(){ if(flag&&mList[index].paused){ mList[index].play(); document.getElementById("m"+index).style.backgroundColor = "#A71307"; document.getElementById("m"+index).style.color = "white"; progressBar(); playTimes(); play.style.backgroundImage = "url(media/pause.png)"; flag = false; }else{ mList[index].pause(); flag = true; play.style.backgroundImage = "url(media/play.png)"; } }
위 HTML 페이지의 코드는 여러 함수를 호출하며 그 중 재생 및 일시 중지는 오디오 태그와 함께 제공되는 메서드이고 다른 함수는 직접 정의합니다. 이러한 기능이 어떻게 구현되어 있는지, 어떤 기능에 해당하는지 살펴보겠습니다.
진행률 표시줄 및 재생 시간:
첫 번째는 노래의 전체 지속 시간을 얻은 다음 현재 재생 진행률에 전체 진행 길이를 곱하여 진행률 표시줄의 위치를 계산하는 진행률 표시줄 기능입니다. 술집.
function progressBar(){ var lenth=mList[index].duration; timer1=setInterval(function(){ cur=mList[index].currentTime;//获取当前的播放时间 progress.style.width=""+parseFloat(cur/lenth)*300+"px"; progressBtn.style.left= 60+parseFloat(cur/lenth)*300+"px"; },10) }
다음은 재생 시간을 변경하는 기능입니다. 여기서는 타이밍 기능을 설정하고 가끔씩 실행하여 재생 시간을 변경합니다. 우리가 얻은 노래 길이는 초 단위로 계산되므로 if 문을 사용하여 길이 판단을 변환하고 재생 시간을 분과 초 단위로 표시하도록 변경해야 합니다.
function playTimes(){ timer2=setInterval(function(){ cur=parseInt(mList[index].currentTime);//秒数 var minute=parseInt(cur/60); if (minute<10) { if(cur%60<10){ playTime.innerHTML="0"+minute+":0"+cur%60+""; }else{ playTime.innerHTML="0"+minute+":"+cur%60+""; } } else{ if(cur%60<10){ playTime.innerText= minute+":0"+cur%60+""; }else{ playTime.innerText= minute+":"+cur%60+""; } } },1000); }
재생 진행률 및 볼륨 조정:
다음으로 진행률 표시줄을 통해 재생 진행률 조정 및 볼륨 조정 기능을 완성해 보겠습니다.
재생 진행률 조정 기능은 이벤트 개체를 사용하여 구현됩니다. offsetX 속성은 IE 이벤트에서만 사용할 수 있으므로 IE 브라우저를 사용하여 효과를 보는 것이 좋습니다. 먼저 진행률 표시줄에 이벤트 리스너를 추가하고, 진행률 표시줄에서 마우스를 클릭하면 마우스의 위치를 구하고, 위치를 전체 진행률 표시줄 길이로 나누어 현재 재생 진행률을 계산합니다. 그러면 노래가 설정됩니다.
//调整播放进度 total.addEventListener("click",function(event){ var e = event || window.event; document.onmousedown = function(event){ var e = event || window.event; var mousePos1 = e.offsetX; var maxValue1 = total.scrollWidth; mList[index].currentTime = (mousePos1/300)*mList[index].duration; progress.style.width = mousePos1+"px"; progressBtn.style.left = 60+ mousePos1 +"px"; } })
다음은 볼륨 조절 기능입니다. 볼륨 조절을 위해 드래그를 사용합니다. 볼륨 바의 버튼 볼에 이벤트 모니터링을 추가한 다음 전체 볼륨 바를 기준으로 버튼 볼의 위치를 계산하는 것입니다. 마지막으로 계산 결과에 볼륨을 곱하여 현재 볼륨을 얻습니다.
volBtn.addEventListener("mousedown",function(event){ var e = event || window.event; var that =this; //阻止球的默认拖拽事件 e.preventDefault(); document.onmousemove = function(event){ var e = event || window.event; var mousePos2 = e.offsetY; var maxValue2 = vol.scrollHeight; if(mousePos2<0){ mousePos2 = 0; } if(mousePos2>maxValue2){ mousePos2=maxValue2; } mList[index].volume = (1-mousePos2/maxValue2); console.log(mList[index].volume); volBtn.style.top = (mousePos2)+"px"; volBar.style.height = 60-(mousePos2)+"px"; document.onmouseup = function(event){ document.onmousemove = null; document.onmouseup = null; } } })
노래 전환
마지막으로 더 복잡한 노래 전환 기능을 구현하겠습니다.
먼저 전환을 위해 이전 버튼과 다음 버튼을 사용하는 방법을 살펴보겠습니다. 음악을 전환할 때 주의해야 할 몇 가지 문제가 있습니다. 첫째, 현재 재생 중인 음악을 중지하고 다음 음악으로 전환해야 합니다. 막대와 재생 시간을 지우고 다시 계산해야 합니다. 셋째, 노래 정보가 그에 따라 변경되어야 하며 플레이어 아래의 재생 목록 스타일도 변경되어야 합니다. 위의 세 가지 사항을 파악한 후 기능 구현을 시작할 수 있습니다.
//上一曲 function prevM(){ clearInterval(timer1); clearInterval(timer2); stopM(); qingkong(); cleanProgress(); --index; if(index==-1){ index=mList.length-1; } clearListBgc(); document.getElementById("m"+index).style.backgroundColor = "#A71307"; document.getElementById("m"+index).style.color = "white"; changeInfo(index); mList[index].play(); progressBar(); playTimes(); if (mList[index].paused) { play.style.backgroundImage = "url(media/play.png)"; }else{ play.style.backgroundImage = "url(media/pause.png)"; } } //下一曲 function nextM(){ clearInterval(timer1); clearInterval(timer2); stopM(); qingkong(); cleanProgress(); ++index; if(index==mList.length){ index=0; } clearListBgc(); document.getElementById("m"+index).style.backgroundColor = "#A71307"; document.getElementById("m"+index).style.color = "white"; changeInfo(index); mList[index].play(); progressBar(); playTimes(); if (mList[index].paused) { play.style.backgroundImage = "url(media/play.png)"; }else{ play.style.backgroundImage = "url(media/pause.png)"; } }
아래 코드는 목록을 클릭하여 노래를 전환하는 것입니다.
m0.onclick = function (){ clearInterval(timer1); clearInterval(timer2); qingkong(); flag = false; stopM(); index = 0; pauseall(); play.style.backgroundImage = "url(media/pause.png)"; clearListBgc(); document.getElementById("m0").style.backgroundColor = "#A71307"; document.getElementById("m"+index).style.color = "white"; mList[index].play(); cleanProgress(); progressBar(); changeInfo(index); playTimes(); } m1.onclick = function (){ clearInterval(timer1); clearInterval(timer2); flag = false; qingkong(); stopM(); index = 1; pauseall(); clearListBgc(); play.style.backgroundImage = "url(media/pause.png)"; document.getElementById("m1").style.backgroundColor = "#A71307"; document.getElementById("m"+index).style.color = "white"; mList[index].play(); cleanProgress(); changeInfo(index); progressBar(); playTimes(); } m2.onclick = function (){ clearInterval(timer1); clearInterval(timer2); flag = false; qingkong(); stopM(); index = 2; pauseall(); play.style.backgroundImage = "url(media/pause.png)"; clearListBgc(); document.getElementById("m2").style.backgroundColor = "#A71307"; document.getElementById("m"+index).style.color = "white"; mList[index].play(); cleanProgress(); changeInfo(index); progressBar(); playTimes(); }
재생목록을 통해 노래를 전환한다는 아이디어는 버튼을 통해 전환하는 것과 유사합니다. 해당 목록 항목에 따라 현재 재생해야 할 노래를 설정하는 것뿐입니다.
첫 번째는 노래 정보 전환입니다. 위의 노래 전환 기능에는 여러 가지 메서드가 호출됩니다. 이러한 메서드의 용도를 살펴보겠습니다.
먼저 노래 정보를 전환하세요:
function changeInfo(index){ if (index==0) { musicName.innerHTML = "光辉岁月"; singer.innerHTML = "Beyond"; } if (index==1) { musicName.innerHTML = "Free Loop"; singer.innerHTML = "Daniel Powter"; } if (index==2) { musicName.innerHTML = "千里之外"; singer.innerHTML = "周杰伦、费玉清"; } }
그런 다음 두 개의 타이머를 삭제하세요:
//将进度条置0 function cleanProgress(timer1){ if(timer1!=undefined){ clearInterval(timer1); } progress.style.width="0"; progressBtn.style.left="60px"; } function qingkong(timer2){ if(timer2!=undefined){ clearInterval(timer2); } }
그런 다음 재생 중인 음악을 중지하고 재생 시간을 복원하세요.
function stopM(){ if(mList[index].played){ mList[index].pause(); mList[index].currentTime=0; flag=false; } }
이 시점에서 HTML5로 작성된 뮤직 플레이어는 기본적으로 완성되었으며, 완성 후에도 효과는 여전히 매우 좋습니다. 빨리 모아서 위의 튜토리얼을 바탕으로 HTML5를 사용하여 나만의 플레이어를 작성해보시길 바랍니다.

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











HTML의 테이블 테두리 안내. 여기에서는 HTML의 테이블 테두리 예제를 사용하여 테이블 테두리를 정의하는 여러 가지 방법을 논의합니다.

HTML 여백-왼쪽 안내. 여기에서는 HTML margin-left에 대한 간략한 개요와 코드 구현과 함께 예제를 논의합니다.

HTML의 Nested Table에 대한 안내입니다. 여기에서는 각 예와 함께 테이블 내에 테이블을 만드는 방법을 설명합니다.

HTML 테이블 레이아웃 안내. 여기에서는 HTML 테이블 레이아웃의 값에 대해 예제 및 출력 n 세부 사항과 함께 논의합니다.

HTML 입력 자리 표시자 안내. 여기서는 코드 및 출력과 함께 HTML 입력 자리 표시자의 예를 논의합니다.

HTML 순서 목록에 대한 안내입니다. 여기서는 HTML Ordered 목록 및 유형에 대한 소개와 각각의 예에 대해서도 설명합니다.

HTML에서 텍스트 이동 안내. 여기서는 Marquee 태그가 구문과 함께 작동하는 방식과 구현할 예제에 대해 소개합니다.

HTML onclick 버튼에 대한 안내입니다. 여기에서는 각각의 소개, 작업, 예제 및 다양한 이벤트의 onclick 이벤트에 대해 설명합니다.