【JavaScript】动手实现一个音乐播放器

【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
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值