AvSessionController.ets 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. /*
  2. * Copyright (c) 2024 Huawei Device Co., Ltd.
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. import { hilog } from '@kit.PerformanceAnalysisKit';
  16. import { common, wantAgent } from '@kit.AbilityKit';
  17. import { BusinessError } from '@kit.BasicServicesKit';
  18. import { avSession } from '@kit.AVSessionKit';
  19. import { BackgroundTaskManager } from '../common/util/BackgroundTaskManager';
  20. import { VideoItem } from '../viewmodel/VideoItem';
  21. import { ImageUtil, PreferencesUtil } from '@pura/harmony-utils';
  22. import { image } from '@kit.ImageKit';
  23. import { SettingPage } from '../pages/SettingPage';
  24. import { Utility } from '../common/util/Utility';
  25. import LyricUtil from '../common/util/LyricUtil';
  26. import ImageUtils from '../common/util/ImageUtils';
  27. const TAG = 'onecold AvSessionController';
  28. export class AvSessionController {
  29. private static instance: AvSessionController | null;
  30. private context: common.UIAbilityContext | undefined = undefined;
  31. private avSession: avSession.AVSession | undefined = undefined;
  32. private avSessionMetadata: avSession.AVMetadata | undefined = undefined;
  33. constructor(isVideo:boolean) {
  34. this.initAvSession(isVideo);
  35. }
  36. public static getInstance(isVideo:boolean): AvSessionController {
  37. if (!AvSessionController.instance) {
  38. AvSessionController.instance = new AvSessionController(isVideo);
  39. }
  40. return AvSessionController.instance;
  41. }
  42. public initAvSession(isVideo:boolean) {
  43. if(isVideo){
  44. let isBgPlayOpen = PreferencesUtil.getBooleanSync(SettingPage.IS_BGPLAY_OPEN,true)
  45. if(!isBgPlayOpen)
  46. return
  47. }
  48. this.context = AppStorage.get('context');
  49. if (!this.context) {
  50. hilog.info(0x0000, TAG, `session create failed : conext is undefined`);
  51. return;
  52. }
  53. let type: avSession.AVSessionType = isVideo ? 'video' : 'audio';
  54. avSession.createAVSession(this.context, 'sessionName', type).then(async (avSession) => {
  55. this.avSession = avSession;
  56. hilog.info(0x0000, TAG, `session create successed : sessionId : ${this.avSession.sessionId}`);
  57. BackgroundTaskManager.startContinuousTask(this.context);
  58. this.setLaunchAbility();
  59. this.avSession.activate();
  60. this.avSession.setExtras({
  61. requireAbilityList: ['url-cast']
  62. });
  63. }).catch((error:Error) => {
  64. console.error('Failed to create AVSession:', error);
  65. });
  66. }
  67. private setLaunchAbility() {
  68. if (!this.context) {
  69. return;
  70. }
  71. const wantAgentInfo: wantAgent.WantAgentInfo = {
  72. wants: [
  73. {
  74. bundleName: this.context.abilityInfo.bundleName,
  75. abilityName: this.context.abilityInfo.name
  76. }
  77. ],
  78. operationType: wantAgent.OperationType.START_ABILITIES,
  79. requestCode: 0,
  80. wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
  81. };
  82. wantAgent.getWantAgent(wantAgentInfo).then((agent) => {
  83. if (this.avSession) {
  84. this.avSession.setLaunchAbility(agent);
  85. }
  86. });
  87. }
  88. public getAvSession() {
  89. return this.avSession;
  90. }
  91. public getAvSessionMetadata() {
  92. return this.avSessionMetadata;
  93. }
  94. public async setAVMetadata(curSource: VideoItem, duration: number) {
  95. if (curSource === undefined) {
  96. hilog.error(0x0000, TAG, 'SetAVMetadata Error, curSource is null');
  97. return;
  98. }
  99. BackgroundTaskManager.startContinuousTask(this.context);
  100. const imagePixMap = await ImageUtil.getPixelMapFromMedia($r('app.media.ic_avatar7'));
  101. let metadata: avSession.AVMetadata = {
  102. assetId: `${curSource.filePath}`,
  103. title: curSource.name,
  104. filter: avSession.ProtocolType.TYPE_CAST_PLUS_STREAM|avSession.ProtocolType.TYPE_DLNA,
  105. mediaImage: imagePixMap,
  106. duration: duration,
  107. // 如果是DRM资源,配置支持的DRM uuid 用于设备过滤。非DRM资源不配置。
  108. drmSchemes: ['3d5e6d35-9b9a-41e8-b843-dd3c6e72c42c']
  109. };
  110. if (this.avSession) {
  111. this.avSession.setAVMetadata(metadata).then(() => {
  112. this.avSessionMetadata = metadata;
  113. hilog.info(0x0000, TAG, 'SetAVMetadata successfully');
  114. }).catch((err: BusinessError) => {
  115. hilog.error(0x0000, TAG, `SetAVMetadata BusinessError: code: ${err.code}, message: ${err.message}`);
  116. });
  117. }
  118. }
  119. public async setAVMetadataMusic(curSource: VideoItem, duration: number,lyricContent?:string) {
  120. if (curSource === undefined) {
  121. hilog.error(0x0000, TAG, 'SetAVMetadata Error, curSource is null');
  122. return;
  123. }
  124. try {
  125. BackgroundTaskManager.startContinuousTask(this.context);
  126. let pixelMapPath:string|undefined = curSource.pixelMapPath
  127. let imagePixMap: PixelMap|string ;
  128. if(pixelMapPath){
  129. imagePixMap = await ImageUtils.imagePathToPixelMap(pixelMapPath)
  130. }else{
  131. imagePixMap = await ImageUtil.getPixelMapFromMedia($r('app.media.ic_avatar2'));
  132. }
  133. let lyric = ''
  134. if(lyricContent)
  135. lyric = LyricUtil.convertLyricToSimpleLrc(lyricContent)
  136. hilog.info(0x0000, TAG, 'onecold SetAVMetadata successfully curSource.pixelMapPath '+curSource.pixelMapPath);
  137. let metadata: avSession.AVMetadata = {
  138. assetId: `${curSource.filePath}`,
  139. title: curSource.name,
  140. filter: avSession.ProtocolType.TYPE_CAST_PLUS_STREAM|avSession.ProtocolType.TYPE_DLNA,
  141. artist: curSource.artist,
  142. mediaImage: imagePixMap,
  143. duration: duration,
  144. lyric:lyric,
  145. };
  146. if (this.avSession) {
  147. this.avSession.setAVMetadata(metadata).then(() => {
  148. this.avSessionMetadata = metadata;
  149. hilog.info(0x0000, TAG, 'SetAVMetadata successfully');
  150. }).catch((err: BusinessError) => {
  151. hilog.error(0x0000, TAG, `SetAVMetadata BusinessError: code: ${err.code}, message: ${err.message}`);
  152. });
  153. }
  154. } catch (error) {
  155. console.warn(' setAVMetadataMusic:', error.message);
  156. }
  157. }
  158. public setAvSessionPlayState(playbackState: avSession.AVPlaybackState) {
  159. if (this.avSession) {
  160. BackgroundTaskManager.startContinuousTask(this.context);
  161. this.avSession.setAVPlaybackState(playbackState, (err: BusinessError) => {
  162. if (err) {
  163. hilog.error(0x0000, TAG, `SetAVPlaybackState BusinessError: code: ${err.code}, message: ${err.message}`);
  164. } else {
  165. hilog.info(0x0000, TAG, 'SetAVPlaybackState successfully');
  166. }
  167. });
  168. }
  169. }
  170. async unregisterSessionListener() {
  171. if (!this.avSession) {
  172. return;
  173. }
  174. this.avSession.off('play');
  175. this.avSession.off('pause');
  176. this.avSession.off('playNext');
  177. this.avSession.off('playPrevious');
  178. this.avSession.off('setLoopMode');
  179. this.avSession.off('seek');
  180. this.avSession.off('toggleFavorite');
  181. this.avSession.destroy()
  182. BackgroundTaskManager.stopContinuousTask(this.context);
  183. }
  184. }