销毁媒体会话的destroy是异步接口,需要确保销毁流程完毕后,才能创建新的AVSession。
import { avSession } from '@kit.AVSessionKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; @Entry @Component struct Index { private session?: avSession.AVSession = undefined; build() { Column() { Button('Create Session') .onClick(async () => { let context = this.getUIContext().getHostContext() as common.UIAbilityContext; if (this.session !== undefined) { this.session.destroy() .then(async () => { try { this.session = await avSession.createAVSession(context, 'SESSION_NAME', 'audio'); console.info(`create session successfully`); } catch (err) { console.error(`failed to create session, error=${JSON.stringify(err)}`); } }) .catch((err: BusinessError) => { console.error(`failed to destroy session, error=${JSON.stringify(err)}`); }); } else { try { this.session = await avSession.createAVSession(context, 'SESSION_NAME', 'audio'); } catch (err) { console.error(`failed to create session, error=${JSON.stringify(err)}`); } } }); } .width('100%') .height('100%') .justifyContent(FlexAlign.Center) .alignItems(HorizontalAlign.Center); } }