使用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;
}