Taro4,在微信小程序使用背景音
首先需要增加权限,在app.config.ts中增加配置
requiredBackgroundModes: ['audio', 'location']
<script setup lang="ts">
import {reactive} from "vue";
import Taro, {useDidShow} from '@tarojs/taro'
const state = reactive({
//播放状态
playing: false,
//时长
duration: 0,
//进度
currentTime: 0,
//标题
title: '晴天',
//歌手
singer: '周杰伦',
//封面
coverImgUrl: 'https://img2.kuwo.cn/star/albumcover/500/s3s94/93/211513640.jpg',
//播放源
src: 'https://sy-sycdn.kuwo.cn/3fbce170be6de62ba25eb72a3f51673b/6735a0de/resource/n2/70/55/756351052.mp3?bitrate$128&from=vip',
})
const backgroundAudioManager = Taro.getBackgroundAudioManager()
useDidShow(() => {
registerCallback
})
// 注册回调事件 监听数据
function registerCallback() {
backgroundAudioManager.onPlay(() => {
state.duration = backgroundAudioManager.duration
})
backgroundAudioManager.onTimeUpdate(() => {
state.currentTime = backgroundAudioManager.currentTime
})
}
// 播放
function play() {
backgroundAudioManager.title = state.title
backgroundAudioManager.singer = state.singer
backgroundAudioManager.coverImgUrl = state.coverImgUrl
backgroundAudioManager.src = state.src
state.playing = true;
}
// 暂停
function pause() {
backgroundAudioManager.pause()
state.playing = false
}
// 增加15秒
function add15s() {
backgroundAudioManager.seek(backgroundAudioManager.currentTime + 15)
}
// 减少15秒
function reduce15s() {
backgroundAudioManager.seek((backgroundAudioManager.currentTime - 15) || 0)
}
</script>
<template>
<view style="width: 100%;height: 100%;">
<view>
<view style="display: flex;flex-direction: column;">
播放状态
<view>
歌曲:{{ state.title }}
</view>
<view>
歌手:{{ state.singer }}
</view>
<view>
封面图:
<view>
<image :src="state.coverImgUrl"/>
</view>
</view>
<view>
时长:{{ state.duration }}
</view>
<view>
当前进度:{{ state.currentTime }}
</view>
<view>
播放状态:{{ state.playing ? '播放中' : '暂停中' }}
</view>
</view>
</view>
<view style="display: flex;justify-content: space-around">
<button @tap="play">播放</button>
<button @tap="pause">暂停</button>
<button @tap="add15s">+15s</button>
<button @tap="reduce15s">-15s</button>
</view>
</view>
</template>
Taro4,在微信小程序使用背景音
http://xuyuanhang.com//archives/taro4-zai-wei-xin-xiao-cheng-xu-shi-yong-bei-jing-yin