跟着示例做微信小程序音乐播放器,附源码及各文件解析

2025-07-19
来源:万象资讯

今日我继续探索小程序的API,模仿他人的案例动手制作了一个小程序,留下自己的足迹。最后附上源码的链接。接下来,我将展示一个微信小程序的音乐播放器,请大家先看看它的效果图。

界面做的确实挺丑的,先上wxss文件

//index.wxss [id_402091443]{ background-color: #eee; border-radius: 8rpx; margin: 20rpx; }

仅仅是对那个按钮的边缘和间隔进行了轻微的调整,至于颜色,我依旧选择了这个浅绿色。

下面是.wxml文件

//index.wxml class="button-style" type="primary" bindtap="listenerButtonPlay">播放 class="button-style" type="primary" bindtap="listenerButtonPause">暂停 class="button-style" type="primary" bindtap="listenerButtonSeek">设置播放进度 class="button-style" type="primary" bindtap="listenerButtonStop">停止播放 class="button-style" type="primary" bindtap="listenerButtonGetPlayState">获取播放状态

没办法,用开发者工具打出来就是这样的丑格式

下面是重点.js

//index.js //获取应用实例 var app = getApp() Page({ data:{ }, //播放

微信小程序开发音乐歌单_小程序API实现音乐播放_微信小程序音乐播放器教程

listenerButtonPlay:function(){ wx.playBackgroundAudio({ dataUrl: 该链接指向的音频文件为:http://ac-5g9r20ds.clouddn.com/e54ad7f0a834b9c07ec6.mp3。, title:'李宗盛', //图片地址地址 coverImgUrl:该图片的链接为:http://ac-5g9r20ds.clouddn.com/63bedb5f584234b6827c.jpg,请点击访问。 }) }, //监听button暂停按钮 listenerButtonPause:function(){ wx.pauseBackgroundAudio({ }); console.log('暂停播放') }, /** * 播放状态 */ listenerButtonGetPlayState:function(){ 调用wx.getBackgroundAudioPlayerState()函数,以获取背景音频播放器的状态信息。 success: function(res){ // success 选择音频播放的具体时长(以秒为计量单位),该操作仅在音乐正在播放的情境下才会生效。 console.log('duration:' + res.duration) console.log('currentPosition:' + res.currentPosition) 播放状态分为三种情况:2代表没有音乐正在播放,1表示音乐正在播放,而0则意味着音乐处于暂停状态。 console.log('status:' + res.status) console.log('downloadPercent:' + res.downloadPercent)

微信小程序音乐播放器教程_微信小程序开发音乐歌单_小程序API实现音乐播放

歌曲数据链接为dataUrl,仅在音乐正在播放时提供。 console.log('dataUrl:' + res.dataUrl) }, fail: function() { // fail }, complete: function() { // complete } }) }, /** * 设置进度 */ listenerButtonSeek:function(){ wx.seekBackgroundAudio({ position: 40 }) }, /** * 停止播放 */ listenerButtonStop:function(){ wx.stopBackgroundAudio({ }) console.log('停止播放') }, onLoad:function(options){ // 页面初始化 options为页面跳转所带来的参数 /** * 监听音乐播放 */ wx.onBackgroundAudioPlay(function() { // callback console.log(当背景音频开始播放时) }) /** * 监听音乐暂停 */ wx.onBackgroundAudioPause(function() { // callback console.log(当背景音频暂停时) }) /** * 监听音乐停止 */ wx.onBackgroundAudioStop(function() { // callback console.log(当背景音频停止播放时) }) } })

在文档中,您可以依次查看函数定义,其中包含了三个监听函数,具体效果可参照附图所示。

实际上,使用其中的API并不复杂;只需在标签中正确标注事件名称,然后在方法中找到对应的处理逻辑;对于像wx.这样的API,你只需填充必要的参数;若遇到不懂之处,可以查阅API文档(API入口)。

分享