實戰教程:如何用JavaScript構建一個功能強大的音樂播放器,兼容本地與在線資源

項目地址:Music Player App

作者:Reza Mehdikhanlou

視頻地址:youtube

我將向您展示如何使用 javascript 編寫音樂播放器。我們創建一個項目,您可以使用 javascript 從本地文件夾或任何 url 播放音頻文件。

項目目錄

  • assets
    • 1.jpg
    • 1.mp3
    • 2.jpg
    • 2.mp3
    • 3.jpg
    • 3.mp3
  • index.html
  • index.js
  • style.css

代碼

index.html

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"><link rel="stylesheet" href="style.css"><title>Music Player App</title>
</head><body><div class="background"><img src="" id="bg-img"></div><div class="container"><div class="player-img"><img src="" class="active" id="cover"></div><h2 id="music-title"></h2><h3 id="music-artist"></h3><div class="player-progress" id="player-progress"><div class="progress" id="progress"></div><div class="music-duration"><span id="current-time">0:00</span><span id="duration">0:00</span></div></div><div class="player-controls"><i class="fa-solid fa-backward" title="Previous" id="prev"></i><i class="fa-solid fa-play play-button" title="Play" id="play"></i><i class="fa-solid fa-forward" title="Next" id="next"></i></div></div><script src="index.js"></script>
</body></html>

index.js

const image = document.getElementById('cover'),title = document.getElementById('music-title'),artist = document.getElementById('music-artist'),currentTimeEl = document.getElementById('current-time'),durationEl = document.getElementById('duration'),progress = document.getElementById('progress'),playerProgress = document.getElementById('player-progress'),prevBtn = document.getElementById('prev'),nextBtn = document.getElementById('next'),playBtn = document.getElementById('play'),background = document.getElementById('bg-img');const music = new Audio();const songs = [{path: 'assets/1.mp3',// path:'https://childish.oss-cn-hangzhou.aliyuncs.com/songs/Peel%20Back%20the%20Heart.mp3'displayName: 'The Charmer\'s Call',cover: 'assets/1.jpg',artist: 'Hanu Dixit',},{path: 'assets/2.mp3',displayName: 'You Will Never See Me Coming',cover: 'assets/2.jpg',artist: 'NEFFEX',},{path: 'assets/3.mp3',displayName: 'Intellect',cover: 'assets/3.jpg',artist: 'Yung Logos',}
];let musicIndex = 0;
let isPlaying = false;function togglePlay() {if (isPlaying) {pauseMusic();} else {playMusic();}
}function playMusic() {isPlaying = true;// Change play button iconplayBtn.classList.replace('fa-play', 'fa-pause');// Set button hover titleplayBtn.setAttribute('title', 'Pause');music.play();
}function pauseMusic() {isPlaying = false;// Change pause button iconplayBtn.classList.replace('fa-pause', 'fa-play');// Set button hover titleplayBtn.setAttribute('title', 'Play');music.pause();
}function loadMusic(song) {music.src = song.path;title.textContent = song.displayName;artist.textContent = song.artist;image.src = song.cover;background.src = song.cover;
}function changeMusic(direction) {musicIndex = (musicIndex + direction + songs.length) % songs.length;loadMusic(songs[musicIndex]);playMusic();
}function updateProgressBar() {const { duration, currentTime } = music;const progressPercent = (currentTime / duration) * 100;progress.style.width = `${progressPercent}%`;const formatTime = (time) => String(Math.floor(time)).padStart(2, '0');durationEl.textContent = `${formatTime(duration / 60)}:${formatTime(duration % 60)}`;currentTimeEl.textContent = `${formatTime(currentTime / 60)}:${formatTime(currentTime % 60)}`;
}function setProgressBar(e) {const width = playerProgress.clientWidth;const clickX = e.offsetX;music.currentTime = (clickX / width) * music.duration;
}playBtn.addEventListener('click', togglePlay);
prevBtn.addEventListener('click', () => changeMusic(-1));
nextBtn.addEventListener('click', () => changeMusic(1));
music.addEventListener('ended', () => changeMusic(1));
music.addEventListener('timeupdate', updateProgressBar);
playerProgress.addEventListener('click', setProgressBar);loadMusic(songs[musicIndex]);

style.css

@import url('https://fonts.googleapis.com/css2?family=Ubuntu:wght@300;400;500;700&display=swap');html{box-sizing: border-box;
}body{margin: 0;font-family: 'Ubuntu', sans-serif;font-size: 12px;min-height: 100vh;display: flex;align-items: center;justify-content: center;
}.background{position: fixed;width: 200%;height: 200%;top: -50%;left: -50%;z-index: -1;
}.background img{position: absolute;margin: auto;top: 0;left: 0;bottom: 0;right: 0;min-width: 50%;min-height: 50%;filter: blur(15px);-webkit-filter: blur(50px);transform: scale(1.1);
}.container{background-color: #e7e7e7;height: 500px;width: 400px;border-radius: 20px;box-shadow: 0 15px 30px rgba(0, 0, 0, 0.3);transition: all 0.5s ease;
}.container:hover{box-shadow: 0 15px 30px rgba(0, 0, 0, 0.6);
}.player-img{width: 300px;height: 300px;position: relative;top: -50px;left: 50px;
}.player-img img{object-fit: cover;border-radius: 20px;height: 0;width: 0;opacity: 0;box-shadow: 0 5px 30px 5px rgba(0, 0, 0, 0.5);
}.player-img:hover img{box-shadow: 0 5px 30px 5px rgba(0, 0, 0, 0.8);
}.player-img img.active{width: 100%;height: 100%;transition: all 0.5s;opacity: 1;
}h2{font-size: 25px;text-align: center;font-weight: 500;margin: 10px 0 0;
}h3{font-size: 18px;text-align: center;font-weight: 500;margin: 10px 0 0;
}.player-progress{background-color: #fff;border-radius: 5px;cursor: pointer;margin: 40px 20px 35px;height: 6px;width: 90%;
}.progress{background-color: #212121;border-radius: 5px;height: 100%;width: 0%;transition: width 0.1s linear;
}.music-duration{position: relative;top: -25px;display: flex;justify-content: space-between;
}.player-controls{position: relative;top: -15px;left: 120px;width: 200px;
}.fa-solid{font-size: 30px;color: #666;margin-right: 30px;cursor: pointer;user-select: none;transition: all 0.3s ease;
}.fa-solid:hover{filter: brightness(40%);
}.play-button{font-size: 44px;position: relative;top: 3px;
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/40709.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/40709.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/40709.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

頂級10大AI測試工具

每周跟蹤AI熱點新聞動向和震撼發展 想要探索生成式人工智能的前沿進展嗎&#xff1f;訂閱我們的簡報&#xff0c;深入解析最新的技術突破、實際應用案例和未來的趨勢。與全球數同行一同&#xff0c;從行業內部的深度分析和實用指南中受益。不要錯過這個機會&#xff0c;成為AI領…

暑期編程預習指南

暑期編程預習指南 高考結束后&#xff0c;迎來的是一段難得的假期時光。對于那些有志于踏入IT領域的高考生來說&#xff0c;這段時間無疑是一個重要的起點。為了幫助你們更好地利用這個假期&#xff0c;為未來的學習和職業生涯打下堅實的基礎&#xff0c;特此提供一份編程預習…

JWT入門

JWT與TOKEN JWT&#xff08;JSON Web Token&#xff09;是一種基于 JSON 格式的輕量級安全令牌&#xff0c;通常用于在網絡應用間安全地傳遞信息。而“token”一詞則是一個更廣泛的術語&#xff0c;用來指代任何形式的令牌&#xff0c;用于在計算機系統中進行身份驗證或授權。J…

【?講解下Laravel為什么會成為最優雅的PHP框架?】

&#x1f3a5;博主&#xff1a;程序員不想YY啊 &#x1f4ab;CSDN優質創作者&#xff0c;CSDN實力新星&#xff0c;CSDN博客專家 &#x1f917;點贊&#x1f388;收藏?再看&#x1f4ab;養成習慣 ?希望本文對您有所裨益&#xff0c;如有不足之處&#xff0c;歡迎在評論區提出…

cloudreve 設置開機服務

創建一個Systemd服務文件&#xff1a; 打開終端并創建一個新的服務文件&#xff1a; sudo nano /etc/systemd/system/cloudreve.service 在服務文件中添加以下內容&#xff1a; 根據你的設置調整路徑和參數&#xff0c;然后將以下配置粘貼到文件中&#xff1a; [Unit] Descri…

Django學習第四天

啟動項目命令 python manage.py runserver 分頁功能封裝到類中去 封裝的類的代碼 """ 自定義的分頁組件,以后如果想要使用這個分頁組件&#xff0c;你需要做&#xff1a; def pretty_list(request):# 靚號列表data_dict {}search_data request.GET.get(q, &…

Excel為數據繪制拆線圖,并將均值線疊加在圖上,以及整個過程的區域錄屏python腳本

Excel為數據繪制拆線圖,并將均值線疊加在圖上,以及整個過程的區域錄屏python腳本 1.演示動畫A.視頻B.gif動畫 2.跟蹤鼠標區域的錄屏腳本 Excel中有一組數據,希望畫出曲線,并且能把均值線也繪制在圖上,以下動畫演示了整個過程,并且提供了區域錄屏腳本,原理如下: 為節約空間,避免…

從華為和特斯拉之爭,看智能駕駛的未來

“一旦特斯拉完全解決自動駕駛問題并量產Optimus&#xff0c;任何空頭都將被消滅&#xff0c;即使是比爾-蓋茨也不例外。”7月2日&#xff0c;馬斯克再次在社交媒體X上畫下了這樣的“大餅”。 與此同時&#xff0c;特斯拉的股價在最近的三個交易日也迎來了24%的漲幅&#xff0c…

中俄汽車產業鏈合作前景廣闊,東方經濟論壇助力雙邊合作與創新

隨著中國汽車零部件企業的競爭力和創新能力不斷增強&#xff0c;中國汽車及零部件行業在俄羅斯的市場份額和品牌影響力顯著提升&#xff0c;中俄兩國在汽車產業鏈上的合作展現出巨大的潛力和廣闊的前景。2024年5月&#xff0c;俄羅斯乘用車新車銷量達到12.8萬輛&#xff0c;同比…

7.基于SpringBoot的SSMP整合案例-表現層開發

目錄 1.基于Restfu1進行表現層接口開發 1.1創建功能類 1.2基于Restful制作表現層接口 2.接收參數 2使用Apifox測試表現層接口功能 保存接口&#xff1a; 分頁接口&#xff1a; 3.表現層一致性處理 3.1先創建一個工具類&#xff0c;用作后端返回格式統一類&#xff1a;…

SpringMVC 的工作流程和詳細解釋

Spring MVC&#xff08;Model-View-Controller&#xff09;框架是基于經典的 MVC 設計模式構建的&#xff0c;用于開發 Web 應用程序。下面是 Spring Boot MVC 的工作流程和詳細解釋&#xff1a; 1.客戶端發起請求 1.客戶端&#xff08;通常是瀏覽器&#xff09;發起 HTTP 請求…

招聘智能管理系統設計

設計一個招聘智能管理系統&#xff0c;需要從多個維度考慮&#xff0c;包括但不限于用戶界面、功能模塊、數據安全、算法模型等。以下是一個基本的設計框架&#xff1a; 1. 系統架構&#xff1a; 前端&#xff1a;提供直觀的用戶界面&#xff0c;包括應聘者和招聘者的登錄/注冊…

Python學習篇:Python基礎知識(三)

目錄 1 Python保留字 2 注釋 3 行與縮進 ?編輯4 多行語句 5 輸入和輸出 6 變量 7 數據類型 8 類型轉換 9 表達式 10 運算符 1 Python保留字 Python保留字&#xff08;也稱為關鍵字&#xff09;是Python編程語言中預定義的、具有特殊含義的標識符。這些保留字不能用作…

Android 工具腳本

工具腳本 Shell腳本 獲取Git分支名稱 def gitBranch() {def branch ""def proc "git rev-parse --abbrev-ref HEAD".execute()proc.in.eachLine { line -> branch line }proc.err.eachLine { line -> println line }proc.waitFor()branch }

生信算法9 - 正則表達式匹配氨基酸序列、核型和字符串

1. 使用正則表達式匹配指定的氨基酸序列 import re# 氨基酸序列 seq VSVLTMFRYAGWLDRLYMLVGTQLAAIIHGVALPLMMLI# 正則表達式匹配 match re.search(r[A|G]W, seq)# 打印match及匹配到開始位置和結束位置 print(match) # <re.Match object; span(10, 12), matchGW> prin…

DP學習——觀察者模式

學而時習之&#xff0c;溫故而知新。 2個角色 分為啥主題和觀察者角色。 我覺得主題就是干活的&#xff0c;打工仔&#xff0c;為觀察者干活。 一對多。一個主題&#xff0c;多個觀察者——就像一個開發人員對多個項目經理——項目經理拿小皮鞭抽呀抽呀&#xff0c;受不了。 …

代碼隨想錄算法訓練營第70天圖論9[1]

代碼隨想錄算法訓練營第70天:圖論9 ? 拓撲排序精講 卡碼網&#xff1a;117. 軟件構建(opens new window) 題目描述&#xff1a; 某個大型軟件項目的構建系統擁有 N 個文件&#xff0c;文件編號從 0 到 N - 1&#xff0c;在這些文件中&#xff0c;某些文件依賴于其他文件的…

5款軟件讓電腦更方便,更快,更好看

? 你有沒有想過&#xff0c;有些軟件能讓你的電腦用起來更方便&#xff0c;更快&#xff0c;更好看&#xff1f; 1. 屏幕動畫創作——Screen To Gif ? Screen To Gif是一款功能強大的屏幕錄制軟件&#xff0c;專注于將屏幕上的動態內容轉換為高質量的GIF動畫。它不僅支持自…

《ClipCap》論文筆記(下)

原文出處 [2111.09734] ClipCap: CLIP Prefix for Image Captioning (arxiv.org) 原文翻譯 接上篇 《ClipCap》論文筆記&#xff08;上&#xff09;-CSDN博客 4. Results Datasets.我們使用 COCO-captions [7,22]、nocaps [1] 和 Conceptual Captions [33] 數據集。我們根…

自動化設備上位機設計 一

目錄 一 設計原型 二 后臺代碼 一 設計原型 二 后臺代碼 namespace 自動化上位機設計 {public partial class Form1 : Form{public Form1(){InitializeComponent();}private void Form1_Load(object sender, EventArgs e){}} }namespace 自動化上位機設計 {partial class Fo…