[TOC]
音樂播放帶旋轉
## 要點
* 獲取背景音樂
```
wx.getBackgroundAudioManager();
```
* 點擊播放
```
onMusic(){
if (this.data.isPlay){
this.setData({
isPlay:false
})
audio.pause();
}
else{
audio.title = this.properties.title;
audio.src = this.properties.url;
this.setData({
isPlay:true
})
}
}
```
* 監聽與頁面保持一致
* attached 函數 你不在method里
```
//當組件觸發 attached 生命周期時,會依次觸發 my-behavior 中的 attached 生命周期函數和 my-component 中的 attached 生命周期函數
attached(){
//監聽音頻播放事件
audio.onPlay(()=>{
this.setData({
isPlay:true
})
})
//監聽音頻暫停事件
audio.onPause(()=>{
this.setData({
isPlay:false
})
})
//監聽音頻停止事件
audio.onStop(()=>{
this.setData({
isPlay:false
})
})
//監聽音頻自然播放至結束的事件
audio.onEnded(()=>{
this.setData({
isPlay:false
})
})
}
```
# 具體代碼
## js
```
const audio = wx.getBackgroundAudioManager();
Component({
/**
* 組件的屬性列表
*/
properties: {
title: String,
url: String
},
behaviors:[common],
/**
* 組件的初始數據
*/
data: {
isPlay:false
},
/**
* 組件的方法列表
*/
methods: {
onMusic(){
if (this.data.isPlay){
this.setData({
isPlay:false
})
audio.pause();
}
else{
audio.title = this.properties.title;
audio.src = this.properties.url;
this.setData({
isPlay:true
})
}
}
},
//當組件觸發 attached 生命周期時,會依次觸發 my-behavior 中的 attached 生命周期函數和 my-component 中的 attached 生命周期函數
attached(){
//監聽音頻播放事件
audio.onPlay(()=>{
this.setData({
isPlay:true
})
})
//監聽音頻暫停事件
audio.onPause(()=>{
this.setData({
isPlay:false
})
})
//監聽音頻停止事件
audio.onStop(()=>{
this.setData({
isPlay:false
})
})
//監聽音頻自然播放至結束的事件
audio.onEnded(()=>{
this.setData({
isPlay:false
})
})
}
})
```
## wxml
```
<view class='music' >
<image src="/images/banner.png" class="banner {{isPlay?'rotate':''}}" ></image>
<image src="{{isPlay?'/images/play.png':'/images/pause.png'}}" class='music-img' bind:tap="onMusic"></image>
</view>
```
## wxss
```
.music{
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.banner{
width: 200px;
height: 200px;
border-radius:100px;
}
.music-img{
width: 60px;
height: 60px;
position: absolute;
top: 70px;
z-index: 10;
}
.rotate{
animation: rotate 12s infinite;
}
@keyframes rotate{
from{
transform: rotate(0deg)
}
to{
transform: rotate(360deg)
}
}
```
- 開發環境及接口
- 0.豆瓣接口
- 1.開發環境配置
- 2.一些相關文檔
- 小程序實例效果
- 第0節、TodoList
- 第一節、豆瓣相關
- 1、tabBar的配置及導航加標題
- 2、數據加載及下拉加載
- 3、加載相關
- 4、輪播
- 5、星星評分
- 第二節、音樂播放相關
- 1.點擊收藏分享
- 2.音樂播放
- 初始版
- 組件版
- 組件加強版
- 3.點贊
- 點贊初級版
- 點贊第二版
- 5.左右按鈕
- 6.緩存
- 第三節、補充
- 地圖
- 點擊拍照換圖
- 掃一掃
- 小程序語法
- 第一節 、HTTP的封裝
- 0.http請求
- 1.function封裝
- 2.class封裝http
- 3.promise封裝
- 4.config地址
- 第二節、組件
- 2.組件單獨設置樣式
- 3.一些有意義的標簽
- 4.behavior
- 5.SLOT
- 6.左右按鈕
- 5.點贊組件
- 6.用戶授權
- 圖片按鈕 如分享
- 第三節、api
- 1.頁面跳轉
- 獲取input里的值
- 1.添加評論
- 2.搜索框
- 3. 獲取input里的值
- 2.設置緩存
- 3.模態框,彈出框
- 4.分享showActionSheet
- 5.定義全局的數據
- 2. 基礎知識
- 1.setData
- 2.文件結構
- 3.wxml語法
- 第一節 數據綁定
- 第二節 列表渲染
- 第三節 條件渲染
- 第四節 模板
- 第五節 事件
- 第六節 引用
- 4.wxs
- 1.文本縮進問題
- 5.小程序中遇到的wxss 問題
- 1.width100%越界問題
- 廢棄的文件
- 一個完整的小程序
- 1.啟動頁面
- 2.yuedu輪播+封裝及數據調用
- yuedu的詳情頁
- 3.電影
- movie-more
- web-view