效果
html+css+js本地音樂(lè)播放器,實(shí)現(xiàn)可視化音頻頻譜
前言
之前用swing寫(xiě)了個(gè)本地音樂(lè)播放器(如下圖),但是效果一言難盡,界面丑,功能bug也多,唉
所以后面又重新用html寫(xiě)了個(gè),界面樣式和功能方面,比swing寫(xiě)的好看、完善多了。
功能
- 導(dǎo)入音樂(lè)(已完成)
- 展示列表(已完成)
- 列表雙擊播放(已完成)
- 列表循環(huán)、單曲循環(huán)、隨機(jī)播放(已完成)
- 上一首、下一首、播放、暫停(已完成)
- 計(jì)算音樂(lè)時(shí)長(zhǎng)(已完成)
- 音樂(lè)播放進(jìn)度條(已完成)
- 進(jìn)度條點(diǎn)擊,音樂(lè)播放位置跳轉(zhuǎn),進(jìn)度條位置跟著跳轉(zhuǎn)(已完成)
- 環(huán)形頻譜(已完成)
廢話不多說(shuō),直接上代碼。
代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>音樂(lè)播放器</title>
<style>
*{
margin: 0 auto;
}
body{
/*background-color: rgb(104,118,138);*/
background: url("img/bg.jpg");
background-position: center;
background-repeat: no-repeat;
background-attachment: fixed;
background-size:100%;
}
/* 設(shè)置滾動(dòng)條的樣式 */
::-webkit-scrollbar {
width:5px;
}
/* 滾動(dòng)槽 */
::-webkit-scrollbar-track {
-webkit-box-shadow:inset 0 0 6px rgba(0,0,0,0.3);
border-radius:10px;
}
/* 滾動(dòng)條滑塊 */
::-webkit-scrollbar-thumb {
border-radius:10px;
background:rgba(0,0,0,0.1);
-webkit-box-shadow:inset 0 0 6px rgba(0,0,0,0.5);
}
::-webkit-scrollbar-thumb:window-inactive {
background:rgba(255,0,0,0.4);
}
.main{
position: relative;
top: 20px;
width: 520px;
height: 600px;
background:rgba(30,144,255,0.4);
box-shadow: 0 15px 50px rgb(0,0,0);
border-radius: 10px;
outline: 0;
}
.musicBox{
position: absolute;
width: 520px;
height: 40px;
line-height: 40px;
vertical-align: center;
}
.buttons{
position: absolute;
display: inline-block;
height:40px;
width: 40px;
cursor: pointer;
}
#fileBox{
left: 0px;
background: url("img/音樂(lè)按鈕.png");
background-position: 0 0;
background-repeat: no-repeat;
}
#fileBox:hover{
left: 0px;
background: url("img/音樂(lè)按鈕.png");
background-position: 0px -40px;
background-repeat: no-repeat;
}
.file{
position: absolute;
left: 0px;
opacity: 0;
height:40px;
width: 40px;
cursor: pointer;
font-size:0;
}
#pre{
left: 40px;
background: url("img/音樂(lè)按鈕.png");
background-position: 0px -80px;
background-repeat: no-repeat;
}
#pre:hover{
background: url("img/音樂(lè)按鈕.png");
background-position: 0px -120px;
background-repeat: no-repeat;
}
#startStop{
left: 80px;
}
.start{
background: url("img/音樂(lè)按鈕.png");
background-position: 0px -160px;
background-repeat: no-repeat;
}
.start:hover{
background: url("img/音樂(lè)按鈕.png");
background-position: 0px -200px;
background-repeat: no-repeat;
}
.stop{
background: url("img/音樂(lè)按鈕.png");
background-position: 0px -240px;
background-repeat: no-repeat;
}
.stop:hover{
background: url("img/音樂(lè)按鈕.png");
background-position: 0px -280px;
background-repeat: no-repeat;
}
#next{
left: 120px;
background: url("img/音樂(lè)按鈕.png");
background-position: 0px -320px;
background-repeat: no-repeat;
}
#next:hover{
background: url("img/音樂(lè)按鈕.png");
background-position: 0px -360px;
background-repeat: no-repeat;
}
#playType{
left: 165px;
}
.lbxh{
background: url("img/音樂(lè)按鈕.png");
background-position: 0px -400px;
background-repeat: no-repeat;
}
.lbxh:hover{
background: url("img/音樂(lè)按鈕.png");
background-position: 0px -440px;
background-repeat: no-repeat;
}
.dqxh{
background: url("img/音樂(lè)按鈕.png");
background-position: 0px -480px;
background-repeat: no-repeat;
}
.dqxh:hover{
background: url("img/音樂(lè)按鈕.png");
background-position: 0px -520px;
background-repeat: no-repeat;
}
.sjbf{
background: url("img/音樂(lè)按鈕.png");
background-position: 0px -560px;
background-repeat: no-repeat;
}
.sjbf:hover{
background: url("img/音樂(lè)按鈕.png");
background-position: 0px -600px;
background-repeat: no-repeat;
}
#progressDiv{
position: absolute;
left: 205px;
height:40px;
width: 310px;
cursor: pointer;
color: aliceblue;
font-size: 14px;
}
#progressDiv .times{
height: 40px;
line-height: 40px;
text-align: center;
display: inline-block;
color: #515151;
}
#progressDiv .times:hover{
color: #2c2c2c;
}
#progressDiv .progress{
position: absolute;
top: 20px;
left: 90px;
border-radius:20px;
}
#progressBar{
border: 2px solid;
box-shadow: 0px 0px 10px 5px #3b8cf8, 0 0 1px #3b8cf8, 0 0 1px #3b8cf8, 0 0 1px #3b8cf8, 0 0 1px #3b8cf8, 0 0 1px #3b8cf8, 0 0 1px #3b8cf8;
color: #fff;
}
.musicList{
position: absolute;
top: 40px;
left: 10px;
width: 500px;
height: 540px;
overflow: auto;
border: 1px solid rgba(30,144,255,0.5);
}
#musicList{
/*position: absolute;*/
list-style: none;
margin: 0px;
padding: 2px 10px;
width: 480px;
height: 530px;
}
#musicList>li{
position: relative;
padding: 10px;
overflow: hidden;
cursor: pointer;
margin: 5px 2px;
font-size: 14px;
text-shadow: 0 0 2px red,0 0 10px red,0 0 30px red,0 0 10px red;
}
#musicList>li:hover{
background-color:rgba(30,144,255, 0.5);
color: rgb(255,255,255);
}
.liFocus{
background-color:rgba(30,144,255, 0.5);
color: rgb(255,255,255);
}
.liDefocus{
background-color: rgba(135,206,250, 0.5);
color: #2c2c2c;
}
/* 讓canvas位于ul標(biāo)簽下面 */
#wrap{
z-index: -1;
position: absolute;
top: 40px;
left: 10px;
}
</style>
</head>
<body>
<div class="main">
<div class="musicBox">
<div class="buttons fileBox" id="fileBox">
<input type="file" id="file" class="file" multiple="multiple" accept="audio/*">
</div>
<div class="buttons" id="pre"></div>
<div class="buttons start" id="startStop"></div>
<div class="buttons" id="next"></div>
<div class="buttons lbxh" id="playType"></div>
<div class="progressDiv" id="progressDiv">
<div class="times" id="rollTime" >00:00</div>
<div class="times">/</div>
<div class="times" id="totalTime">00:00</div>
<div class="progress" id="totalProgress" style="width: 210px;border: 2px solid #68768A;"></div>
<div class="progress" id="progressBar"></div>
</div>
</div>
<div class="musicList">
<ul id="musicList"></ul>
</div>
<canvas id="wrap"></canvas>
</div>
<script>
let file = document.getElementById('file'), // 導(dǎo)入歌曲
pre = document.getElementById('pre'), // 上一首
startStop = document.getElementById('startStop'), //播放、暫停
next = document.getElementById('next'), // 下一首
playType = document.getElementById('playType'), // 切換播放方式
rollTime = document.getElementById('rollTime'), // 實(shí)時(shí)播放時(shí)間
totalTime = document.getElementById('totalTime'), // 總時(shí)長(zhǎng)
progressBar = document.getElementById('progressBar'), // 歌曲實(shí)時(shí)進(jìn)度條
totalProgress = document.getElementById('totalProgress'), // 歌曲總進(jìn)度條
liIdPrefix = 'mli', // 音樂(lè)列表li的id前綴
listContainer = document.getElementById('musicList'); // 音樂(lè)列表
let audio = new Audio();
var playTypeNum = 1,// 默認(rèn)是列表循環(huán)(1 列表循環(huán) 2 單曲循環(huán) 3 隨機(jī)播放)
current, // 當(dāng)前音樂(lè)播放索引
preIndex, // 上一個(gè)播放的索引(因?yàn)楫?dāng)前播放音樂(lè)所在的li會(huì)有個(gè)聚焦的class樣式,因此在改變當(dāng)前播放之前,先記錄當(dāng)前播放索引,用于清空聚焦的class樣式)
fileList = [];
// 音頻可視化
wrap.width = 500;
wrap.height = 540;
const canvasCtx = wrap.getContext("2d");
const AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext;
let audioContext = new AudioContext();//實(shí)例化
let sources; // 音頻源
/**
* 加載音樂(lè)文件列表
*/
file.onchange = function (e){
if (e.target.files.length>0){
fileList = e.target.files;
showMusiclist(fileList);
current = 0;
preIndex = undefined; // 每次重新導(dǎo)入了音樂(lè),將 上一個(gè)播放的索引 重置為undefined
loadMusicAndPlay(current);
}
}
/**
* 展示音樂(lè)列表
*/
function showMusiclist(list){
var container = document.createDocumentFragment();
for(var i = 0; i < list.length ; i++ ){
var file = list[i]
var node = document.createElement('li'); // 創(chuàng)建li元素
node.id = liIdPrefix + i; // 設(shè)置li的id
node.innerText = '[' + (i+1) + '] ' + file.name;
node.className = 'liDefocus'; // 設(shè)置li的class樣式
container.appendChild(node);
}
// 每次列表添加數(shù)據(jù)之前,先清空之前的列表
while (listContainer.firstChild) {
listContainer.removeChild(listContainer.firstChild);
}
listContainer.appendChild(container);
}
/**
* 切換播放方式
*/
playType.onclick = function (){
if (playTypeNum == 1){ // 當(dāng)前播放為列表循環(huán),點(diǎn)擊切換播放方式時(shí),改為單曲循環(huán)
console.log('列表循環(huán)====>>>單曲循環(huán)');
playTypeNum = 2;
playType.className = "buttons dqxh"; // 設(shè)置單曲循環(huán)的class
}else if (playTypeNum == 2){ // 當(dāng)前播放為單曲循環(huán),點(diǎn)擊切換播放方式時(shí),改為隨機(jī)播放
console.log('單曲循環(huán)====>>>隨機(jī)播放');
playTypeNum = 3;
playType.className = "buttons sjbf"; // 設(shè)置隨機(jī)播放的class
}else { // 當(dāng)前播放為隨機(jī)播放,點(diǎn)擊切換播放方式時(shí),改為列表循環(huán)
console.log('隨機(jī)播放====>>>列表循環(huán)');
playTypeNum = 1;
playType.className = "buttons lbxh"; // 設(shè)置列表循環(huán)的class
}
}
/**
* 根據(jù)播放方式,播放音樂(lè)
*/
function playTypeChange(){
preIndex = current; // 每次改變當(dāng)前播放時(shí),記錄當(dāng)前播放的索引
if (playTypeNum == 1){ // 列表循環(huán)
if(current >= fileList.length - 1){
current = 0;
loadMusicAndPlay(current);
}else{
loadMusicAndPlay(++current);
}
}else if(playTypeNum == 2){ // 單曲循環(huán)
// 單曲循環(huán)不改變播放索引
console.log(current);
loadMusicAndPlay(current);
}else {
// 隨機(jī)播放,生成隨機(jī)數(shù)
current = Math.floor(Math.random()*fileList.length);
loadMusicAndPlay(current);
}
}
/**
* 雙擊切換播放
*/
listContainer.ondblclick = function(e){
if(e.target.tagName.toLowerCase() === 'li'){
for(var i = 0; i < this.children.length; i++){
if(this.children[i] === e.target){
preIndex = current; // 切換播放之前,先記錄當(dāng)前播放索引
current = i
}
}
console.log('第%d首', current + 1)
loadMusicAndPlay(current);
}
}
/**
* 上一曲
*/
pre.onclick = function (){
if (fileList.length>0){
console.log('點(diǎn)擊播放上一首!');
preIndex = current;
if (current == 0){
current = fileList.length-1;
loadMusicAndPlay(current);
}else {
loadMusicAndPlay(--current);
}
}
}
/**
* 下一曲
*/
next.onclick = function (){
if (fileList.length>0) {
console.log('點(diǎn)擊播放下一首!');
preIndex = current;
if (current >= fileList.length - 1) {
current = 0;
loadMusicAndPlay(current);
} else {
loadMusicAndPlay(++current);
}
}
}
/**
* 播放暫停
*/
startStop.onclick = function (){
startOrStop();
}
/**
* 播放或暫停
*/
function startOrStop(){
if (fileList.length>0) {
if (audio.paused) { // 如果當(dāng)前音樂(lè)是暫停狀態(tài),點(diǎn)擊按鈕,則改為播放狀態(tài)
startStop.className = "buttons start"; // 設(shè)置播放的class
audio.play();
} else { // 如果當(dāng)前音樂(lè)是播放狀態(tài),點(diǎn)擊按鈕,則改為暫停狀態(tài)
startStop.className = "buttons stop"; // 設(shè)置暫停的class
audio.pause();
}
}
}
/**
* 加載音樂(lè)、播放
*/
function loadMusicAndPlay(id){
var file = fileList[id];
progressBar.setAttribute('style','width:0');// 重置進(jìn)度條
if (!Object.is(preIndex,undefined)){ // 如果上一次播放索引不為undefined
listContainer.children[preIndex].className = 'liDefocus';
}
listContainer.children[id].className = 'liFocus'; // 聚焦當(dāng)前行
// 如果音樂(lè)是暫停狀態(tài),切換播放,則改為播放狀態(tài)
if (audio.paused){
startStop.className = "buttons start"; // 設(shè)置播放的class
}
audioContext.resume();
var fileReader = new FileReader();
fileReader.readAsDataURL(file); // 文件讀取為url
fileReader.onload = function(e) {
audio.src = e.target.result;
audio.volume = 0.2; // 設(shè)置起始音量
// 當(dāng)音頻源為undefined時(shí)才創(chuàng)建
if (Object.is(sources,undefined)){
/**
畫(huà)頻譜,需要用到audioContext。我們通過(guò)audio元素來(lái)創(chuàng)建音頻源。
注意:在這里音頻源不能多次創(chuàng)建,因?yàn)槲覀兊腶udio元素是全局變量,在每次切換播放的時(shí)候,
并沒(méi)有重新new Audio,這說(shuō)明不管放那一首歌,audio始終是同一個(gè)元素(對(duì)象),只是改變了它的src屬性值,
因此我們創(chuàng)建音源的時(shí)候也只能創(chuàng)建一次。
如果每次切換都創(chuàng)建音源會(huì)報(bào)錯(cuò),除非每次切換歌曲的時(shí)候都創(chuàng)建一遍audio,這樣每一次的audio都不同,
這樣音源才可以也跟著每次都創(chuàng)建一遍
*/
//創(chuàng)建一個(gè)MediaElementAudioSourceNode接口來(lái)關(guān)聯(lián)audio元素的音頻。
sources = audioContext.createMediaElementSource(audio);
}
var analyser = audioContext.createAnalyser();
// 連接到音頻分析器,分析頻譜
sources.connect(analyser);
analyser.connect(audioContext.destination);
繪制頻譜(analyser,file.name); // 繪制音頻頻譜
audio.play();
}
}
function 繪制頻譜(analyser,name){
var oW = wrap.width;
var oH = wrap.height;
var color1 = canvasCtx.createLinearGradient(oW/2, 0, oW, oH / 2);
color1.addColorStop(0, '#FFF');
color1.addColorStop(.2, '#FFFF00');
color1.addColorStop(.25, '#FF4500');
color1.addColorStop(.4, '#00FF7F');
color1.addColorStop(.5, '#FFD700');
color1.addColorStop(.75, '#FFFAFA');
color1.addColorStop(.85, '#00FF7F');
color1.addColorStop(1, '#FF00FF');
/*var color2=canvasCtx.createLinearGradient(0,0,oW,oH);
color2.addColorStop(0, '#1E90FF');
color2.addColorStop(.25, '#FFD700');
color2.addColorStop(.5, '#8A2BE2');
color2.addColorStop(.75, '#4169E1');
color2.addColorStop(1, '#FF0000');*/
var output = new Uint8Array(360);
var du = 2,//角度
R = 160,//半徑
W = 3;//寬
(function drawSpectrum() {
analyser.getByteFrequencyData(output);
canvasCtx.clearRect(0, 0, wrap.width, wrap.height);
for (var i = 0; i < 360; i++) {
var value = output[i] / 8;
canvasCtx.beginPath();
canvasCtx.lineWidth = W;
Rv1 = (R -value);
Rv2 = (R +value);
canvasCtx.moveTo((Math.sin((i * du) / 180 * Math.PI) * Rv1 + oW/2),-Math.cos((i * du) / 180 * Math.PI) * Rv1 + oH/2);
canvasCtx.lineTo((Math.sin((i * du) / 180 * Math.PI) * Rv2 + oW/2),-Math.cos((i * du) / 180 * Math.PI) * Rv2 + oH/2);
canvasCtx.strokeStyle = color1;//線條的顏色
canvasCtx.stroke();
}
canvasCtx.font = "14px 華文楷體";
// 設(shè)置顏色
canvasCtx.fillStyle = color1;
// 設(shè)置水平對(duì)齊方式
canvasCtx.textAlign = "center";
// 設(shè)置垂直對(duì)齊方式
canvasCtx.textBaseline = "middle";
// 繪制文字(參數(shù):要寫(xiě)的字,x坐標(biāo),y坐標(biāo))
canvasCtx.fillText(name, oW/2, oH/2);
requestAnimationFrame(drawSpectrum);
})();
}
/**
* 監(jiān)聽(tīng)音頻是否播放完畢,播放完畢繼續(xù)播放下一首
*/
audio.addEventListener('ended', function () {
console.log('音頻播放完畢,開(kāi)始播放下一首!');
playTypeChange();
}, false);
/**
* 監(jiān)聽(tīng)音頻加載事件(元數(shù)據(jù)加載),獲取音頻時(shí)長(zhǎng)
*/
audio.addEventListener("loadedmetadata", function () {
totalTime.textContent = getFormatterDate(audio.duration);
});
/**
* 監(jiān)聽(tīng)音頻播放時(shí)間更新事件,實(shí)時(shí)更新當(dāng)前播放時(shí)間和進(jìn)度條
*/
audio.addEventListener( "timeupdate" , function (){
var currentTime = audio.currentTime; // 當(dāng)前播放時(shí)間
var totalTime = audio.duration; // 總時(shí)間
// 當(dāng)是數(shù)字的時(shí)候
if (!isNaN(totalTime)) {
rollTime.textContent = getFormatterDate(currentTime);// 當(dāng)前播放時(shí)間
var width = Math.floor(currentTime / totalTime * 210);// 得到播放時(shí)間與總時(shí)長(zhǎng)的比值
// 設(shè)置進(jìn)度條走動(dòng)
progressBar.setAttribute('style','width:'+width+'px');
}
});
/**
* 監(jiān)聽(tīng)進(jìn)度條點(diǎn)擊事件
*/
totalProgress.addEventListener("click",function (event) {
updateTime(event.offsetX);// 獲取鼠標(biāo)所在位置,更新播放時(shí)間和進(jìn)度條
});
/**
* 監(jiān)聽(tīng)進(jìn)度條點(diǎn)擊事件
*/
progressBar.addEventListener("click",function (event) {
updateTime(event.offsetX);// 獲取鼠標(biāo)所在位置,更新播放時(shí)間和進(jìn)度條
});
/**
* 更新播放時(shí)間和進(jìn)度條
*/
function updateTime(x){
if (fileList.length>0) {
var bfb = x / 210 * 100;
audio.currentTime = audio.duration*+bfb/100;
var width = Math.floor(audio.currentTime / audio.duration * 210);// 得到播放時(shí)間與總時(shí)長(zhǎng)的比值
// 設(shè)置進(jìn)度條走動(dòng)
progressBar.setAttribute('style','width:'+width+'px');
}
}
/**
* 格式化時(shí)間(00:00)
*/
function getFormatterDate(time){
var m = parseInt(time / 60 );// 分
var s = parseInt(time % 60 );// 秒
// 補(bǔ)零
m = m > 9 ? m : "0" + m;
s = s > 9 ? s : "0" + s;
return m + ":" + s;
}
// 調(diào)用事件
window.onkeydown = function (e) {
if (e.keyCode==80 && e.ctrlKey && e.altKey){
console.log('按下了快捷鍵:ctrl+alt+p 鍵');
startOrStop();
}
}
</script>
</body>
</html>
頻譜方面,是我以前寫(xiě)的一篇 js實(shí)現(xiàn)環(huán)形可視化音頻 博客里面的代碼直接拿過(guò)來(lái)用了,改動(dòng)一點(diǎn)顏色和大小。
最后
我在想等有空的時(shí)候,能不能把這個(gè)頁(yè)面改成chrome擴(kuò)展,不過(guò)這需要另外花點(diǎn)時(shí)間去學(xué)擴(kuò)展的開(kāi)發(fā)方式了,只能等有空的時(shí)候研究下。然后swing寫(xiě)的那個(gè)播放器,我后面有空也會(huì)花時(shí)間完善下,等沒(méi)什么bug了,會(huì)再寫(xiě)篇文章。
全部代碼和用到的圖標(biāo)資源下載:點(diǎn)我下載文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-490549.html
如果沒(méi)有積分也沒(méi)關(guān)系,我還上傳到gitee了:html音樂(lè)播放器文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-490549.html
到了這里,關(guān)于html+css+js本地音樂(lè)播放器,實(shí)現(xiàn)可視化音頻頻譜的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!