首页 前端知识 实战教程:如何用JavaScript构建一个功能强大的音乐播放器,兼容本地与在线资源

实战教程:如何用JavaScript构建一个功能强大的音乐播放器,兼容本地与在线资源

2024-09-28 23:09:33 前端知识 前端哥 439 543 我要收藏

项目地址: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 Back the Heart.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 icon
    playBtn.classList.replace('fa-play', 'fa-pause');
    // Set button hover title
    playBtn.setAttribute('title', 'Pause');
    music.play();
}

function pauseMusic() {
    isPlaying = false;
    // Change pause button icon
    playBtn.classList.replace('fa-pause', 'fa-play');
    // Set button hover title
    playBtn.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;
}
转载请注明出处或者链接地址:https://www.qianduange.cn//article/18645.html
标签
评论
发布的文章
大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!