目录

Querying and Listening for Audio Input Devices

You can use APIs to manage audio input devices, including querying audio input device information and listening for device connection status changes. For details about the APIs, see AudioRoutingManager.

The following examples are code snippets. For the complete sample, click the link at the lower right of each code snippet.

Creating an AudioRoutingManager Instance

Before using AudioRoutingManager to manage audio devices, import the audio module and create an instance.

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

let audioManager = audio.getAudioManager();
let audioRoutingManager = audioManager.getRoutingManager();

Supported Audio Input Device Types

The table below lists the supported audio input devices.

Name Value Description
WIRED_HEADSET 3 Wired headset with a microphone.
BLUETOOTH_SCO 7 Bluetooth device using Synchronous Connection Oriented (SCO) links.
MIC 15 Microphone.
USB_HEADSET 22 USB headset with a microphone.
NEARLINK 31 NearLink device.

Obtaining Input Device Information

Use the getDevices method to obtain information about all current input devices.

import { audio } from '@kit.AudioKit';
import { BusinessError } from '@kit.BasicServicesKit';
// ...

  audioRoutingManager.getDevices(audio.DeviceFlag.INPUT_DEVICES_FLAG).then((audioDeviceDescriptors: audio.
    AudioDeviceDescriptors) => {
    console.info(`Succeeded in getting devices. AudioDeviceDescriptors: ${JSON.stringify(audioDeviceDescriptors)}`);
    // ...
  }).catch((err: BusinessError) => {
    console.error(`Failed to get devices. Code: ${err.code}, message: ${err.message}`);
    // ...
  });

Listening for Device Connection State Changes

Set a listener to listen for changes of the device connection state. When a device is connected or disconnected, a callback is triggered.

import { audio } from '@kit.AudioKit';
import { BusinessError } from '@kit.BasicServicesKit';
// ...

let deviceChangeCallback = (deviceChanged: audio.DeviceChangeAction) => {
  console.info(`Succeeded in using on function. DeviceChangeAction: ${JSON.stringify(deviceChanged)}`);
  // ...
}
// ...

  try {
    // Listen for audio device state changes.
    audioRoutingManager.on('deviceChange', audio.DeviceFlag.INPUT_DEVICES_FLAG, deviceChangeCallback);
  } catch (err) {
    let error = err as BusinessError;
    console.error(`Failed to use on function. Code: ${error.code}, message: ${error.message}`);
    // ...
  }