【JavaScript】动手实现一个音乐播放器
文章目录
前言
知识点
- 利用
svelte
框架 - 利用
<audio></audio>
播放音乐 - 利用
animation-play-state
控制动画启停 - 利用正则解析歌词
- 利用
scrollIntoView
实现滚动 - 利用CSS变量控制进度条
效果
实践
基础组件
方便复用起见,提前实现图标,按钮和进度条组件。 图标和按钮配合做控制按钮,进度条用来显示歌曲进度和音量。
Icon
利用iconfont
来选择图标,添加至项目打包下载,在入口文件里引入iconfont.js
即可。
<script>
export let name;
export let color = '#16c2c2';
export let size = '32px';
</script>
<svg class="icon" aria-hidden="true" style={'color:' + color + ';font-size:' + size}>
<use xlink:href={'#icon-' + name} />
</svg>
<style>
.icon {
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
</style>
Button
可以传入icon
显示图标的按钮。
<script>
import Icon from './Icon.svelte';
export let icon;
export let size = '28px';
</script>
<button on:click>
{#if icon}
<Icon name={icon} {size} />
{/if}
<slot />
</button>
<style>
button {
background-color: transparent;
padding: 4px;
border: none;
cursor: pointer;
}
button:hover {
transform: scale(1.2);
filter: brightness(1.2);
}
</style>
Progress
我们注意设置两种模式,横着的表示歌曲进度;竖着的用来控制音量。
<script>
import {
createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
const VERTICAL = 'vertical';
const HORIZONTAL = 'horizontal';
export let direction = HORIZONTAL;
export let progress = 0; // [0-1]
</script>
<div class="container">
<div
class="bar"
style={`
--progress: ${progress * 100}%;
--bar-width: ${direction === HORIZONTAL ? '100%' : '1em'};
--bar-height: ${direction === HORIZONTAL ? '1em' : '100%'};
--bar-direction: ${direction === HORIZONTAL ? '90deg' : '0deg'};
`}
on:click={(e) => {
dispatch(
'change',
direction === HORIZONTAL
? e.offsetX / e.target.scrollWidth
: 1 - e.offsetY / e.target.scrollHeight
);
}}
/>
</div>
<style lang="scss">
.container {
--progress: 0%;
--past-color: #c20c0c;
--future-color: #333;
--bar-width: 100%;
--bar-height: 1em;
--bar-direction: 90deg;
heig