以下是一个简单的音乐微信小程序示例代码,可以播放音乐和展示歌曲列表(需要进阶版优化版的可以在评论区艾特我哦):
目录
index.wxml
<!-- index.wxml -->
<view class="container">
<view class="header">我的音乐播放器demo</view>
<view class="song-list">
<block wx:for="{{songs}}" wx:key="index">
<view class="song-item" bindtap="playSong" data-song="{{item}}">
<text>{{item.name}}</text>
</view>
</block>
</view>
<audio hidden="{{!isPlaying}}" id="myAudio" src="{{currentSong.url}}" bindended="onSongEnded"></audio>
</view>
index.js
// index.js
Page({
data: {
songs: [
{ name: "歌曲1", url: "http://www.example.com/song1.mp3" },
{ name: "歌曲2", url: "http://www.example.com/song2.mp3" },
{ name: "歌曲3", url: "http://www.example.com/song3.mp3" },
],
isPlaying: false,
currentSong: {},
},
playSong: function (event) {
var song = event.currentTarget.dataset.song;
this.setData({
isPlaying: true,
currentSong: song
});
var audioContext = wx.createAudioContext('myAudio');
audioContext.play();
},
onSongEnded: function () {
this.setData({
isPlaying: false,
currentSong: {}
});
}
})
index.wxss
/* index.wxss */
.container {
display: flex;
flex-direction: column;
align-items: center;
}
.header {
font-size: 24px;
margin-top: 20px;
margin-bottom: 20px;
}
.song-list {
display: flex;
flex-direction: column;
align-items: flex-start;
}
.song-item {
padding: 10px;
border-bottom: 1px solid #ccc;
width: 100%;
box-sizing: border-box;
}
.song-item:last-child {
border-bottom: none;
}
小程序功能简述:
这个示例中,`songs` 列表是一个包含歌曲信息的数组,每个歌曲都有 `name` 和 `url` 属性。
在页面渲染时,使用 `wx:for` 指令遍历 `songs` 数组,生成歌曲列表。
每个歌曲都是一个 `song-item` 元素,可以通过点击 `song-item` 元素来播放对应的歌曲。
项目总结:
在 JavaScript 中,通过 `bindtap` 事件绑定和 `data-song` 自定义属性传递被点击的歌曲信息。播放器的逻辑在 `playSong` 函数中,将点击的歌曲信息设置到 `currentSong` 中,然后通过 `wx.createAudioContext` 创建音频上下文,并调用 `play` 方法播放歌曲。
当歌曲播放结束后,通过 `bindended` 事件绑定的 `onSongEnded` 函数将 `isPlaying` 设置为 false,以便在页面中展示歌曲已停止播放。