HTML+JavaScript+CSS+JQuery实现音乐播放器

本文介绍了一个使用HTML、CSS和JavaScript自制的音乐播放器,包括重新开始播放、上一曲、下一曲、暂停/继续、静音、音量调节和进度条控制等功能。通过引入jQuery和iconfont,实现了音乐播放的各种交互效果,并详细展示了代码实现过程。
摘要由CSDN通过智能技术生成

音乐播放器效果如下

在这里插入图片描述

包含的功能

  1. 重新开始播放
  2. 上一曲
  3. 下一曲
  4. 暂停、继续播放
  5. 静音
  6. 调节音量
  7. 可调节播放进度条
  8. 自动播放下一曲

代码

  1. HTML代码
    HTML就是一个基本的网页结果,什么地方有什么样的标签,其中也引用了iconfont字体图标,还有引入JS和CSS文件以及设置网站图标
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>MusciPlayer</title>
		<script src="https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js"></script>
		<script src="./js/index.js"></script>
		<link href="./css/index.css" rel="stylesheet" />
		<link rel="shortcut icon" href="./img/favicon.ico" type="image/x-icon" />
	</head>
	<body>
		<!-- 容器 -->
		<div class="container">
			<!-- 播放器盒子 -->
			<div class="musicbox">
				<!-- 图片歌曲信息 -->
				<div class="music-detail">
					<!-- 图片 -->
					<div class="music-img">
					</div>
					<!-- 歌曲信息 -->
					<div class="music-info">
					</div>
				</div>
				<!-- 相关操作 -->
				<div class="music-control">
					<!-- 进度条 -->
					<div class="runningbox">
						<div class="start">00:00</div>
						<div class="running" onclick="changeProgress()">
							<div class="running1">
							</div>
						</div>
						<div class="end">00:00</div>
					</div>
					<div class="control">
						<!-- 停止 -->
						<span id="replay" class="iconfont" onclick="replayMusic()">&#xe63d;</span>
						<!-- 上一曲 -->
						<span id="pre" class="iconfont" onclick="preMusic()">&#xe63c;</span>
						<!-- 播放 -->
						<span id="pause" class="iconfont" onclick="pauseMusic()">&#xe63b;</span>
						<!-- 下一曲 -->
						<span id="next" class="iconfont" onclick="nextMusic()">&#xe63e;</span>
						<!-- 音量 -->
						<div class="vulme">
							<span id="mute" class="iconfont" onclick="muteMusic()">&#xe641;</span>
							<div class="vulmeBar">
								<div class="vulmeBar1" onclick="changeVulme()"></div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</body>
</html>

  1. CSS代码
    CSS部分都是比较简单的代码,但是难一点的是用JQuery操作CSS属性来实现进度条以及音量调节条,以及还有引入了iconfont字体和设置动画
* {
	margin: 0;
	padding: 0;
}

/* 容器 */
.container {
	position: absolute;
	height: 100vh;
	width: 100vw;
	background-color: cornflowerblue;
}

/* 播放器盒子 */
.musicbox {
	position: relative;
	height: 270px;
	width: 430px;
	margin: 220px auto;
	border-radius: 6px;
	border: 6px solid white;
}

/* 音乐信息 */
.music-detail {
	position: absolute;
	height: 140px;
	width: 100%;
}

/* 音乐图片 */
.music-img {
	float: left;
	height: 110px;
	width: 110px;
	margin: 15px 0 10px 35px;
	border-radius: 50%;
	overflow: hidden;
	border: 5px solid whitesmoke;
}

.musicimg {
	height: 110px;
	width: 110px;
	animation: Cycle 10s linear infinite;
}

/* 音乐信息 */
.music-info {
	float: right;
	height: 110px;
	width: 200px;
	margin: 25px 70px 10px 0;
}

.name {
	height: 30px;
	width: 200px;
	line-height: 30px;
	font-weight: bold;
	font-size: 19px;
	text-align: center;
	margin-top: 20px;
	cursor: default;
}

.auther {
	height: 20px;
	width: 200px;
	line-height: 20px;
	font-size: 15px;
	font-weight: bold;
	text-align: center;
	margin-top: 5px;
	cursor: default;
}

/* 音乐控制器 */
.music-control {
	position: relative;
	height: 130px;
	width: 430px;
	margin-top: 140px;
}

/* 进度框 */
.runningbox {
	display: flex;
	position: absolute;
	height: 70px;
	width: 430px;
}

.running {
	width: 60%;
	height: 6px;
	margin: 32px auto;
	border-radius: 3px;
	background-color: gainsboro;
}

.running1 {
	height: 6px;
	width: 0;
	border-radius: 3px;
	background-color: grey;
}

.start {
	height: 70px;
	float: left;
	line-height: 70px;
	margin-left: 10%;
	font-size: 14px;
}

.end {
	height: 70px;
	margin-right: 10%;
	line-height: 70px;
	float: right;
	font-size: 14px;
}


/* 控制按钮 */
.control {
	position: absolute;
	display: flex;
	justify-content: space-between;
	height: 35px;
	line-height: 35px;
	margin: 70px 15% 0;
	width: 70%;
}

.music-control span {
	font-size: 35px;
	border-radius: 50%;
	cursor: default;
}

.music-control span:hover {
	background-color: gainsboro;
}

.vulme {
	display: flex;
	width: 35px;
	transition: width 1.5s;
}

.vulme span {
	margin: 1px;
	font-size: 33px;
}

.vulme:hover {
	background-color: white;
	border-radius: 17.5px;
	width: 150px;
}

.vulmeBar {
	height: 5px;
	margin: 15px 7.5px;
	border-radius: 2.5px;
	background-color: gainsboro;
}

.vulmeBar1 {
	height: 5px;
	border-radius: 2.5px;
	background-color: seagreen;
}

/* 图片旋转 */
@keyframes Cycle {
	0% {
		transform: rotate(0deg);
	}

	50% {
		transform: rotate(180deg);
	}

	100% {
		transform: rotate(360deg);
	}
}

/* 引入icon */
@font-face {
	font-family: 'iconfont';
	src: url('../font/iconfont.ttf?t=1621521025244') format('truetype');
}

.iconfont {
	font-family: "iconfont" !important;
	font-size: 16px;
	font-style: normal;
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
}
  1. JavaScript+JQuery代码
    这里是最复杂的部分了,涉及到调用audio组件,img组件等的方法和属性,同时还要实时监测页面数据的变化,来实现更改播放进度,音量和自动播放下一曲。
// 音乐信息链接
var url = 'https://api.vvhan.com/api/rand.music?type=json&sort=热歌榜'
// 音乐信息
var musicInfo = []
var nowmusic = ''
// 创建DOM元素
var audio = $("<audio></audio>")
// 创建图片标签
var musicimg = $("<img>")
// 获取歌名标签
var song = $("<div></div>")
// 获取歌手标签
var auther = $("<div></div>")

// 相关属性
var isPaused = false
var isMuted = false
// 播放列表长度
var len = 0
var nowloca = 0
// 音量
var volume = 1


// 初始化 获取音乐信息
function init() {
    $.ajax({
        url: url,
        type: "get",
        dataType: 'json',
        success: function (res) {
            // 设置自动播放
            audio.attr("autoplay", "autoplay")
            // 设置音乐源地址(URL)
            audio.attr("src", res.info.mp3url)
            $(".musicbox").append(audio)
            // 设置图片URL
            musicimg.attr("src", res.info.picUrl)
            // 给图篇标题添加musicimg类
            musicimg.addClass("musicimg")
            // 把图片标签插入HTML中
            $(".music-img").append(musicimg)
            // 插入歌手名
            auther.text(res.info.auther)
            auther.addClass("auther")
            // 插入歌曲名
            song.text(res.info.name)
            song.addClass("name")
            // 插入标签
            $(".music-info").append(song)
            $(".music-info").append(auther)

            len = 1
            nowloca = 1

            // 存储歌曲列表
            musicInfo.push(res.info)
            nowmusic = res.info
        }
    })
}

$(function () {
    // 初始化
    init()
    // 监测数据变化
    setTimer()
})

// 进度条
function ProgressBar() {
    // 获取歌曲全长
    var duration = audio.prop("duration")
    // 获取歌曲当前播放长度
    var currentTime = audio.prop("currentTime")

    // 时长
    let m = parseInt(duration / 60)
    let s = parseInt(duration % 60)

    // 当前播放时长
    let sm = parseInt(currentTime / 60)
    let ss = parseInt(currentTime % 60)

    // 将时间插入到网页中
    if (s > 9) {
        let end = '0' + m + ':' + s
        $(".end").text(end)
    } else {
        let end = '0' + m + ':0' + s
        $(".end").text(end)
    }
    if (sm > 0) {
        if (ss > 9) {
            let runtime = '0' + sm + ':' + ss
            $(".start").text(runtime)
        } else {
            let runtime = '0' + sm + ':0' + ss
            $(".start").text(runtime)
        }
    }else {
        if (ss > 9) {
            let runtime = '0' + sm + ':' + ss
            $(".start").text(runtime)
        } else {
            let runtime = '0' + sm + ':0' + ss 
            $(".start").text(runtime)
        }
    }

    // 修改进度条长度
    let width = $(".running").css("width")
    let rate = currentTime / duration
    width = parseFloat(width)  * parseFloat(rate)
    $(".running1").css("width", parseInt(width))
    
    // 歌曲播放完 加载下一曲
    if (duration == currentTime) {
        $.ajax({
            url: url,
            type: "get",
            dataType: 'json',
            success: function (res) {
                nowmusic = res.info

                // nowloca等于数组长度 获取新的歌曲
                musicInfo.push(nowmusic)
                // 定位参数
                len = musicInfo.length
                nowloca = len
                // 设置信息
                audio.prop("src", nowmusic.mp3url)
                musicimg.prop("src", nowmusic.picUrl)
                auther.text(nowmusic.auther)
                song.text(nowmusic.name)
            }
        })
    }
}
// 重新播放
function replayMusic() {
    audio.prop("src", nowmusic.mp3url)
    musicimg.prop("src", nowmusic.picUrl)
    auther.text(nowmusic.auther)
    song.text(nowmusic.name)
}
// 暂停播放
function pauseMusic() {
    var player = document.getElementsByTagName("audio")
    if (isPaused)
    {
        player[0].play()
        musicimg.css("animation-play-state", "running")
        $("#pause").html("&#xe63b;")
    } else {
        player[0].pause()
        musicimg.css("animation-play-state", "paused")
        $("#pause").html("&#xe63a;")
    }
    isPaused = !isPaused
}
// 静音
function muteMusic() {
    // 静音 defaultMuted默认是否静音
    var player = document.getElementsByTagName("audio")
    if (isMuted) {
        player[0].muted = false
        $("#mute").html("&#xe641;")
        $(".vulmeBar").css("width", vulme * 100)
    } else {
        player[0].muted = true
        $("#mute").html("&#xe640;")
        $(".vulmeBar").css("width", 0)
    }
    isMuted = !isMuted
}
// 上一曲
function preMusic() {
    if (nowloca == 1) {
        alert("这是第一首歌曲哦!!!")
    } else {
        nowloca = nowloca - 1 
        nowmusic = musicInfo[nowloca - 1]
        audio.prop("src", nowmusic.mp3url)
        musicimg.prop("src", nowmusic.picUrl)
        auther.text(nowmusic.auther)
        song.text(nowmusic.name)
    }
}
// 下一曲
function nextMusic() {
    // 根据nowloca判断读取列表里面的还是重新获取歌曲
    if (nowloca == len) {
        $.ajax({
            url: url,
            type: "get",
            dataType: 'json',
            success: function (res) {
                nowmusic = res.info

                // nowloca等于数组长度 获取新的歌曲
                musicInfo.push(nowmusic)
                // 定位参数
                len = musicInfo.length
                nowloca = len
                // 设置信息
                audio.prop("src", nowmusic.mp3url)
                musicimg.prop("src", nowmusic.picUrl)
                auther.text(nowmusic.auther)
                song.text(nowmusic.name)
            }
        })
    } else {
        nowmusic = musicInfo[nowloca]
        // 设置信息
        audio.prop("src", nowmusic.mp3url)
        musicimg.prop("src", nowmusic.picUrl)
        auther.text(nowmusic.auther)
        song.text(nowmusic.name)
        // 定位参数
        nowloca = nowloca + 1
    }
}
// 修改音量
function changeVulme(e) {
    $(".vulmeBar").click(function (e) {
        let x = e.offsetX
        let y = e.offsetY

        // 在指定位置计算音量
        if (x >= 0 && x <= 5 || y <= 0) {
            volume = x / 100
            audio.prop("volume", volume)
            
            $(".vulmeBar1").css("width", volume * 100)
        } 

    });

}
// 修改歌曲进度
function changeProgress() {
    $(".running").click(function (e) {
        let x = e.offsetX
        let y = e.offsetY
        var duration = audio.prop("duration")

        // 在指定位置计算
        if (x >= 0 && x <= 258 || y <= 0) {
            let l = x / 258
            let time = l * duration

            document.getElementsByTagName("audio")[0].currentTime = time
            $(".running1").css("width", x)
        } 

    });
}
// 实时监测数据变化
function setTimer() {
    // 设置定时器 每秒执行一次
    setInterval(() => {
        ProgressBar()
      
        // 监测音量 volume 当vulme的宽度等于150时 设置宽度 否者为0 隐藏
        if ($(".vulme").css("width") === '150px') {
            $(".vulmeBar").css("width", 100)
            $(".vulmeBar1").css("width", volume * 100)
        } else {
            $(".vulmeBar").css("width", 0)
            $(".vulmeBar1").css("width",0)
        }
    }, 1000)
}

总结

总的来说这个音乐播放器实现起来不难,重要的是要清楚各个标签的属性和方法和实现的逻辑然后按照自己想要的页面布局来写就可以了。

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值