背景
我们平常见到的h5页面,大多数都有背景音乐,打开页面自动播放,该文教大家如何利用uniapp开发h5,实现内置音乐播放、暂停,以及音乐icon的旋转和暂停动画。
创建音乐对象
代码如下:
var innerAudioContext = uni.createInnerAudioContext();
innerAudioContext.autoplay = true;//自动播放
innerAudioContext.loop = true; //循环播放
innerAudioContext.src = '../../static/你的音乐名称.mp3';
innerAudioContext.onPlay(() => {//可以播放事件
console.log('开始播放');
this.playing = !innerAudioContext.paused;//查看是否可以自动播放
});
innerAudioContext.onError((res) => {
console.log(res.errMsg);
console.log(res.errCode);
});
需要注意:
- 不是所有机型都可以自动播放,大部分安卓机可以自动播放,大部分ios机无法自动播放。
- 如果无法自动播放,innerAudioContext.paused会等于false
- 我们设置playing属性来控制音乐icon的旋转和暂停动画
使用animation-play-state属性
我们知道,普通的旋转动画不难实现,但是暂停呢?一般的做法是通过添加和删除动画的class来达到旋转和暂停,但是删除动画的class,音乐icon会回到初始位置,这种效果不太理想。实际上,css3确实可以暂停动画的执行,只需要添加animation-play-state属性。
animation-play-state有两个属性值,一个是running,另一个是paused。字面意思,可以控制动画的运行和暂停。
具体实现动画的代码如下:
<view class="flex-row center-center player playing" :class="playing?'none':'keepgo'" @click.stop="play">
<image src="../../static/音乐开.png" style="width: 50rpx;height: 50rpx;"></image>
</view>
<script>
export default{
data(){
return {
playing:false,
}
},
methods:{
play() {
this.playing = !this.playing; //背景音乐点击,暂停或继续
},
}
//...
}
</script>
<style>
.flex-row {
display: flex;
flex-direction: row;
}
.center-center {
align-items: center;
justify-content: center;
}
.playing {
animation: run 10s linear 0s infinite;
}
.player {
position: fixed;
top: 30rpx;
right: 30rpx;
width: 65rpx;
height: 65rpx;
border-radius: 50%;
background-color: rgba(0, 0, 0, 0.1);
z-index: 999999;
}
.keepgo {
animation-play-state: paused;
}
</style>
我们通过添加和移除keepgo样式,同样可以实现运行和暂停的效果,不一定是running。这样, 背景音乐的暂停和播放动画就实现了。
结语
今天是2020年除夕夜,遭遇了新冠病毒的大事件,这个年的味道变淡了。
本人是武汉大学研究生,1月22日于武汉火车站发车,途径黄石北,换乘到老家莆田。在家两日身体状况良好,无发热现象,还在每日观察中。
希望全世界人民都可以挺过这段艰难的日子,潜在病毒携带者好好呆在家里。我们一起度过难关。
武汉加油!中国加油!世界加油!💪