【demo】react+webpack音乐播放器

使用react+webpack做了一个简单的音乐播放界面

使用H5的audio作为播放器

音乐播放时唱片图片顺时针旋转,音乐停止时图片也停止旋转

github:https://github.com/heyue-99/music-player



url-loader和file-loader 都是用于打包文件和图片

一般限制小图片转 base64 可以用 url-loader,其他情况都用 file-loader
url-loader应该是file-loader上加了一层过滤。

比如:{test: /\.(png|jpg)$/, loader:'url-loader?limit=8192'}

这样在小于8K的图片将直接以base64的形式内联在代码中,可以减少一次http请求。

file-loader的主要功能是:把源文件迁移到指定的目录(可以简单理解为从源文件目录迁移到build目录),并返回新文件的路径(简单拼接而成)。

var url = require("file-loader!./music.mp3");

基于上述分析,我用url-loader来打包图片,file-loader来打包MP3文件


监听audio的方法pause和play,当音乐停止调用组件中自己定义的pause方法,当音乐播放时调用组件中自己定义的play方法,以此来改变state,再利用state来控制唱片图片的className。

利用CSS3的keyfames规则,animation属性,transform属性,animation-play-state属性来完成唱片转动。


index.html

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
<div id="example" style="width: 300px; margin: 150px auto;"></div>
<script type="text/javascript" src="/main.js"></script>
</body>
</html> 

app.js

import React from "react";
import ReactDOM from "react-dom";
//import css from './style.css';
require('./style.css')

var url = require("file-loader!./music.mp3");

var Music = React.createClass({
	 getInitialState: function() {
		return{
			isPlay : false
		};
	},

	 play: function(){
  	 	this.setState({
       		isPlay : true
  		})
 	 },

 	 pause: function(){
  		this.setState({
       		isPlay : false
  		})
 	 },

	componentDidMount: function(){
		var audio = this.refs.audio;
		audio.addEventListener('play',this.play);
		audio.addEventListener('pause',this.pause);
	},

	render: function(){
		var record = this.state.isPlay ? 'play img' :'img';
		return(
			<div>
				<div className={record}></div>
				<div className="music">
					<audio ref="audio" controls="controls" loop="loop" src={url}>
						Your browser does not support the audio element.
					</audio>
				</div>
			</div>
		);
	}
})


ReactDOM.render(
	<Music />,
	document.getElementById("example")
);

style.css

body{
	background-color: green;
}
@keyframes rotate{
	from{
		transform: rotateZ(0);
	}
	to{
		transform: rotateZ(360deg);
	}
}
.img{
	background-image: url(./circle.svg); 
	width: 200px;
	height: 200px;
	margin: 20px auto;
	animation: rotate 5s linear infinite;
        animation-play-state: paused;
}
.play{
	animation-play-state: running;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值