From 3dbb3984c5ff05dda3884eb9397b2f8c6e545db1 Mon Sep 17 00:00:00 2001 From: guangda Date: Fri, 12 Sep 2025 16:23:14 +0800 Subject: [PATCH 1/2] fix bug --- entry/src/main/ets/common/utils/LrcUtils.ets | 12 +- .../src/main/ets/common/utils/MediaTools.ets | 19 ++- .../ets/common/utils/ResourceConversion.ets | 11 +- .../main/ets/common/utils/SongItemBuilder.ets | 6 +- .../ets/component/ControlAreaComponent.ets | 132 ++++++++++-------- .../ets/component/PlayerInfoComponent.ets | 6 +- .../ets/controller/AVSessionController.ets | 106 ++++++++------ .../ets/controller/AudioCastController.ets | 122 ++++++++++------ .../ets/controller/AudioPlayerController.ets | 24 +++- .../controller/AudioRendererController.ets | 94 +++++++------ .../main/ets/entryability/EntryAbility.ets | 13 +- 11 files changed, 342 insertions(+), 203 deletions(-) diff --git a/entry/src/main/ets/common/utils/LrcUtils.ets b/entry/src/main/ets/common/utils/LrcUtils.ets index d62e99d..94ac3c3 100644 --- a/entry/src/main/ets/common/utils/LrcUtils.ets +++ b/entry/src/main/ets/common/utils/LrcUtils.ets @@ -31,11 +31,15 @@ const krcLineRegex = new RegExp('\\[(\\d+),(\\d+)\\](.*)'); const krcWordRegex1 = new RegExp('<(\\d+),(\\d+),(\\d+)>([^<]*)', 'g'); const krcWordRegex2 = new RegExp('<(\\d+),(\\d+),(\\d+)>(.*)'); - export async function getRawStringData(context: Context, rawFilePath: string): Promise { - let value = await context.resourceManager.getRawFileContent(rawFilePath); - let textDecoder = util.TextDecoder.create('utf-8', { ignoreBOM: true }); - let stringData = textDecoder.decodeToString(value, { stream: false }); + let stringData = ''; + try { + let value = await context.resourceManager.getRawFileContent(rawFilePath); + let textDecoder = util.TextDecoder.create('utf-8', { ignoreBOM: true }); + stringData = textDecoder.decodeToString(value, { stream: false }); + } catch (error) { + hilog.error(0x0000, 'lyrics', `getRawFileContent failed, the error is: ${JSON.stringify(error)}`); + } return stringData; } diff --git a/entry/src/main/ets/common/utils/MediaTools.ets b/entry/src/main/ets/common/utils/MediaTools.ets index fe3dde5..0d49f72 100644 --- a/entry/src/main/ets/common/utils/MediaTools.ets +++ b/entry/src/main/ets/common/utils/MediaTools.ets @@ -28,13 +28,18 @@ export class MediaTools { static resourceConversion: ResourceConversion = new ResourceConversion(); static async getPixelMapFromResource(context: common.UIAbilityContext | undefined, - name: resourceManager.Resource): Promise { - let unit8Array = await context?.resourceManager?.getMediaContent(name.id); - let imageSource = image.createImageSource(unit8Array?.buffer.slice(0, unit8Array?.buffer.byteLength)); - let pixelMap: image.PixelMap = await imageSource.createPixelMap({ - desiredPixelFormat: image.PixelMapFormat.RGBA_8888 - }); - await imageSource.release(); + name: resourceManager.Resource): Promise { + let pixelMap: image.PixelMap | undefined = undefined; + try { + let unit8Array = await context?.resourceManager?.getMediaContent(name.id); + let imageSource = image.createImageSource(unit8Array?.buffer.slice(0, unit8Array?.buffer.byteLength)); + pixelMap = await imageSource.createPixelMap({ + desiredPixelFormat: image.PixelMapFormat.RGBA_8888 + }); + await imageSource.release(); + } catch (error) { + hilog.error(0x0000, TAG, `getMediaContent failed, the error is: ${JSON.stringify(error)}`); + } return pixelMap; } diff --git a/entry/src/main/ets/common/utils/ResourceConversion.ets b/entry/src/main/ets/common/utils/ResourceConversion.ets index 500639c..1486ba4 100644 --- a/entry/src/main/ets/common/utils/ResourceConversion.ets +++ b/entry/src/main/ets/common/utils/ResourceConversion.ets @@ -14,6 +14,9 @@ */ import { common } from '@kit.AbilityKit'; +import { hilog } from '@kit.PerformanceAnalysisKit'; + +const TAG = 'ResourceConversion'; export class ResourceConversion { private context: common.UIAbilityContext | undefined = undefined; @@ -26,6 +29,12 @@ export class ResourceConversion { if (!this.context) { return; } - return this.context.resourceManager.getStringSync(res.id); + let resourceStr: string = ''; + try { + resourceStr = this.context.resourceManager.getStringSync(res.id); + } catch (error) { + hilog.error(0x0000, TAG, `getStringSync failed, the error is: ${JSON.stringify(error)}`); + } + return resourceStr; } } \ No newline at end of file diff --git a/entry/src/main/ets/common/utils/SongItemBuilder.ets b/entry/src/main/ets/common/utils/SongItemBuilder.ets index eb3ac46..01757ce 100644 --- a/entry/src/main/ets/common/utils/SongItemBuilder.ets +++ b/entry/src/main/ets/common/utils/SongItemBuilder.ets @@ -50,7 +50,11 @@ export default class SongItemBuilder { public async release(): Promise { if (this.context && this.context !== null && this.songItem !== null) { - this.context.resourceManager.closeRawFd(this.songItem.pcmSrc); + try { + this.context.resourceManager.closeRawFd(this.songItem.pcmSrc); + } catch (error) { + hilog.error(0x0000, TAG, `closeRawFd failed, the error is: ${JSON.stringify(error)}`); + } } this.songItem = null; } diff --git a/entry/src/main/ets/component/ControlAreaComponent.ets b/entry/src/main/ets/component/ControlAreaComponent.ets index 13ce4a8..b2af145 100644 --- a/entry/src/main/ets/component/ControlAreaComponent.ets +++ b/entry/src/main/ets/component/ControlAreaComponent.ets @@ -87,41 +87,45 @@ export struct ControlAreaComponent { * @param videoSession: The AV session to configure for casting. */ async initAVCastPicker() { - // [Start onOutputDeviceChange] - this.avSessionController?.AVSession?.on('outputDeviceChange', async (connectState: avSession.ConnectionState, - device: avSession.OutputDeviceInfo) => { - let currentDevice: avSession.DeviceInfo = device?.devices?.[0]; - this.deviceInfo = currentDevice; - if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE && - connectState === avSession.ConnectionState.STATE_CONNECTED) { - // [StartExclude onOutputDeviceChange] - if (!this.isAvPlayerPlay) { - if (currentDevice.supportedProtocols === avSession.ProtocolType.TYPE_CAST_PLUS_AUDIO) { - this.isPcm = true; - } else { - Prompt.showToast({ - message: this.resourceConversion.getStringValueFromResource($r('app.string.reason_switch_quality')) - }); - this.isAvPlayerPlay = true; - this.selectToneQuality = ToneQuality.SQ; + try { + // [Start onOutputDeviceChange] + this.avSessionController?.AVSession?.on('outputDeviceChange', async (connectState: avSession.ConnectionState, + device: avSession.OutputDeviceInfo) => { + let currentDevice: avSession.DeviceInfo = device?.devices?.[0]; + this.deviceInfo = currentDevice; + if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE && + connectState === avSession.ConnectionState.STATE_CONNECTED) { + // [StartExclude onOutputDeviceChange] + if (!this.isAvPlayerPlay) { + if (currentDevice.supportedProtocols === avSession.ProtocolType.TYPE_CAST_PLUS_AUDIO) { + this.isPcm = true; + } else { + Prompt.showToast({ + message: this.resourceConversion.getStringValueFromResource($r('app.string.reason_switch_quality')) + }); + this.isAvPlayerPlay = true; + this.selectToneQuality = ToneQuality.SQ; + } } + // [EndExclude onOutputDeviceChange] + this.isCasting = true; + this.startCast(this.currentTime, this.selectIndex); + } + // [StartExclude onOutputDeviceChange] + else if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE && + connectState === avSession.ConnectionState.STATE_DISCONNECTED) { + this.releaseAvCastController(); + } + else if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL) { + this.playMusic(this.selectIndex, this.currentTime); + this.releaseAvCastController(); } // [EndExclude onOutputDeviceChange] - this.isCasting = true; - this.startCast(this.currentTime, this.selectIndex); - } - // [StartExclude onOutputDeviceChange] - else if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_REMOTE && - connectState === avSession.ConnectionState.STATE_DISCONNECTED) { - this.releaseAvCastController(); - } - else if (currentDevice.castCategory === avSession.AVCastCategory.CATEGORY_LOCAL) { - this.playMusic(this.selectIndex, this.currentTime); - this.releaseAvCastController(); - } - // [EndExclude onOutputDeviceChange] - }) - // [End onOutputDeviceChange] + }) + // [End onOutputDeviceChange] + } catch (error) { + hilog.error(0x0000, TAG, `avSession on event failed, the error is: ${JSON.stringify(error)}`); + } } async avPlayerStateChange() { @@ -188,9 +192,13 @@ export struct ControlAreaComponent { this.avSessionController = AVSessionController.getInstance(); } await this.configSession(); - this.audioCastController?.avCastController?.on('endOfStream', () => { - this.playNextOrPrevious('next'); - }); + try { + this.audioCastController?.avCastController?.on('endOfStream', () => { + this.playNextOrPrevious('next'); + }); + } catch (error) { + hilog.error(0x0000, TAG, `avCastController on event failed, the error is: ${JSON.stringify(error)}`); + } this.audioCastController.setPlayModel(this.playMode); } } @@ -198,19 +206,23 @@ export struct ControlAreaComponent { async startCast(startPosition: number, selectIndex: number) { if (!this.audioCastController) { - let session = await this.avSessionController?.AVSession?.getAVCastController(); - this.audioCastController = new AudioCastController(session); + try { + let session = await this.avSessionController?.AVSession?.getAVCastController(); + this.audioCastController = new AudioCastController(session); + this.selectIndex = selectIndex; + await this.audioCastController.initAVCast(this.songList, selectIndex, startPosition); + // [Start AvCastControllerPlayControl] + this.audioCastController.avCastController?.on('playNext', () => { + this.playNextOrPrevious('next'); + }); + this.audioCastController.avCastController?.on('playPrevious', () => { + this.playNextOrPrevious('previous'); + }); + // [End AvCastControllerPlayControl] + } catch (error) { + hilog.error(0x0000, TAG, `avCastController on event failed, the error is: ${JSON.stringify(error)}`); + } } - this.selectIndex = selectIndex; - await this.audioCastController.initAVCast(this.songList, selectIndex, startPosition); - // [Start AvCastControllerPlayControl] - this.audioCastController.avCastController?.on('playNext', () => { - this.playNextOrPrevious('next'); - }); - this.audioCastController.avCastController?.on('playPrevious', () => { - this.playNextOrPrevious('previous'); - }); - // [End AvCastControllerPlayControl] } /** @@ -226,17 +238,21 @@ export struct ControlAreaComponent { } await this.avSessionController.setAVMetadata(this.isAvPlayerPlay); this.avSessionController.setAvSessionListener(controller); - // [Start AvSessionPlayControl] - this.avSessionController.AVSession?.on('playNext', () => { - this.playNextOrPrevious('next'); - }); - this.avSessionController.AVSession?.on('playPrevious', () => { - this.playNextOrPrevious('previous'); - }); - // [End AvSessionPlayControl] - this.avSessionController.AVSession?.on('setLoopMode', () => { - this.switchPlayMode(); - }); + try { + // [Start AvSessionPlayControl] + this.avSessionController.AVSession?.on('playNext', () => { + this.playNextOrPrevious('next'); + }); + this.avSessionController.AVSession?.on('playPrevious', () => { + this.playNextOrPrevious('previous'); + }); + // [End AvSessionPlayControl] + this.avSessionController.AVSession?.on('setLoopMode', () => { + this.switchPlayMode(); + }); + } catch (error) { + hilog.error(0x0000, TAG, `avSession on event failed, the error is: ${JSON.stringify(error)}`); + } this.initAVCastPicker(); } diff --git a/entry/src/main/ets/component/PlayerInfoComponent.ets b/entry/src/main/ets/component/PlayerInfoComponent.ets index f60ba12..92c02ff 100644 --- a/entry/src/main/ets/component/PlayerInfoComponent.ets +++ b/entry/src/main/ets/component/PlayerInfoComponent.ets @@ -115,7 +115,11 @@ export struct PlayerInfoComponent { } if (this.avSessionController) { this.avSessionController.unregisterSessionListener(); - this.avSessionController.AVSession?.destroy(); + try { + this.avSessionController.AVSession?.destroy(); + } catch (error) { + hilog.error(0x0000, TAG, `avSession destroy failed, the error is: ${JSON.stringify(error)}`); + } this.avSessionController = undefined; } } diff --git a/entry/src/main/ets/controller/AVSessionController.ets b/entry/src/main/ets/controller/AVSessionController.ets index 8f8f04e..b2b30d8 100644 --- a/entry/src/main/ets/controller/AVSessionController.ets +++ b/entry/src/main/ets/controller/AVSessionController.ets @@ -156,7 +156,11 @@ export class AVSessionController { } public async stopCasting() { - await this.AVSession?.stopCasting(); + try { + await this.AVSession?.stopCasting(); + } catch (error) { + hilog.error(0x0000, TAG, `avSession stopCasting failed, the error is: ${JSON.stringify(error)}`); + } } /** @@ -166,40 +170,52 @@ export class AVSessionController { */ public async setAvSessionListener(controller: Controller) { await this.unregisterSessionListener(); - // [Start ListenAvSessionPlay] - this.AVSession?.on('play', () => controller?.setPlaying()); - this.AVSession?.on('pause', () => controller?.setPause()); - // [End ListenAvSessionPlay] - this.AVSession?.on('stop', () => controller?.setStop()); - this.AVSession?.on('seek', (time: number) => { - controller?.seek(time); - }); + try { + // [Start ListenAvSessionPlay] + this.AVSession?.on('play', () => controller?.setPlaying()); + this.AVSession?.on('pause', () => controller?.setPause()); + // [End ListenAvSessionPlay] + this.AVSession?.on('stop', () => controller?.setStop()); + this.AVSession?.on('seek', (time: number) => { + controller?.seek(time); + }); + } catch (error) { + hilog.error(0x0000, TAG, `avSession on event failed, the error is: ${JSON.stringify(error)}`); + } } public async setLoopModeState(AVSessionLoopMode: number) { if (this.AVSession) { - this.AVSession.setAVPlaybackState({ loopMode: AVSessionLoopMode }, (err: BusinessError) => { - if (err) { - hilog.error(0x0000, TAG, `SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`); - } else { - hilog.info(0x0000, TAG, 'SetAVPlaybackState successfully'); - } - }); + try { + this.AVSession.setAVPlaybackState({ loopMode: AVSessionLoopMode }, (err: BusinessError) => { + if (err) { + hilog.error(0x0000, TAG, `SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`); + } else { + hilog.info(0x0000, TAG, 'SetAVPlaybackState successfully'); + } + }); + } catch (error) { + hilog.error(0x0000, TAG, `avSession setAVPlaybackState failed, the error is: ${JSON.stringify(error)}`); + } } } public initAvSessionPlayState(avPlayerController: AudioPlayerController | undefined) { - this.AVSession?.setAVPlaybackState({ - state: avPlayerController?.state === 'playing' ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : - avSession.PlaybackState.PLAYBACK_STATE_PAUSE, - position: { - elapsedTime: avPlayerController?.currentTime, - updateTime: new Date().getTime(), - }, - speed: 1.0, - bufferedTime: 14000, - duration: avPlayerController?.durationTime - }); + try { + this.AVSession?.setAVPlaybackState({ + state: avPlayerController?.state === 'playing' ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : + avSession.PlaybackState.PLAYBACK_STATE_PAUSE, + position: { + elapsedTime: avPlayerController?.currentTime, + updateTime: new Date().getTime(), + }, + speed: 1.0, + bufferedTime: 14000, + duration: avPlayerController?.durationTime + }); + } catch (error) { + hilog.error(0x0000, TAG, `avSession setAVPlaybackState failed, the error is: ${JSON.stringify(error)}`); + } } /** @@ -207,12 +223,16 @@ export class AVSessionController { * @param state Current player state ('playing' or other). */ public async setAvSessionState(isPlay: boolean) { - // [Start SetAvSessionPlay] - await this.AVSession?.setAVPlaybackState({ - state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : - avSession.PlaybackState.PLAYBACK_STATE_PAUSE, - }); - // [End SetAvSessionPlay] + try { + // [Start SetAvSessionPlay] + await this.AVSession?.setAVPlaybackState({ + state: isPlay ? avSession.PlaybackState.PLAYBACK_STATE_PLAY : + avSession.PlaybackState.PLAYBACK_STATE_PAUSE, + }); + // [End SetAvSessionPlay] + } catch (error) { + hilog.error(0x0000, TAG, `avSession setAVPlaybackState failed, the error is: ${JSON.stringify(error)}`); + } } /** @@ -220,14 +240,18 @@ export class AVSessionController { * @param position Current playback position in milliseconds. */ public async setAvSessionPosition(position: number) { - // [Start SetAvSessionPosition] - await this.AVSession?.setAVPlaybackState({ - position: { - elapsedTime: position, - updateTime: new Date().getTime() - } - }); - // [End SetAvSessionPosition] + try { + // [Start SetAvSessionPosition] + await this.AVSession?.setAVPlaybackState({ + position: { + elapsedTime: position, + updateTime: new Date().getTime() + } + }); + // [End SetAvSessionPosition] + } catch (error) { + hilog.error(0x0000, TAG, `avSession setAVPlaybackState failed, the error is: ${JSON.stringify(error)}`); + } } async unregisterSessionListener() { diff --git a/entry/src/main/ets/controller/AudioCastController.ets b/entry/src/main/ets/controller/AudioCastController.ets index 7ca36e1..6fb49a6 100644 --- a/entry/src/main/ets/controller/AudioCastController.ets +++ b/entry/src/main/ets/controller/AudioCastController.ets @@ -96,8 +96,12 @@ export class AudioCastController implements Controller { this.songList = songList; this.musicIndex = musicIndex; await this.setCastResource(startPosition); - let currentItem = await this.avCastController?.getCurrentItem(); - this.duration = currentItem?.description!.duration!; + try { + let currentItem = await this.avCastController?.getCurrentItem(); + this.duration = currentItem?.description!.duration!; + } catch (error) { + hilog.error(0x0000, TAG, `avCastController getCurrentItem failed, the error is: ${JSON.stringify(error)}`); + } this.setAVCastCallback(); } @@ -108,79 +112,115 @@ export class AudioCastController implements Controller { // [EndExclude AudioCastController] setAVCastCallback() { this.unregisterCastListener(); - // [StartExclude AudioCastController] - this.avCastController?.on('playbackStateChange', ['state'], async (playbackState: avSession.AVPlaybackState) => { - if (playbackState.state) { - this.state = playbackState.state; - } - }); - // [EndExclude AudioCastController] - this.avCastController?.on('playbackStateChange', ['position'], (playbackState: avSession.AVPlaybackState) => { - if (playbackState.position) { - this.elapsedTime = playbackState.position.elapsedTime; - } - }); - // [StartExclude AudioCastController] - this.avCastController?.on('playbackStateChange', ['volume'], (playbackState: avSession.AVPlaybackState) => { - if (playbackState.volume) { - this.volume = playbackState.volume; - } - }); - this.avCastController?.on('error', (error: BusinessError) => { - hilog.error(0x0000, TAG, `error happened, error code: ${error.code}, error message : ${error.message}.`); - }) - this.avCastController?.on('playbackStateChange', 'all', (playbackState: avSession.AVPlaybackState) => { - hilog.info(0x0000, TAG, `playbackStateChange state ${playbackState}`); - }); - // [EndExclude AudioCastController] + try { + // [StartExclude AudioCastController] + this.avCastController?.on('playbackStateChange', ['state'], async (playbackState: avSession.AVPlaybackState) => { + if (playbackState.state) { + this.state = playbackState.state; + } + }); + // [EndExclude AudioCastController] + this.avCastController?.on('playbackStateChange', ['position'], (playbackState: avSession.AVPlaybackState) => { + if (playbackState.position) { + this.elapsedTime = playbackState.position.elapsedTime; + } + }); + // [StartExclude AudioCastController] + this.avCastController?.on('playbackStateChange', ['volume'], (playbackState: avSession.AVPlaybackState) => { + if (playbackState.volume) { + this.volume = playbackState.volume; + } + }); + this.avCastController?.on('error', (error: BusinessError) => { + hilog.error(0x0000, TAG, `error happened, error code: ${error.code}, error message : ${error.message}.`); + }) + this.avCastController?.on('playbackStateChange', 'all', (playbackState: avSession.AVPlaybackState) => { + hilog.info(0x0000, TAG, `playbackStateChange state ${playbackState}`); + }); + // [EndExclude AudioCastController] + } catch (error) { + hilog.error(0x0000, TAG, `avCastController on event failed, the error is: ${JSON.stringify(error)}`); + } } // [StartExclude AudioCastController] public async setPlaying() { - // [Start SetPlaying] - let avCommand: avSession.AVCastControlCommand = { command: 'play' }; - await this.avCastController?.sendControlCommand(avCommand); - // [End SetPlaying] + try { + // [Start SetPlaying] + let avCommand: avSession.AVCastControlCommand = { command: 'play' }; + await this.avCastController?.sendControlCommand(avCommand); + // [End SetPlaying] + } catch (error) { + hilog.error(0x0000, TAG, `avCastController sendControlCommand failed, the error is: ${JSON.stringify(error)}`); + } } public async setPause() { let avCommand: avSession.AVCastControlCommand = { command: 'pause' }; - await this.avCastController?.sendControlCommand(avCommand); + try { + await this.avCastController?.sendControlCommand(avCommand); + } catch (error) { + hilog.error(0x0000, TAG, `avCastController sendControlCommand failed, the error is: ${JSON.stringify(error)}`); + } } // [Start SendCommand] public async seek(timeMS: number) { let avCommand: avSession.AVCastControlCommand = { command: 'seek', parameter: timeMS }; - await this.avCastController?.sendControlCommand(avCommand); + try { + await this.avCastController?.sendControlCommand(avCommand); + } catch (error) { + hilog.error(0x0000, TAG, `avCastController sendControlCommand failed, the error is: ${JSON.stringify(error)}`); + } } public async setAVCastVolume(volume: number) { let avCommand: avSession.AVCastControlCommand = { command: 'setVolume', parameter: volume }; - await this.avCastController?.sendControlCommand(avCommand); + try { + await this.avCastController?.sendControlCommand(avCommand); + } catch (error) { + hilog.error(0x0000, TAG, `avCastController sendControlCommand failed, the error is: ${JSON.stringify(error)}`); + } } public async setPlayModel(mode: number) { let avCommand: avSession.AVCastControlCommand = { command: 'setLoopMode', parameter: mode }; - await this.avCastController?.sendControlCommand(avCommand); + try { + await this.avCastController?.sendControlCommand(avCommand); + } catch (error) { + hilog.error(0x0000, TAG, `avCastController sendControlCommand failed, the error is: ${JSON.stringify(error)}`); + } } // [End SendCommand] public async setStop() { let avCommand: avSession.AVCastControlCommand = { command: 'stop' }; - await this.avCastController?.sendControlCommand(avCommand); + try { + await this.avCastController?.sendControlCommand(avCommand); + } catch (error) { + hilog.error(0x0000, TAG, `avCastController sendControlCommand failed, the error is: ${JSON.stringify(error)}`); + } } /** * Releases AV cast controller resources and removes event listeners. */ public async releaseAVCast() { - await this.avCastController?.release(); + try { + await this.avCastController?.release(); + } catch (error) { + hilog.error(0x0000, TAG, `avCastController release failed, the error is: ${JSON.stringify(error)}`); + } this.unregisterCastListener(); } public async unregisterCastListener() { - this.avCastController?.off('playbackStateChange'); - this.avCastController?.off('playNext'); - this.avCastController?.off('playPrevious'); - this.avCastController?.off('endOfStream'); + try { + this.avCastController?.off('playbackStateChange'); + this.avCastController?.off('playNext'); + this.avCastController?.off('playPrevious'); + this.avCastController?.off('endOfStream'); + } catch (error) { + hilog.error(0x0000, TAG, `avCastController off event failed, the error is: ${JSON.stringify(error)}`); + } } // [EndExclude AudioCastController] } diff --git a/entry/src/main/ets/controller/AudioPlayerController.ets b/entry/src/main/ets/controller/AudioPlayerController.ets index aad0dff..6dcf951 100644 --- a/entry/src/main/ets/controller/AudioPlayerController.ets +++ b/entry/src/main/ets/controller/AudioPlayerController.ets @@ -168,7 +168,11 @@ export class AudioPlayerController implements Controller { async setPlaying() { const validPlayingStates = ['prepared', 'paused', 'completed']; if (validPlayingStates.includes(this.state)) { - await this.avPlayer.play(); + try { + await this.avPlayer.play(); + } catch (error) { + hilog.error(0x0000, TAG, `avPlayer play failed, the error is: ${JSON.stringify(error)}`); + } return; } else { hilog.error(0x0000, TAG, `setAudioPlayer Playing error,this state is ${this.state}`); @@ -177,7 +181,11 @@ export class AudioPlayerController implements Controller { async setPause() { if (this.state === 'playing') { - await this.avPlayer.pause(); + try { + await this.avPlayer.pause(); + } catch (error) { + hilog.error(0x0000, TAG, `avPlayer pause failed, the error is: ${JSON.stringify(error)}`); + } return; } } @@ -185,7 +193,11 @@ export class AudioPlayerController implements Controller { async setStop() { const validStopStates = ['prepared', 'paused', 'completed', 'playing']; if (validStopStates.includes(this.state)) { - await this.avPlayer.stop(); + try { + await this.avPlayer.stop(); + } catch (error) { + hilog.error(0x0000, TAG, `avPlayer stop failed, the error is: ${JSON.stringify(error)}`); + } return; } else { hilog.error(0x0000, TAG, `setAudioPlayer Stop error,this state is ${this.state}`); @@ -235,7 +247,11 @@ export class AudioPlayerController implements Controller { this.avPlayer.off('error'); this.avPlayer.off('volumeChange'); this.avPlayer.off('stateChange'); - await this.avPlayer.release(); + try { + await this.avPlayer.release(); + } catch (error) { + hilog.error(0x0000, TAG, `avPlayer release failed, the error is: ${JSON.stringify(error)}`); + } AppStorage.setOrCreate('avPlayerController', undefined); } } \ No newline at end of file diff --git a/entry/src/main/ets/controller/AudioRendererController.ets b/entry/src/main/ets/controller/AudioRendererController.ets index 81698c2..e0c29d9 100644 --- a/entry/src/main/ets/controller/AudioRendererController.ets +++ b/entry/src/main/ets/controller/AudioRendererController.ets @@ -109,8 +109,12 @@ export class AudioRendererController implements Controller { break; } }); - this.audioRenderer.on('audioInterrupt', this.interruptCallback); - this.audioRenderer.on('outputDeviceChangeWithInfo', this.outputDeviceChangeCallback); + try { + this.audioRenderer.on('audioInterrupt', this.interruptCallback); + this.audioRenderer.on('outputDeviceChangeWithInfo', this.outputDeviceChangeCallback); + } catch (error) { + hilog.error(0x0000, TAG, `audioRenderer on event failed, the error is: ${JSON.stringify(error)}`); + } } public async setAvSessionCallback() { @@ -127,42 +131,46 @@ export class AudioRendererController implements Controller { let secondBufferWalk = SecondBufferWalk.getInstance().get(); let bufferWalk = 0; let options: Options | undefined = undefined; - this.audioRenderer.on('writeData', (buffer) => { - if (!this.songRawFileDescriptor) { - return; - } - options = { - offset: this.currentOffset, - length: buffer.byteLength - }; - try { - fileIo.readSync(this.songRawFileDescriptor.fd, buffer, options); - this.currentOffset += buffer.byteLength; - this.bufferRead = this.currentOffset - this.initOffset; - bufferWalk += buffer.byteLength; - hilog.info(0x0000, TAG, 'buffer.byteLength+bufferWalk+bufferRead: ' + buffer.byteLength +'%'+ bufferWalk + '%' + this.bufferRead); - hilog.info(0x0000, TAG, - `songRawFileDescriptor get successed` + 'bufferRead is ' + this.bufferRead + '///' + 'bufferNeedRead is ' + - this.bufferNeedRead); - if (this.bufferRead <= this.bufferNeedRead) { - if (bufferWalk >= secondBufferWalk) { - let curMs = MediaTools.getMsFromByteLength(this.bufferRead); - this.seek(curMs); + try { + this.audioRenderer.on('writeData', (buffer) => { + if (!this.songRawFileDescriptor) { + return; + } + options = { + offset: this.currentOffset, + length: buffer.byteLength + }; + try { + fileIo.readSync(this.songRawFileDescriptor.fd, buffer, options); + this.currentOffset += buffer.byteLength; + this.bufferRead = this.currentOffset - this.initOffset; + bufferWalk += buffer.byteLength; + hilog.info(0x0000, TAG, 'buffer.byteLength+bufferWalk+bufferRead: ' + buffer.byteLength +'%'+ bufferWalk + '%' + this.bufferRead); + hilog.info(0x0000, TAG, + `songRawFileDescriptor get successed` + 'bufferRead is ' + this.bufferRead + '///' + 'bufferNeedRead is ' + + this.bufferNeedRead); + if (this.bufferRead <= this.bufferNeedRead) { + if (bufferWalk >= secondBufferWalk) { + let curMs = MediaTools.getMsFromByteLength(this.bufferRead); + this.seek(curMs); + bufferWalk = 0; + } + } else { bufferWalk = 0; + let curMs = MediaTools.getMsFromByteLength(this.songRawFileDescriptor.length); + hilog.info(0x0000, TAG, 'setWriteDataCallback CurMs is ' + curMs); + this.seek(curMs); + this.setPlayNext(); } - } else { - bufferWalk = 0; - let curMs = MediaTools.getMsFromByteLength(this.songRawFileDescriptor.length); - hilog.info(0x0000, TAG, 'setWriteDataCallback CurMs is ' + curMs); - this.seek(curMs); - this.setPlayNext(); + } catch (error) { + hilog.error(0x0000, TAG, `fileIO readSync fail the error is:${JSON.stringify(error)}`); } - } catch (error) { - hilog.error(0x0000, TAG, `fileIO readSync fail the error is:${JSON.stringify(error)}`); - } - hilog.info(0x0000, TAG, 'writeData is calling. '); - }) + hilog.info(0x0000, TAG, 'writeData is calling. '); + }) + } catch (error) { + hilog.error(0x0000, TAG, `audioRenderer on event failed, the error is: ${JSON.stringify(error)}`); + } } private interruptCallback: (interruptEvent: audio.InterruptEvent) => void = @@ -223,7 +231,11 @@ export class AudioRendererController implements Controller { private async loadSongAssent() { let songItem = this.songList[this.musicIndex]; await this.songItemBuilder.build(songItem); - this.songRawFileDescriptor = await this.context?.resourceManager.getRawFd(songItem.pcmSrc); + try { + this.songRawFileDescriptor = await this.context?.resourceManager.getRawFd(songItem.pcmSrc); + } catch (error) { + hilog.error(0x0000, TAG, `getRawFd failed, the error is: ${JSON.stringify(error)}`); + } if (!this.songRawFileDescriptor) { hilog.error(0x0000, TAG, `loadSongAssent faile : songRawFileDescriptor get failed`); return; @@ -365,9 +377,13 @@ export class AudioRendererController implements Controller { if (!this.audioRenderer) { return; } - this.audioRenderer.off('stateChange'); - this.audioRenderer.off('writeData'); - this.audioRenderer.off('outputDeviceChangeWithInfo'); - this.audioRenderer.off('audioInterrupt'); + try { + this.audioRenderer.off('stateChange'); + this.audioRenderer.off('writeData'); + this.audioRenderer.off('outputDeviceChangeWithInfo'); + this.audioRenderer.off('audioInterrupt'); + } catch (error) { + hilog.error(0x0000, TAG, `audioRenderer off event failed, the error is: ${JSON.stringify(error)}`); + } } } \ No newline at end of file diff --git a/entry/src/main/ets/entryability/EntryAbility.ets b/entry/src/main/ets/entryability/EntryAbility.ets index 3a9758e..3f2d8d1 100644 --- a/entry/src/main/ets/entryability/EntryAbility.ets +++ b/entry/src/main/ets/entryability/EntryAbility.ets @@ -27,24 +27,25 @@ export default class EntryAbility extends UIAbility { async onCreate(): Promise { AppStorage.setOrCreate('context', this.context); + let fileList: Array = []; try { this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET); + fileList = this.context.resourceManager.getRawFileListSync(''); } catch (err) { hilog.error(DOMAIN, TAG, `setColorMode failed.`); } - let fileList: Array = this.context.resourceManager.getRawFileListSync(''); for (const fileName of fileList) { if (fileName.includes('.')) { - let value = await this.context.resourceManager.getRawFileContent(fileName); - let myBuffer: ArrayBufferLike = value.buffer; - let filePath = this.context.filesDir + `/${fileName}`; try { + let value = await this.context.resourceManager.getRawFileContent(fileName); + let myBuffer: ArrayBufferLike = value.buffer; + let filePath = this.context.filesDir + `/${fileName}`; let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE); fileIo.writeSync(file.fd, myBuffer); fileIo.closeSync(file); - } catch (err) { - hilog.error(DOMAIN, TAG, `fileIO failed Cause: code ${err.code}, filePath is: ${filePath}`); + } catch (error) { + hilog.error(DOMAIN, TAG, `fileIO failed Cause, the error is ${JSON.stringify(error)}`); } } } -- Gitee From 2b0eab08e048dedd15851b1bdca640b02554b5cf Mon Sep 17 00:00:00 2001 From: guangda Date: Tue, 23 Sep 2025 15:24:01 +0800 Subject: [PATCH 2/2] fix bug --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bdcb5f0..198dafb 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ │ │ └───SongItemBuilder.ets // 音乐数据转换工具类 │ ├───component │ │ ├───ControlAreaComponent.ets // 控制器组件 -│ │ ├───LrcView.ets // 歌词展示页 +│ │ ├───LrcInfoComponent.ets // 歌词展示页 │ │ ├───LyricsComponent.ets // 歌词控制器组件 │ │ ├───MusicInfoComponent.ets // 音乐详情组件 │ │ ├───PlayerInfoComponent.ets // 音乐播放页组件 -- Gitee