1、权限:
1.1、在entry => src => main => module.json5中配置:
"requestPermissions": [
{"name": "ohos.permission.KEEP_BACKGROUND_RUNNING"}
],
1.2、在ability中配置backgroundModes(也是module.json5中),配置:
"backgroundModes": [
'audioPlayback'
]
表示为背景音频播放任务
全部:
"abilities": [
{
"name": "EntryAbility",
"srcEntry": "./ets/entryability/EntryAbility.ets",
"description": "$string:EntryAbility_desc",
"icon": "$media:layered_image",
"label": "$string:EntryAbility_label",
"startWindowIcon": "$media:startIcon",
"startWindowBackground": "$color:start_window_background",
"exported": true,
"skills": [
{
"entities": [
"entity.system.home"
],
"actions": [
"action.system.home"
]
}
],
"backgroundModes": [
'audioPlayback'
]
}
],
在播放音乐时调用:
AvPlayerManager.startBackgroundTask()
// 开启后台长时间任务,,播放的时候调用
static async startBackgroundTask(){
// 如果已经存在,就表示开启了后台任务
if (AvSessionManager.session.sessionId){
return
}
// want的信息,作用:当点击播控中心的时候,会跳转到app中来
let wantAgentInfo: wantAgent.WantAgentInfo = {
wants: [
{
bundleName: 'com.zhangjian.myapplication',//包名
abilityName: 'EntryAbility' }
],
operationType: wantAgent.OperationType.START_ABILITIES,
requestCode: 0,
wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
}
let want=await wantAgent.getWantAgent(wantAgentInfo)
// 申请长时间任务
await backgroundTaskManager.startBackgroundRunning(getContext(),
backgroundTaskManager.BackgroundMode.AUDIO_PLAYBACK,
want
)
}
AvSessionManager,后台播放任务之前需要初始化
import { avSession } from '@kit.AVSessionKit'
export class AvSessionManager{
static session:avSession.AVSession//媒体会话对象
static controller:avSession.AVSessionController//控制器
static async init(context:Context){
AvSessionManager.session=await avSession.createAVSession(context,'bgPlay','audio')
AvSessionManager.controller=await AvSessionManager.session.getController()
}
}
音乐管理借鉴实例:
import { media } from '@kit.MediaKit'
import { SongItemType } from '../bean/SongItemType'
import { AvSessionManager } from './AvSessionManager'
import { backgroundTaskManager } from '@kit.BackgroundTasksKit'
import { wantAgent } from '@kit.AbilityKit'
export class AvPlayerManager{
static player:media.AVPlayer|null=null
static currentMusic:SongItemType=new SongItemType()
static async init(){
if (!AvPlayerManager.player) {
AvPlayerManager.player=await media.createAVPlayer()
}
AvPlayerManager.player.on('stateChange',(state)=>{
switch (state){
case 'initialized':
AvPlayerManager.player?.prepare()
break
case 'prepared':
AvPlayerManager.player?.play()
break
}
})
AvPlayerManager.player.on('durationUpdate',(duration)=>{
AvPlayerManager.currentMusic.duration=duration
})
AvPlayerManager.player.on('timeUpdate',(time)=>{
AvPlayerManager.currentMusic.time=time
})
AvPlayerManager.player.on('error',(time)=>{
})
}
static async changePlay(){
await AvPlayerManager.player?.reset()
}
static play(song:SongItemType){
AvPlayerManager.startBackgroundTask()
AvPlayerManager.player!.url=song.url
}
static playRaw(){
AvPlayerManager.startBackgroundTask()
let mp3=getContext().createModuleContext('entry').resourceManager.getRawFdSync('like.MP3')
let avFileDescriptor: media.AVFileDescriptor =
{ fd: mp3.fd, offset: mp3.offset, length: mp3.length };
AvPlayerManager.player!.fdSrc=avFileDescriptor
}
static playUrl(song:string){
AvPlayerManager.startBackgroundTask()
AvPlayerManager.player!.url=song
}
// 开启后台长时间任务,,播放的时候调用
static async startBackgroundTask(){
// 如果已经存在,就表示开启了后台任务
if (AvSessionManager.session.sessionId){
return
}
// want的信息,作用:当点击播控中心的时候,会跳转到app中来
let wantAgentInfo: wantAgent.WantAgentInfo = {
wants: [
{
bundleName: 'com.zhangjian.myapplication',//包名
abilityName: 'EntryAbility' }
],
operationType: wantAgent.OperationType.START_ABILITIES,
requestCode: 0,
wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
}
let want=await wantAgent.getWantAgent(wantAgentInfo)
// 申请长时间任务
await backgroundTaskManager.startBackgroundRunning(getContext(),
backgroundTaskManager.BackgroundMode.AUDIO_PLAYBACK,
want
)
}
}