xugenyuan

ref |> 处理播控中心不生效问题

Signed-off-by: xugenyuan <xugenyuan@wondertek.com.cn>
... ... @@ -372,7 +372,7 @@ export struct OperRowListView {
.gesture(
TapGesture()
.onAction((event: GestureEvent) => {
this.AudioSuspension.setPlayerUrl(this.audioUrl, this.audioTitle)
this.AudioSuspension.setPlayerUrl(this.audioUrl, this.audioTitle, this.contentDetailData.newsId + "", this.contentDetailData.newsSourceName)
TrackingButton.click('suspendedWindow',this.pageId,this.pageName)
}))
}
... ...
... ... @@ -39,14 +39,15 @@ export class AudioSuspensionModel {
/**
* 配置音频地址
*/
public setPlayerUrl(url: string, srcTitle: string) {
public async setPlayerUrl(url: string, srcTitle: string, srcContentId?: string, srcSource?: string) {
/*console.log(TAG,'this.url', this.url)
console.log(TAG,'url', url)*/
this.playerController.get().keepOnBackground = true
BackgroundAudioController.sharedController().avplayerController = this.playerController.get()
BackgroundAudioController.sharedController().createSession()
await BackgroundAudioController.sharedController().createSession()
BackgroundAudioController.sharedController().startContinuousTask()
BackgroundAudioController.sharedController().setSessionMetaData("aaa", srcTitle, "")
let id = $r('app.media.newspaper_default').id
BackgroundAudioController.sharedController().setSessionMetaData(srcContentId ?? "", srcTitle, 'file://', srcSource ?? "")
BackgroundAudioController.sharedController().stopUseFeatures()
BackgroundAudioController.sharedController().listenPlayEvents()
... ...
... ... @@ -116,6 +116,7 @@ export class LiveRoomManager {
}
private connectWithIMToken(token: string) {
Logger.debug(TAG, "连接开始,IM Token:" + token)
const timeout = 5
IMEngine.getInstance().connect(token, timeout).then(result => {
if (EngineError.Success === result.code) {
... ...
... ... @@ -5,6 +5,7 @@ import { BusinessError } from '@kit.BasicServicesKit'
import { Logger } from 'wdKit/Index'
import { PlayerConstants } from '../constants/PlayerConstants'
import { WDPlayerController } from './WDPlayerController'
import { image } from '@kit.ImageKit'
const TAG = "BackgroundAudioController"
... ... @@ -23,20 +24,28 @@ export class BackgroundAudioController {
public gotContextFunc?: () => Context
public avplayerController?: WDPlayerController
private lastSession?: AVSessionManager.AVSession
private applyedLongTaskPlay: boolean = false
private lastProgress: number = 0.0
private hasSetupProgress: boolean = false
// 开始创建并激活媒体会话
// 创建session
async createSession() {
if (!this.gotContextFunc) { return }
if (this.lastSession == null) {
this.destorySession()
let type: AVSessionManager.AVSessionType = 'audio';
let session = await AVSessionManager.createAVSession(this.gotContextFunc(),'SESSION_NAME', type);
this.lastSession = session
}
// 激活接口要在元数据、控制命令注册完成之后再执行
await session.activate();
Logger.debug(TAG, `session create done : sessionId : ${session.sessionId}`);
await this.lastSession?.activate();
Logger.debug(TAG, `session create done : sessionId : ${this.lastSession?.sessionId}`);
this.lastSession = session
this.lastProgress = 0
this.hasSetupProgress = false
}
destorySession() {
... ... @@ -47,13 +56,13 @@ export class BackgroundAudioController {
}
//设置播放元数据
setSessionMetaData(assetId: string, title: string, mediaImage: string, artist?: string) {
setSessionMetaData(assetId: string, title: string, mediaImage: image.PixelMap | string, artist: string) {
Logger.debug(TAG, `SetAVMetadata assetId: ${assetId}}, title: ${title}, mediaImage: ${mediaImage}, artist: ${artist}`);
let metadata: AVSessionManager.AVMetadata = {
assetId: assetId,
title: title,
assetId: assetId.length > 0 ? assetId : "fake-asset-id",
title: title.length > 0 ? title : " ",
mediaImage: mediaImage,
artist: artist ?? "",
// duration: "",
artist: artist.length > 0 ? artist : "人日日报",
};
this.lastSession?.setAVMetadata(metadata).then(() => {
Logger.debug(TAG, `SetAVMetadata successfully`);
... ... @@ -64,26 +73,59 @@ export class BackgroundAudioController {
//设置播放状态
setSessionPlayStatus(playStatus: number) {
let pauseed = playStatus == PlayerConstants.STATUS_PAUSE
let playbackStatus = AVSessionManager.PlaybackState.PLAYBACK_STATE_PLAY
switch (playStatus){
case PlayerConstants.STATUS_PAUSE: {
playbackStatus = AVSessionManager.PlaybackState.PLAYBACK_STATE_PAUSE
} break
case PlayerConstants.STATUS_START: {
playbackStatus = AVSessionManager.PlaybackState.PLAYBACK_STATE_PLAY
} break
case PlayerConstants.STATUS_STOP: {
playbackStatus = AVSessionManager.PlaybackState.PLAYBACK_STATE_STOP
} break
case PlayerConstants.STATUS_ERROR: {
playbackStatus = AVSessionManager.PlaybackState.PLAYBACK_STATE_ERROR
} break
case PlayerConstants.STATUS_COMPLETION: {
playbackStatus = AVSessionManager.PlaybackState.PLAYBACK_STATE_COMPLETED
} break
default: {
playbackStatus = AVSessionManager.PlaybackState.PLAYBACK_STATE_IDLE
} break
}
let playbackState: AVSessionManager.AVPlaybackState = {
state:pauseed ? AVSessionManager.PlaybackState.PLAYBACK_STATE_PAUSE : AVSessionManager.PlaybackState.PLAYBACK_STATE_PLAY,
isFavorite:false
state:playbackStatus,
// isFavorite:false
};
this.lastSession?.setAVPlaybackState(playbackState, (err: BusinessError) => {
if (err) {
Logger.error(TAG, `Failed to set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
} else {
Logger.debug(TAG, `SetAVPlaybackState 设置播放状态成功` + playStatus);
Logger.debug(TAG, `SetAVPlaybackState 设置播放状态成功 ` + playStatus);
}
});
}
//设置进度,单位秒
setSessionPlayProgress(progressDuration: number, totalDuration: number) {
Logger.debug(TAG, `set progress: ` + progressDuration + " duration: " + totalDuration);
// Logger.debug(TAG, `set progress: ` + progressDuration + " duration: " + totalDuration);
if (totalDuration <= 0) {
return
}
let newProgress = progressDuration / totalDuration
if (Math.abs(newProgress - this.lastProgress) < 0.01) {
return
}
this.lastProgress = newProgress
if (this.hasSetupProgress) {
return
}
this.hasSetupProgress = true
Logger.debug(TAG, `set progress: ` + progressDuration + " duration: " + totalDuration);
// 设置状态: 播放状态,进度位置,播放倍速,缓存的时间
let playbackState: AVSessionManager.AVPlaybackState = {
state: AVSessionManager.PlaybackState.PLAYBACK_STATE_PLAY, // 播放状态
... ... @@ -92,14 +134,14 @@ export class BackgroundAudioController {
updateTime: new Date().getTime(), // 应用更新当前位置时的时间戳,以ms为单位
},
duration: totalDuration * 1000,
// speed: 1.0, // 可选,默认是1.0,播放的倍速,按照应用内支持的speed进行设置,系统不做校验
// bufferedTime: 14000, // 可选,资源缓存的时间,以ms为单位
speed: 1.0, // 可选,默认是1.0,播放的倍速,按照应用内支持的speed进行设置,系统不做校验
bufferedTime: totalDuration * 1000, // 可选,资源缓存的时间,以ms为单位
};
this.lastSession?.setAVPlaybackState(playbackState, (err) => {
if (err) {
Logger.error(TAG, `Failed to set AVPlaybackState. Code: ${err.code}, message: ${err.message}`);
} else {
// Logger.debug(TAG, `SetAVPlaybackState successfully`);
Logger.debug(TAG, `SetAVPlaybackState successfully`);
}
});
}
... ... @@ -107,34 +149,37 @@ export class BackgroundAudioController {
// 置灰或禁用不支持的按钮
stopUseFeatures() {
// 取消指定session下的相关监听
this.lastSession?.off('playFromAssetId');
this.lastSession?.off('setSpeed');
this.lastSession?.off('setLoopMode');
this.lastSession?.off('toggleFavorite');
this.lastSession?.off('skipToQueueItem');
this.lastSession?.off('handleKeyEvent');
this.lastSession?.off('commonCommand');
this.lastSession?.off('rewind');
this.lastSession?.off('fastForward');
// this.lastSession?.off('playFromAssetId');
// this.lastSession?.off('setSpeed');
// this.lastSession?.off('setLoopMode');
// this.lastSession?.off('toggleFavorite');
// this.lastSession?.off('skipToQueueItem');
// this.lastSession?.off('handleKeyEvent');
// this.lastSession?.off('commonCommand');
// this.lastSession?.off('rewind');
// this.lastSession?.off('fastForward');
}
listenPlayEvents() {
this.lastSession?.on('play', () => {
Logger.debug(TAG, `on play `);
this.avplayerController?.play()
this.hasSetupProgress = false
});
this.lastSession?.on('pause', () => {
Logger.debug(TAG, `on pause `);
this.avplayerController?.pause()
});
this.lastSession?.on('stop', () => {
Logger.debug(TAG, `on stop `);
this.avplayerController?.stop()
});
this.lastSession?.on('playNext', () => {
Logger.debug(TAG, `on playNext `);
});
this.lastSession?.on('playPrevious', () => {
Logger.debug(TAG, `on playPrevious `);
});
// this.lastSession?.on('playNext', () => {
// Logger.debug(TAG, `on playNext `);
// });
// this.lastSession?.on('playPrevious', () => {
// Logger.debug(TAG, `on playPrevious `);
// });
this.lastSession?.on('seek', (position: number) => {
Logger.debug(TAG, `on seek , the time is ${JSON.stringify(position)}`);
... ... @@ -151,13 +196,16 @@ export class BackgroundAudioController {
});
// 应用响应seek命令,使用应用内播放器完成seek实现
this.avplayerController?.setSeekTime(position * 0.001, SliderChangeMode.End)
this.hasSetupProgress = false
});
}
// 开启后台长时任务
startContinuousTask() {
if (this.applyedLongTaskPlay) {
return
}
let params: Record<string, string> = {
"title": "开始后台任务",
"content": "内容?",
... ... @@ -175,9 +223,9 @@ export class BackgroundAudioController {
deviceId: '',
bundleName: "com.peopledailychina.hosactivity",
abilityName: "EntryAbility",
action: 'com.test.pushaction',
entities: [],
parameters:params,
// action: 'com.test.pushaction',
// entities: [],
// parameters:params,
}
],
// 指定点击通知栏消息后的动作是拉起ability
... ... @@ -195,6 +243,7 @@ export class BackgroundAudioController {
backgroundTaskManager.BackgroundMode.AUDIO_PLAYBACK,
wantAgentObj).then(() => {
Logger.debug(TAG, `Succeeded in operationing startBackgroundRunning.`);
this.applyedLongTaskPlay = true
}).catch((err: BusinessError) => {
Logger.error(TAG, `Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
});
... ... @@ -208,6 +257,7 @@ export class BackgroundAudioController {
}).catch((err: BusinessError) => {
Logger.error(TAG, `Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
});
this.applyedLongTaskPlay = false
}
}
\ No newline at end of file
... ...
... ... @@ -24,6 +24,9 @@
"startWindowIcon": "$media:app_icon",
"startWindowBackground": "$color:start_window_background",
"exported": true,
"backgroundModes": [
"audioPlayback"
],
"skills": [
{
"entities": [
... ... @@ -33,6 +36,8 @@
"action.system.home",
"com.test.pushaction"
],
},
{
"uris": [
{
"scheme": 'rmrbapp',
... ... @@ -40,10 +45,9 @@
'port': '8080',
"path": 'openwith'
}
]
}
],
"backgroundModes": ["audioPlayback"]
}
]
}
],
"metadata": [
... ...