参考官方文档:https://docs.openharmony.cn/pages/v5.0/zh-cn/application-dev/reference/apis-audio-kit/js-apis-audio.md#ondevicechangedeprecated

import { audio } from '@kit.AudioKit';

let audioManager = audio.getAudioManager();//获取音频管理器

private EarPhone_on() : void {
    audioManager.on('deviceChange', (deviceChanged: audio.DeviceChangeAction) => {
      console.info(`device change type : ${deviceChanged.type} `);
      console.info(`device descriptor size : ${deviceChanged.deviceDescriptors.length} `);
      console.info(`device change descriptor deviceRole : ${deviceChanged.deviceDescriptors[0].deviceRole} `);
      console.info(`device change descriptor deviceType: ${deviceChanged.deviceDescriptors[0].deviceType} `);

      deviceChanged.deviceDescriptors.forEach(descriptor => {
        console.info(`device change descriptor deviceRole: ${descriptor.deviceRole} `);
        console.info(`device change descriptor deviceType: ${descriptor.deviceType} `);

        if (descriptor.deviceType === 3) { // 设备类型 3 代表耳机
          if (deviceChanged.type === 1) { // 连接状态 1 代表设备断开
            console.info('Earphones disconnected');

          } else if (deviceChanged.type === 0) { // 连接状态 0 代表设备连接
            console.info('Earphones connected');

          }
        }
      });

    });
  }

 

Logo

社区规范:仅讨论OpenHarmony相关问题。

更多推荐