harmony 鸿蒙@ohos.multimedia.audio (Audio Management)

2022-08-09 浏览 (1202)

@ohos.multimedia.audio (Audio Management)

The Audio module provides basic audio management capabilities, including audio volume and audio device management, and audio data collection and rendering.

This module provides the following common audio-related functions:

  • AudioManager: audio management.
  • AudioRenderer: audio rendering, used to play Pulse Code Modulation (PCM) audio data.
  • AudioCapturer: audio capture, used to record PCM audio data.
  • TonePlayer: tone player, used to manage and play Dual Tone Multi Frequency (DTMF) tones, such as dial tones and ringback tones.

NOTE

The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.

Modules to Import

import audio from '@ohos.multimedia.audio';

Constants

NameTypeReadableWritableDescription
LOCAL_NETWORK_ID9+stringYesNoNetwork ID of the local device.
This is a system API.
System capability: SystemCapability.Multimedia.Audio.Device
DEFAULT_VOLUME_GROUP_ID9+numberYesNoDefault volume group ID.
System capability: SystemCapability.Multimedia.Audio.Volume
DEFAULT_INTERRUPT_GROUP_ID9+numberYesNoDefault audio interruption group ID.
System capability: SystemCapability.Multimedia.Audio.Interrupt

Example

import audio from '@ohos.multimedia.audio';

const localNetworkId = audio.LOCAL_NETWORK_ID;
const defaultVolumeGroupId = audio.DEFAULT_VOLUME_GROUP_ID;
const defaultInterruptGroupId = audio.DEFAULT_INTERRUPT_GROUP_ID;

audio.getAudioManager

getAudioManager(): AudioManager

Obtains an AudioManager instance.

System capability: SystemCapability.Multimedia.Audio.Core

Return value

TypeDescription
AudioManagerAudioManager instance.

Example

import audio from '@ohos.multimedia.audio';
let audioManager = audio.getAudioManager();

audio.createAudioRenderer8+

createAudioRenderer(options: AudioRendererOptions, callback: AsyncCallback<AudioRenderer>): void

Creates an AudioRenderer instance. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
optionsAudioRendererOptionsYesRenderer configurations.
callbackAsyncCallback<AudioRenderer>YesCallback used to return the AudioRenderer instance.

Example

import fs from '@ohos.file.fs';
import audio from '@ohos.multimedia.audio';

let audioStreamInfo: audio.AudioStreamInfo = {
  samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
  channels: audio.AudioChannel.CHANNEL_1,
  sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
  encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
}

let audioRendererInfo: audio.AudioRendererInfo = {
  content: audio.ContentType.CONTENT_TYPE_SPEECH,
  usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION,
  rendererFlags: 0
}

let audioRendererOptions: audio.AudioRendererOptions = {
  streamInfo: audioStreamInfo,
  rendererInfo: audioRendererInfo
}

audio.createAudioRenderer(audioRendererOptions,(err, data) => {
  if (err) {
    console.error(`AudioRenderer Created: Error: ${err}`);
  } else {
    console.info('AudioRenderer Created: Success: SUCCESS');
    let audioRenderer = data;
  }
});

audio.createAudioRenderer8+

createAudioRenderer(options: AudioRendererOptions): Promise<AudioRenderer>

Creates an AudioRenderer instance. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
optionsAudioRendererOptionsYesRenderer configurations.

Return value

TypeDescription
Promise<AudioRenderer>Promise used to return the AudioRenderer instance.

Example

import fs from '@ohos.file.fs';
import audio from '@ohos.multimedia.audio';
import { BusinessError } from '@ohos.base';

let audioStreamInfo: audio.AudioStreamInfo = {
  samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
  channels: audio.AudioChannel.CHANNEL_1,
  sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
  encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
}

let audioRendererInfo: audio.AudioRendererInfo = {
  content: audio.ContentType.CONTENT_TYPE_SPEECH,
  usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION,
  rendererFlags: 0
}

let audioRendererOptions: audio.AudioRendererOptions = {
  streamInfo: audioStreamInfo,
  rendererInfo: audioRendererInfo
}

let audioRenderer: audio.AudioRenderer;
audio.createAudioRenderer(audioRendererOptions).then((data) => {
  audioRenderer = data;
  console.info('AudioFrameworkRenderLog: AudioRenderer Created : Success : Stream Type: SUCCESS');
}).catch((err: BusinessError) => {
  console.error(`AudioFrameworkRenderLog: AudioRenderer Created : ERROR : ${err}`);
});

audio.createAudioCapturer8+

createAudioCapturer(options: AudioCapturerOptions, callback: AsyncCallback<AudioCapturer>): void

Creates an AudioCapturer instance. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Capturer

Required permissions: ohos.permission.MICROPHONE

Parameters

NameTypeMandatoryDescription
optionsAudioCapturerOptionsYesCapturer configurations.
callbackAsyncCallback<AudioCapturer>YesCallback used to return the AudioCapturer instance.

Example

import audio from '@ohos.multimedia.audio';
let audioStreamInfo: audio.AudioStreamInfo = {
  samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
  channels: audio.AudioChannel.CHANNEL_2,
  sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
  encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
}

let audioCapturerInfo: audio.AudioCapturerInfo = {
  source: audio.SourceType.SOURCE_TYPE_MIC,
  capturerFlags: 0
}

let audioCapturerOptions: audio.AudioCapturerOptions = {
  streamInfo: audioStreamInfo,
  capturerInfo: audioCapturerInfo
}

audio.createAudioCapturer(audioCapturerOptions, (err, data) => {
  if (err) {
    console.error(`AudioCapturer Created : Error: ${err}`);
  } else {
    console.info('AudioCapturer Created : Success : SUCCESS');
    let audioCapturer = data;
  }
});

audio.createAudioCapturer8+

createAudioCapturer(options: AudioCapturerOptions): Promise<AudioCapturer>

Creates an AudioCapturer instance. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Capturer

Required permissions: ohos.permission.MICROPHONE

Parameters

NameTypeMandatoryDescription
optionsAudioCapturerOptionsYesCapturer configurations.

Return value

TypeDescription
Promise<AudioCapturer>Promise used to return the AudioCapturer instance.

Example

import audio from '@ohos.multimedia.audio';
import { BusinessError } from '@ohos.base';

let audioStreamInfo: audio.AudioStreamInfo = {
  samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
  channels: audio.AudioChannel.CHANNEL_2,
  sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
  encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
}

let audioCapturerInfo: audio.AudioCapturerInfo = {
  source: audio.SourceType.SOURCE_TYPE_MIC,
  capturerFlags: 0
}

let audioCapturerOptions:audio.AudioCapturerOptions = {
  streamInfo: audioStreamInfo,
  capturerInfo: audioCapturerInfo
}

let audioCapturer: audio.AudioCapturer;
audio.createAudioCapturer(audioCapturerOptions).then((data) => {
  audioCapturer = data;
  console.info('AudioCapturer Created : Success : Stream Type: SUCCESS');
}).catch((err: BusinessError) => {
  console.error(`AudioCapturer Created : ERROR : ${err}`);
});

audio.createTonePlayer9+

createTonePlayer(options: AudioRendererInfo, callback: AsyncCallback<TonePlayer>): void

Creates a TonePlayer instance. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Tone

System API: This is a system API.

Parameters

NameTypeMandatoryDescription
optionsAudioRendererInfoYesAudio renderer information.
callbackAsyncCallback<TonePlayer>YesCallback used to return the TonePlayer instance.

Example

import audio from '@ohos.multimedia.audio';

let audioRendererInfo: audio.AudioRendererInfo = {
  usage : audio.StreamUsage.STREAM_USAGE_DTMF,
  rendererFlags : 0
}
let tonePlayer: audio.TonePlayer;

audio.createTonePlayer(audioRendererInfo, (err, data) => {
  console.info(`callback call createTonePlayer: audioRendererInfo: ${audioRendererInfo}`);
  if (err) {
    console.error(`callback call createTonePlayer return error: ${err.message}`);
  } else {
    console.info(`callback call createTonePlayer return data: ${data}`);
    tonePlayer = data;
  }
});

audio.createTonePlayer9+

createTonePlayer(options: AudioRendererInfo): Promise<TonePlayer>

Creates a TonePlayer instance. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Tone

System API: This is a system API.

Parameters

NameTypeMandatoryDescription
optionsAudioRendererInfoYesAudio renderer information.

Return value

TypeDescription
Promise<TonePlayer>Promise used to return the TonePlayer instance.

Example

import audio from '@ohos.multimedia.audio';
let tonePlayer: audio.TonePlayer;
async function createTonePlayerBefore(){
  let audioRendererInfo: audio.AudioRendererInfo = {
    usage : audio.StreamUsage.STREAM_USAGE_DTMF,
    rendererFlags : 0
  }
  tonePlayer = await audio.createTonePlayer(audioRendererInfo);
}

AudioVolumeType

Enumerates the audio stream types.

System capability: SystemCapability.Multimedia.Audio.Volume

NameValueDescription
VOICE_CALL8+0Audio stream for voice calls.
RINGTONE2Audio stream for ringtones.
MEDIA3Audio stream for media purpose.
ALARM10+4Audio stream for alarming.
ACCESSIBILITY10+5Audio stream for accessibility.
VOICE_ASSISTANT8+9Audio stream for voice assistant.
ULTRASONIC10+10Audio stream for ultrasonic.
This is a system API.
ALL9+100All public audio streams.
This is a system API.

InterruptRequestResultType9+

Enumerates the result types of audio interruption requests.

System capability: SystemCapability.Multimedia.Audio.Interrupt

System API: This is a system API.

NameValueDescription
INTERRUPT_REQUEST_GRANT0The audio interruption request is accepted.
INTERRUPT_REQUEST_REJECT1The audio interruption request is denied. There may be a stream with a higher priority.

InterruptMode9+

Enumerates the audio interruption modes.

System capability: SystemCapability.Multimedia.Audio.Interrupt

NameValueDescription
SHARE_MODE0Shared mode.
INDEPENDENT_MODE1Independent mode.

DeviceFlag

Enumerates the audio device flags.

System capability: SystemCapability.Multimedia.Audio.Device

NameValueDescription
NONE_DEVICES_FLAG9+0No device.
This is a system API.
OUTPUT_DEVICES_FLAG1Output device.
INPUT_DEVICES_FLAG2Input device.
ALL_DEVICES_FLAG3All devices.
DISTRIBUTED_OUTPUT_DEVICES_FLAG9+4Distributed output device.
This is a system API.
DISTRIBUTED_INPUT_DEVICES_FLAG9+8Distributed input device.
This is a system API.
ALL_DISTRIBUTED_DEVICES_FLAG9+12Distributed input and output device.
This is a system API.

DeviceRole

Enumerates the audio device roles.

System capability: SystemCapability.Multimedia.Audio.Device

NameValueDescription
INPUT_DEVICE1Input role.
OUTPUT_DEVICE2Output role.

DeviceType

Enumerates the audio device types.

System capability: SystemCapability.Multimedia.Audio.Device

NameValueDescription
INVALID0Invalid device.
EARPIECE1Earpiece.
SPEAKER2Speaker.
WIRED_HEADSET3Wired headset with a microphone.
WIRED_HEADPHONES4Wired headset without microphone.
BLUETOOTH_SCO7Bluetooth device using Synchronous Connection Oriented (SCO) links.
BLUETOOTH_A2DP8Bluetooth device using Advanced Audio Distribution Profile (A2DP) links.
MIC15Microphone.
USB_HEADSET22USB Type-C headset.
DEFAULT9+1000Default device type.

CommunicationDeviceType9+

Enumerates the device types used for communication.

System capability: SystemCapability.Multimedia.Audio.Communication

NameValueDescription
SPEAKER2Speaker.

AudioRingMode

Enumerates the ringer modes.

System capability: SystemCapability.Multimedia.Audio.Communication

NameValueDescription
RINGER_MODE_SILENT0Silent mode.
RINGER_MODE_VIBRATE1Vibration mode.
RINGER_MODE_NORMAL2Normal mode.

AudioSampleFormat8+

Enumerates the audio sample formats.

System capability: SystemCapability.Multimedia.Audio.Core

NameValueDescription
SAMPLE_FORMAT_INVALID-1Invalid format.
SAMPLE_FORMAT_U80Unsigned 8-bit integer.
SAMPLE_FORMAT_S16LE1Signed 16-bit integer, little endian.
SAMPLE_FORMAT_S24LE2Signed 24-bit integer, little endian.
Due to system restrictions, only some devices support this sampling format.
SAMPLE_FORMAT_S32LE3Signed 32-bit integer, little endian.
Due to system restrictions, only some devices support this sampling format.
SAMPLE_FORMAT_F32LE9+4Signed 32-bit floating point number, little endian.
Due to system restrictions, only some devices support this sampling format.

AudioErrors9+

Enumerates the audio error codes.

System capability: SystemCapability.Multimedia.Audio.Core

NameValueDescription
ERROR_INVALID_PARAM6800101Invalid parameter.
ERROR_NO_MEMORY6800102Memory allocation failure.
ERROR_ILLEGAL_STATE6800103Unsupported state.
ERROR_UNSUPPORTED6800104Unsupported parameter value.
ERROR_TIMEOUT6800105Processing timeout.
ERROR_STREAM_LIMIT6800201Too many audio streams.
ERROR_SYSTEM6800301System error.

AudioChannel8+

Enumerates the audio channels.

System capability: SystemCapability.Multimedia.Audio.Core

NameValueDescription
CHANNEL_10x1 << 0Channel 1.
CHANNEL_20x1 << 1Channel 2.

AudioSamplingRate8+

Enumerates the audio sampling rates. The sampling rates supported vary according to the device in use.

System capability: SystemCapability.Multimedia.Audio.Core

NameValueDescription
SAMPLE_RATE_80008000The sampling rate is 8000.
SAMPLE_RATE_1102511025The sampling rate is 11025.
SAMPLE_RATE_1200012000The sampling rate is 12000.
SAMPLE_RATE_1600016000The sampling rate is 16000.
SAMPLE_RATE_2205022050The sampling rate is 22050.
SAMPLE_RATE_2400024000The sampling rate is 24000.
SAMPLE_RATE_3200032000The sampling rate is 32000.
SAMPLE_RATE_4410044100The sampling rate is 44100.
SAMPLE_RATE_4800048000The sampling rate is 48000.
SAMPLE_RATE_6400064000The sampling rate is 64000.
SAMPLE_RATE_9600096000The sampling rate is 96000.

AudioEncodingType8+

Enumerates the audio encoding types.

System capability: SystemCapability.Multimedia.Audio.Core

NameValueDescription
ENCODING_TYPE_INVALID-1Invalid.
ENCODING_TYPE_RAW0PCM encoding.

ContentType

Enumerates the audio content types.

System capability: SystemCapability.Multimedia.Audio.Core

NameValueDescription
CONTENT_TYPE_UNKNOWN0Unknown content.
CONTENT_TYPE_SPEECH1Speech.
CONTENT_TYPE_MUSIC2Music.
CONTENT_TYPE_MOVIE3Movie.
CONTENT_TYPE_SONIFICATION4Notification tone.
CONTENT_TYPE_RINGTONE8+5Ringtone.

StreamUsage

Enumerates the audio stream usage.

System capability: SystemCapability.Multimedia.Audio.Core

NameValueDescription
STREAM_USAGE_UNKNOWN0Unknown usage.
STREAM_USAGE_MEDIA1Media.
STREAM_USAGE_MUSIC10+1Music.
STREAM_USAGE_VOICE_COMMUNICATION2Voice communication.
STREAM_USAGE_VOICE_ASSISTANT9+3Voice assistant.
STREAM_USAGE_ALARM10+4Alarming.
STREAM_USAGE_VOICE_MESSAGE10+5Voice message.
STREAM_USAGE_NOTIFICATION_RINGTONE6Notification tone.
STREAM_USAGE_RINGTONE10+6Ringtone.
STREAM_USAGE_NOTIFICATION10+7Notification.
STREAM_USAGE_ACCESSIBILITY10+8Accessibility.
STREAM_USAGE_SYSTEM10+9System tone (such as screen lock sound effect or key tone).
This is a system API.
STREAM_USAGE_MOVIE10+10Movie or video.
STREAM_USAGE_GAME10+11Game sound effect.
STREAM_USAGE_AUDIOBOOK10+12Audiobook.
STREAM_USAGE_NAVIGATION10+13Navigation.
STREAM_USAGE_DTMF10+14Dial tone.
This is a system API.
STREAM_USAGE_ENFORCED_TONE10+15Forcible tone (such as camera shutter sound effect).
This is a system API.
STREAM_USAGE_ULTRASONIC10+16Ultrasonic.
This is a system API.

InterruptRequestType9+

Enumerates the audio interruption request types.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Interrupt

NameValueDescription
INTERRUPT_REQUEST_TYPE_DEFAULT0Default type, which can be used to interrupt audio requests.

AudioState8+

Enumerates the audio states.

System capability: SystemCapability.Multimedia.Audio.Core

NameValueDescription
STATE_INVALID-1Invalid state.
STATE_NEW0Creating instance state.
STATE_PREPARED1Prepared.
STATE_RUNNING2Running.
STATE_STOPPED3Stopped.
STATE_RELEASED4Released.
STATE_PAUSED5Paused.

AudioEffectMode10+

Enumerates the audio effect modes.

System capability: SystemCapability.Multimedia.Audio.Renderer

NameValueDescription
EFFECT_NONE0The audio effect is disabled.
EFFECT_DEFAULT1The default audio effect is used.

AudioRendererRate8+

Enumerates the audio renderer rates.

System capability: SystemCapability.Multimedia.Audio.Renderer

NameValueDescription
RENDER_RATE_NORMAL0Normal rate.
RENDER_RATE_DOUBLE1Double rate.
RENDER_RATE_HALF2Half rate.

InterruptType

Enumerates the audio interruption types.

System capability: SystemCapability.Multimedia.Audio.Renderer

NameValueDescription
INTERRUPT_TYPE_BEGIN1Audio interruption started.
INTERRUPT_TYPE_END2Audio interruption ended.

InterruptForceType9+

Enumerates the types of force that causes audio interruption.

System capability: SystemCapability.Multimedia.Audio.Renderer

NameValueDescription
INTERRUPT_FORCE0Forced action taken by the system.
INTERRUPT_SHARE1The application can choose to take action or ignore.

InterruptHint

Enumerates the hints provided along with audio interruption.

System capability: SystemCapability.Multimedia.Audio.Renderer

NameValueDescription
INTERRUPT_HINT_NONE8+0None.
INTERRUPT_HINT_RESUME1Resume the playback.
INTERRUPT_HINT_PAUSE2Paused/Pause the playback.
INTERRUPT_HINT_STOP3Stopped/Stop the playback.
INTERRUPT_HINT_DUCK4Ducked the playback. (In ducking, the audio volume is reduced, but not silenced.)
INTERRUPT_HINT_UNDUCK8+5Unducked the playback.

AudioStreamInfo8+

Describes audio stream information.

System capability: SystemCapability.Multimedia.Audio.Core

NameTypeMandatoryDescription
samplingRateAudioSamplingRateYesAudio sampling rate.
channelsAudioChannelYesNumber of audio channels.
sampleFormatAudioSampleFormatYesAudio sample format.
encodingTypeAudioEncodingTypeYesAudio encoding type.

AudioRendererInfo8+

Describes audio renderer information.

System capability: SystemCapability.Multimedia.Audio.Core

NameTypeMandatoryDescription
contentContentTypeNoAudio content type.
This parameter is mandatory in API versions 8 and 9 and optional since API version 10.
usageStreamUsageYesAudio stream usage.
rendererFlagsnumberYesAudio renderer flags.
The value 0 means a common audio renderer, and 1 means a low-latency audio renderer. Currently, the JS APIs do not support the low-latency audio renderer.

InterruptResult9+

Describes the audio interruption result.

System capability: SystemCapability.Multimedia.Audio.Interrupt

System API: This is a system API.

NameTypeMandatoryDescription
requestResultInterruptRequestResultTypeYesAudio interruption request type.
interruptNodenumberYesNode to interrupt.

AudioRendererOptions8+

Describes audio renderer configurations.

NameTypeMandatoryDescription
streamInfoAudioStreamInfoYesAudio stream information.
System capability: SystemCapability.Multimedia.Audio.Renderer
rendererInfoAudioRendererInfoYesAudio renderer information.
System capability: SystemCapability.Multimedia.Audio.Renderer
privacyType10+AudioPrivacyTypeNoWhether the audio stream can be recorded by other applications. The default value is 0.
System capability: SystemCapability.Multimedia.Audio.PlaybackCapture

AudioPrivacyType10+

Enumerates whether an audio stream can be recorded by other applications.

System capability: SystemCapability.Multimedia.Audio.PlaybackCapture

NameValueDescription
PRIVACY_TYPE_PUBLIC0The audio stream can be recorded by other applications.
PRIVACY_TYPE_PRIVATE1The audio stream cannot be recorded by other applications.

InterruptEvent9+

Describes the interruption event received by the application when playback is interrupted.

System capability: SystemCapability.Multimedia.Audio.Renderer

NameTypeMandatoryDescription
eventTypeInterruptTypeYesWhether the interruption has started or ended.
forceTypeInterruptForceTypeYesWhether the interruption is taken by the system or to be taken by the application.
hintTypeInterruptHintYesHint provided along the interruption.

VolumeEvent9+

Describes the event received by the application when the volume is changed.

System capability: SystemCapability.Multimedia.Audio.Volume

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.
volumenumberYesVolume to set. The value range can be obtained by calling getMinVolume and getMaxVolume.
updateUibooleanYesWhether to show the volume change in UI.
volumeGroupIdnumberYesVolume group ID. It can be used as an input parameter of getGroupManager.
This is a system API.
networkIdstringYesNetwork ID.
This is a system API.

MicStateChangeEvent9+

Describes the event received by the application when the microphone mute status changes.

System capability: SystemCapability.Multimedia.Audio.Device

NameTypeMandatoryDescription
mutebooleanYesMute status of the microphone. The value true means that the microphone is muted, and false means the opposite.

ConnectType9+

Enumerates the types of connected devices.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Volume

NameValueDescription
CONNECT_TYPE_LOCAL1Local device.
CONNECT_TYPE_DISTRIBUTED2Distributed device.

VolumeGroupInfos9+

Describes the volume group information. The value is an array of VolumeGroupInfo and is read-only.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Volume

VolumeGroupInfo9+

Describes the volume group information.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Volume

NameTypeReadableWritableDescription
networkId9+stringYesNoNetwork ID of the device.
groupId9+numberYesNoGroup ID of the device.
mappingId9+numberYesNoGroup mapping ID.
groupName9+stringYesNoGroup name.
type9+ConnectTypeYesNoType of the connected device.

DeviceChangeAction

Describes the device connection status and device information.

System capability: SystemCapability.Multimedia.Audio.Device

NameTypeMandatoryDescription
typeDeviceChangeTypeYesDevice connection status.
deviceDescriptorsAudioDeviceDescriptorsYesDevice information.

ChannelBlendMode11+

Enumerates the audio channel blending modes.

System capability: SystemCapability.Multimedia.Audio.Core

NameValueDescription
MODE_DEFAULT11+0The audio channels are not blended.
MODE_BLEND_LR11+1The left and right audio channels are blended.
MODE_ALL_LEFT11+2The left channel is replicated into the right channel.
MODE_ALL_RIGHT11+3The right channel is replicated into the left channel.

DeviceChangeType

Enumerates the device connection statuses.

System capability: SystemCapability.Multimedia.Audio.Device

NameValueDescription
CONNECT0Connected.
DISCONNECT1Disconnected.

AudioCapturerOptions8+

Describes audio capturer configurations.

NameTypeMandatoryDescription
streamInfoAudioStreamInfoYesAudio stream information.
System capability: SystemCapability.Multimedia.Audio.Capturer
capturerInfoAudioCapturerInfoYesAudio capturer information.
System capability: SystemCapability.Multimedia.Audio.Capturer
playbackCaptureConfig10+AudioPlaybackCaptureConfigNoConfiguration of internal audio recording.
System capability: SystemCapability.Multimedia.Audio.PlaybackCapture

AudioCapturerInfo8+

Describes audio capturer information.

System capability: SystemCapability.Multimedia.Audio.Core

NameTypeMandatoryDescription
sourceSourceTypeYesAudio source type.
capturerFlagsnumberYesAudio capturer flags.

SourceType8+

Enumerates the audio source types.

NameValueDescription
SOURCE_TYPE_INVALID-1Invalid audio source.
System capability: SystemCapability.Multimedia.Audio.Core
SOURCE_TYPE_MIC0Mic source.
System capability: SystemCapability.Multimedia.Audio.Core
SOURCE_TYPE_VOICE_RECOGNITION9+1Voice recognition source.
System capability: SystemCapability.Multimedia.Audio.Core
SOURCE_TYPE_PLAYBACK_CAPTURE10+2Internal audio recording source.
System capability: SystemCapability.Multimedia.Audio.PlaybackCapture
SOURCE_TYPE_WAKEUP 10+3Audio recording source in voice wake-up scenarios.
System capability: SystemCapability.Multimedia.Audio.Core
Required permissions: ohos.permission.MANAGE_INTELLIGENT_VOICE
This is a system API.
SOURCE_TYPE_VOICE_COMMUNICATION7Voice communication source.
System capability: SystemCapability.Multimedia.Audio.Core

AudioPlaybackCaptureConfig10+

Defines the configuration of internal audio recording.

System capability: SystemCapability.Multimedia.Audio.PlaybackCapture

NameTypeMandatoryDescription
filterOptionsCaptureFilterOptionsYesOptions for filtering the played audio streams to be recorded.

CaptureFilterOptions10+

Defines the options for filtering the played audio streams to be recorded.

Required permissions: ohos.permission.CAPTURE_VOICE_DOWNLINK_AUDIO

This permission is required when an application wants to record a played audio stream for which StreamUsage is set to SOURCE_TYPE_VOICE_COMMUNICATION.

System capability: SystemCapability.Multimedia.Audio.PlaybackCapture

NameTypeMandatoryDescription
usagesArray<StreamUsage>YesStreamUsage of the audio stream to be recorded. You can specify zero or more stream usages. If the array is empty, the audio stream for which StreamUsage is STREAM_USAGE_MEDIA is recorded by default.

AudioScene8+

Enumerates the audio scenes.

System capability: SystemCapability.Multimedia.Audio.Communication

NameValueDescription
AUDIO_SCENE_DEFAULT0Default audio scene.
AUDIO_SCENE_RINGING1Ringing audio scene.
This is a system API.
AUDIO_SCENE_PHONE_CALL2Phone call audio scene.
This is a system API.
AUDIO_SCENE_VOICE_CHAT3Voice chat audio scene.

VolumeAdjustType10+

Enumerates the volume adjustment types.

System capability: SystemCapability.Multimedia.Audio.Volume

NameValueDescription
VOLUME_UP0Adjusts the volume upwards.
This is a system API.
VOLUME_DOWN1Adjusts the volume downwards.
This is a system API.

AudioManager

Implements audio volume and audio device management. Before calling any API in AudioManager, you must use getAudioManager to create an AudioManager instance.

setAudioParameter

setAudioParameter(key: string, value: string, callback: AsyncCallback<void>): void

Sets an audio parameter. This API uses an asynchronous callback to return the result.

This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only.

Required permissions: ohos.permission.MODIFY_AUDIO_SETTINGS

System capability: SystemCapability.Multimedia.Audio.Core

Parameters

NameTypeMandatoryDescription
keystringYesKey of the audio parameter to set.
valuestringYesValue of the audio parameter to set.
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioManager.setAudioParameter('key_example', 'value_example', (err: BusinessError) => {
  if (err) {
    console.error(`Failed to set the audio parameter. ${err}`);
    return;
  }
  console.info('Callback invoked to indicate a successful setting of the audio parameter.');
});

setAudioParameter

setAudioParameter(key: string, value: string): Promise<void>

Sets an audio parameter. This API uses a promise to return the result.

This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only.

Required permissions: ohos.permission.MODIFY_AUDIO_SETTINGS

System capability: SystemCapability.Multimedia.Audio.Core

Parameters

NameTypeMandatoryDescription
keystringYesKey of the audio parameter to set.
valuestringYesValue of the audio parameter to set.

Return value

TypeDescription
Promise<void>Promise used to return the result.

Example

audioManager.setAudioParameter('key_example', 'value_example').then(() => {
  console.info('Promise returned to indicate a successful setting of the audio parameter.');
});

getAudioParameter

getAudioParameter(key: string, callback: AsyncCallback<string>): void

Obtains the value of an audio parameter. This API uses an asynchronous callback to return the result.

This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only.

System capability: SystemCapability.Multimedia.Audio.Core

Parameters

NameTypeMandatoryDescription
keystringYesKey of the audio parameter whose value is to be obtained.
callbackAsyncCallback<string>YesCallback used to return the value of the audio parameter.

Example

import { BusinessError } from '@ohos.base';
audioManager.getAudioParameter('key_example', (err: BusinessError, value: string) => {
  if (err) {
    console.error(`Failed to obtain the value of the audio parameter. ${err}`);
    return;
  }
  console.info(`Callback invoked to indicate that the value of the audio parameter is obtained ${value}.`);
});

getAudioParameter

getAudioParameter(key: string): Promise<string>

Obtains the value of an audio parameter. This API uses a promise to return the result.

This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only.

System capability: SystemCapability.Multimedia.Audio.Core

Parameters

NameTypeMandatoryDescription
keystringYesKey of the audio parameter whose value is to be obtained.

Return value

TypeDescription
Promise<string>Promise used to return the value of the audio parameter.

Example

audioManager.getAudioParameter('key_example').then((value: string) => {
  console.info(`Promise returned to indicate that the value of the audio parameter is obtained ${value}.`);
});

setAudioScene8+

setAudioScene(scene: AudioScene, callback: AsyncCallback<void>): void

Sets an audio scene. This API uses an asynchronous callback to return the result.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Communication

Parameters

NameTypeMandatoryDescription
sceneAudioSceneYesAudio scene to set.
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL, (err: BusinessError) => {
  if (err) {
    console.error(`Failed to set the audio scene mode.​ ${err}`);
    return;
  }
  console.info('Callback invoked to indicate a successful setting of the audio scene mode.');
});

setAudioScene8+

setAudioScene(scene: AudioScene): Promise<void>

Sets an audio scene. This API uses a promise to return the result.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Communication

Parameters

NameTypeMandatoryDescription
sceneAudioSceneYesAudio scene to set.

Return value

TypeDescription
Promise<void>Promise used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL).then(() => {
  console.info('Promise returned to indicate a successful setting of the audio scene mode.');
}).catch ((err: BusinessError) => {
  console.error(`Failed to set the audio scene mode ${err}`);
});

getAudioScene8+

getAudioScene(callback: AsyncCallback<AudioScene>): void

Obtains the audio scene. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Communication

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<AudioScene>YesCallback used to return the audio scene.

Example

import { BusinessError } from '@ohos.base';
audioManager.getAudioScene((err: BusinessError, value: audio.AudioScene) => {
  if (err) {
    console.error(`Failed to obtain the audio scene mode.​ ${err}`);
    return;
  }
  console.info(`Callback invoked to indicate that the audio scene mode is obtained ${value}.`);
});

getAudioScene8+

getAudioScene(): Promise<AudioScene>

Obtains the audio scene. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Communication

Return value

TypeDescription
Promise<AudioScene>Promise used to return the audio scene.

Example

import { BusinessError } from '@ohos.base';
audioManager.getAudioScene().then((value: audio.AudioScene) => {
  console.info(`Promise returned to indicate that the audio scene mode is obtained ${value}.`);
}).catch ((err: BusinessError) => {
  console.error(`Failed to obtain the audio scene mode ${err}`);
});

getAudioSceneSync10+

getAudioSceneSync(): AudioScene

Obtains the audio scene. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Communication

Return value

TypeDescription
AudioSceneAudio scene.

Example

import { BusinessError } from '@ohos.base';

try {
  let value: audio.AudioScene = audioManager.getAudioSceneSync();
  console.info(`indicate that the audio scene mode is obtained ${value}.`);
} catch (err) {
  let error = err as BusinessError;
  console.error(`Failed to obtain the audio scene mode ${error}`);
}

getVolumeManager9+

getVolumeManager(): AudioVolumeManager

Obtains an AudioVolumeManager instance.

System capability: SystemCapability.Multimedia.Audio.Volume

Example

import audio from '@ohos.multimedia.audio';
let audioVolumeManager: audio.AudioVolumeManager = audioManager.getVolumeManager();

getStreamManager9+

getStreamManager(): AudioStreamManager

Obtains an AudioStreamManager instance.

System capability: SystemCapability.Multimedia.Audio.Core

Example

import audio from '@ohos.multimedia.audio';
let audioStreamManager: audio.AudioStreamManager = audioManager.getStreamManager();

getRoutingManager9+

getRoutingManager(): AudioRoutingManager

Obtains an AudioRoutingManager instance.

System capability: SystemCapability.Multimedia.Audio.Device

Example

import audio from '@ohos.multimedia.audio';
let audioRoutingManager: audio.AudioRoutingManager = audioManager.getRoutingManager();

setVolume(deprecated)

setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback<void>): void

Sets the volume for a stream. This API uses an asynchronous callback to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use setVolume in AudioVolumeGroupManager. The substitute API is available only for system applications.

Required permissions: ohos.permission.ACCESS_NOTIFICATION_POLICY

This permission is required only for muting or unmuting the ringer when volumeType is set to AudioVolumeType.RINGTONE.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.
volumenumberYesVolume to set. The value range can be obtained by calling getMinVolume and getMaxVolume.
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err: BusinessError) => {
  if (err) {
    console.error(`Failed to set the volume. ${err}`);
    return;
  }
  console.info('Callback invoked to indicate a successful volume setting.');
});

setVolume(deprecated)

setVolume(volumeType: AudioVolumeType, volume: number): Promise<void>

Sets the volume for a stream. This API uses a promise to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use setVolume in AudioVolumeGroupManager. The substitute API is available only for system applications.

Required permissions: ohos.permission.ACCESS_NOTIFICATION_POLICY

This permission is required only for muting or unmuting the ringer when volumeType is set to AudioVolumeType.RINGTONE.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.
volumenumberYesVolume to set. The value range can be obtained by calling getMinVolume and getMaxVolume.

Return value

TypeDescription
Promise<void>Promise used to return the result.

Example

audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => {
  console.info('Promise returned to indicate a successful volume setting.');
});

getVolume(deprecated)

getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void

Obtains the volume of a stream. This API uses an asynchronous callback to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use getVolume in AudioVolumeGroupManager.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.
callbackAsyncCallback<number>YesCallback used to return the volume.

Example

import { BusinessError } from '@ohos.base';
audioManager.getVolume(audio.AudioVolumeType.MEDIA, (err: BusinessError, value: number) => {
  if (err) {
    console.error(`Failed to obtain the volume. ${err}`);
    return;
  }
  console.info('Callback invoked to indicate that the volume is obtained.');
});

getVolume(deprecated)

getVolume(volumeType: AudioVolumeType): Promise<number>

Obtains the volume of a stream. This API uses a promise to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use getVolume in AudioVolumeGroupManager.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.

Return value

TypeDescription
Promise<number>Promise used to return the volume.

Example

audioManager.getVolume(audio.AudioVolumeType.MEDIA).then((value: number) => {
  console.info(`Promise returned to indicate that the volume is obtained ${value} .`);
});

getMinVolume(deprecated)

getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void

Obtains the minimum volume allowed for a stream. This API uses an asynchronous callback to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use getMinVolume in AudioVolumeGroupManager.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.
callbackAsyncCallback<number>YesCallback used to return the minimum volume.

Example

import { BusinessError } from '@ohos.base';
audioManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err: BusinessError, value: number) => {
  if (err) {
    console.error(`Failed to obtain the minimum volume. ${err}`);
    return;
  }
  console.info(`Callback invoked to indicate that the minimum volume is obtained. ${value}`);
});

getMinVolume(deprecated)

getMinVolume(volumeType: AudioVolumeType): Promise<number>

Obtains the minimum volume allowed for a stream. This API uses a promise to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use getMinVolume in AudioVolumeGroupManager.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.

Return value

TypeDescription
Promise<number>Promise used to return the minimum volume.

Example

audioManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value: number) => {
  console.info(`Promised returned to indicate that the minimum volume is obtained. ${value}`);
});

getMaxVolume(deprecated)

getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void

Obtains the maximum volume allowed for a stream. This API uses an asynchronous callback to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use getMaxVolume in AudioVolumeGroupManager.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.
callbackAsyncCallback<number>YesCallback used to return the maximum volume.

Example

import { BusinessError } from '@ohos.base';
audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err: BusinessError, value: number) => {
  if (err) {
    console.error(`Failed to obtain the maximum volume. ${err}`);
    return;
  }
  console.info(`Callback invoked to indicate that the maximum volume is obtained. ${value}`);
});

getMaxVolume(deprecated)

getMaxVolume(volumeType: AudioVolumeType): Promise<number>

Obtains the maximum volume allowed for a stream. This API uses a promise to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use getMaxVolume in AudioVolumeGroupManager.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.

Return value

TypeDescription
Promise<number>Promise used to return the maximum volume.

Example

audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data: number) => {
  console.info('Promised returned to indicate that the maximum volume is obtained.');
});

mute(deprecated)

mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void>): void

Mutes or unmutes a stream. This API uses an asynchronous callback to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use mute in AudioVolumeGroupManager. The substitute API is available only for system applications.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.
mutebooleanYesMute status to set. The value true means to mute the stream, and false means the opposite.
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioManager.mute(audio.AudioVolumeType.MEDIA, true, (err: BusinessError) => {
  if (err) {
    console.error(`Failed to mute the stream. ${err}`);
    return;
  }
  console.info('Callback invoked to indicate that the stream is muted.');
});

mute(deprecated)

mute(volumeType: AudioVolumeType, mute: boolean): Promise<void>

Mutes or unmutes a stream. This API uses a promise to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use mute in AudioVolumeGroupManager. The substitute API is available only for system applications.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.
mutebooleanYesMute status to set. The value true means to mute the stream, and false means the opposite.

Return value

TypeDescription
Promise<void>Promise used to return the result.

Example

audioManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => {
  console.info('Promise returned to indicate that the stream is muted.');
});

isMute(deprecated)

isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void

Checks whether a stream is muted. This API uses an asynchronous callback to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use isMute in AudioVolumeGroupManager.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.
callbackAsyncCallback<boolean>YesCallback used to return the mute status of the stream. The value true means that the stream is muted, and false means the opposite.

Example

import { BusinessError } from '@ohos.base';
audioManager.isMute(audio.AudioVolumeType.MEDIA, (err: BusinessError, value: boolean) => {
  if (err) {
    console.error(`Failed to obtain the mute status. ${err}`);
    return;
  }
  console.info(`Callback invoked to indicate that the mute status of the stream is obtained. ${value}`);
});

isMute(deprecated)

isMute(volumeType: AudioVolumeType): Promise<boolean>

Checks whether a stream is muted. This API uses a promise to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use isMute in AudioVolumeGroupManager.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.

Return value

TypeDescription
Promise<boolean>Promise used to return the mute status of the stream. The value true means that the stream is muted, and false means the opposite.

Example

audioManager.isMute(audio.AudioVolumeType.MEDIA).then((value: boolean) => {
  console.info(`Promise returned to indicate that the mute status of the stream is obtained ${value}.`);
});

isActive(deprecated)

isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void

Checks whether a stream is active. This API uses an asynchronous callback to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use isActive in AudioStreamManager.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.
callbackAsyncCallback<boolean>YesCallback used to return the active status of the stream. The value true means that the stream is active, and false means the opposite.

Example

import { BusinessError } from '@ohos.base';
audioManager.isActive(audio.AudioVolumeType.MEDIA, (err: BusinessError, value: boolean) => {
  if (err) {
    console.error(`Failed to obtain the active status of the stream. ${err}`);
    return;
  }
  console.info(`Callback invoked to indicate that the active status of the stream is obtained ${value}.`);
});

isActive(deprecated)

isActive(volumeType: AudioVolumeType): Promise<boolean>

Checks whether a stream is active. This API uses a promise to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use isActive in AudioStreamManager.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.

Return value

TypeDescription
Promise<boolean>Promise used to return the active status of the stream. The value true means that the stream is active, and false means the opposite.

Example

audioManager.isActive(audio.AudioVolumeType.MEDIA).then((value: boolean) => {
  console.info(`Promise returned to indicate that the active status of the stream is obtained ${value}.`);
});

setRingerMode(deprecated)

setRingerMode(mode: AudioRingMode, callback: AsyncCallback<void>): void

Sets the ringer mode. This API uses an asynchronous callback to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use setRingerMode in AudioVolumeGroupManager. The substitute API is available only for system applications.

Required permissions: ohos.permission.ACCESS_NOTIFICATION_POLICY

This permission is required only for muting or unmuting the ringer.

System capability: SystemCapability.Multimedia.Audio.Communication

Parameters

NameTypeMandatoryDescription
modeAudioRingModeYesRinger mode.
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err: BusinessError) => {
  if (err) {
    console.error(`Failed to set the ringer mode.​ ${err}`);
    return;
  }
  console.info('Callback invoked to indicate a successful setting of the ringer mode.');
});

setRingerMode(deprecated)

setRingerMode(mode: AudioRingMode): Promise<void>

Sets the ringer mode. This API uses a promise to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use setRingerMode in AudioVolumeGroupManager. The substitute API is available only for system applications.

Required permissions: ohos.permission.ACCESS_NOTIFICATION_POLICY

This permission is required only for muting or unmuting the ringer.

System capability: SystemCapability.Multimedia.Audio.Communication

Parameters

NameTypeMandatoryDescription
modeAudioRingModeYesRinger mode.

Return value

TypeDescription
Promise<void>Promise used to return the result.

Example

audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => {
  console.info('Promise returned to indicate a successful setting of the ringer mode.');
});

getRingerMode(deprecated)

getRingerMode(callback: AsyncCallback<AudioRingMode>): void

Obtains the ringer mode. This API uses an asynchronous callback to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use getRingerMode in AudioVolumeGroupManager.

System capability: SystemCapability.Multimedia.Audio.Communication

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<AudioRingMode>YesCallback used to return the ringer mode.

Example

import { BusinessError } from '@ohos.base';
audioManager.getRingerMode((err: BusinessError, value: audio.AudioRingMode) => {
  if (err) {
    console.error(`Failed to obtain the ringer mode.​ ${err}`);
    return;
  }
  console.info(`Callback invoked to indicate that the ringer mode is obtained ${value}.`);
});

getRingerMode(deprecated)

getRingerMode(): Promise<AudioRingMode>

Obtains the ringer mode. This API uses a promise to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use getRingerMode in AudioVolumeGroupManager.

System capability: SystemCapability.Multimedia.Audio.Communication

Return value

TypeDescription
Promise<AudioRingMode>Promise used to return the ringer mode.

Example

audioManager.getRingerMode().then((value: audio.AudioRingMode) => {
  console.info(`Promise returned to indicate that the ringer mode is obtained ${value}.`);
});

getDevices(deprecated)

getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void

Obtains the audio devices with a specific flag. This API uses an asynchronous callback to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use getDevices in AudioRoutingManager.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
deviceFlagDeviceFlagYesAudio device flag.
callbackAsyncCallback<AudioDeviceDescriptors>YesCallback used to return the device list.

Example

import { BusinessError } from '@ohos.base';
audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err: BusinessError, value: audio.AudioDeviceDescriptors) => {
  if (err) {
    console.error(`Failed to obtain the device list. ${err}`);
    return;
  }
  console.info('Callback invoked to indicate that the device list is obtained.');
});

getDevices(deprecated)

getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors>

Obtains the audio devices with a specific flag. This API uses a promise to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use getDevices in AudioRoutingManager.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
deviceFlagDeviceFlagYesAudio device flag.

Return value

TypeDescription
Promise<AudioDeviceDescriptors>Promise used to return the device list.

Example

audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data: audio.AudioDeviceDescriptors) => {
  console.info('Promise returned to indicate that the device list is obtained.');
});

setDeviceActive(deprecated)

setDeviceActive(deviceType: ActiveDeviceType, active: boolean, callback: AsyncCallback<void>): void

Sets a device to the active state. This API uses an asynchronous callback to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use setCommunicationDevice in AudioRoutingManager.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
deviceTypeActiveDeviceTypeYesActive audio device type.
activebooleanYesActive state to set. The value true means to set the device to the active state, and false means the opposite.
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true, (err: BusinessError) => {
  if (err) {
    console.error(`Failed to set the active status of the device. ${err}`);
    return;
  }
  console.info('Callback invoked to indicate that the device is set to the active status.');
});

setDeviceActive(deprecated)

setDeviceActive(deviceType: ActiveDeviceType, active: boolean): Promise<void>

Sets a device to the active state. This API uses a promise to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use setCommunicationDevice in AudioRoutingManager.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
deviceTypeActiveDeviceTypeYesActive audio device type.
activebooleanYesActive state to set. The value true means to set the device to the active state, and false means the opposite.

Return value

TypeDescription
Promise<void>Promise used to return the result.

Example

audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true).then(() => {
  console.info('Promise returned to indicate that the device is set to the active status.');
});

isDeviceActive(deprecated)

isDeviceActive(deviceType: ActiveDeviceType, callback: AsyncCallback<boolean>): void

Checks whether a device is active. This API uses an asynchronous callback to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use isCommunicationDeviceActive in AudioRoutingManager.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
deviceTypeActiveDeviceTypeYesActive audio device type.
callbackAsyncCallback<boolean>YesCallback used to return the active state of the device.

Example

import { BusinessError } from '@ohos.base';
audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER, (err: BusinessError, value: boolean) => {
  if (err) {
    console.error(`Failed to obtain the active status of the device. ${err}`);
    return;
  }
  console.info('Callback invoked to indicate that the active status of the device is obtained.');
});

isDeviceActive(deprecated)

isDeviceActive(deviceType: ActiveDeviceType): Promise<boolean>

Checks whether a device is active. This API uses a promise to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use isCommunicationDeviceActive in AudioRoutingManager.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
deviceTypeActiveDeviceTypeYesActive audio device type.

Return value

TypeDescription
Promise<boolean>Promise used to return the active state of the device.

Example

audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER).then((value: boolean) => {
  console.info(`Promise returned to indicate that the active status of the device is obtained ${value}.`);
});

setMicrophoneMute(deprecated)

setMicrophoneMute(mute: boolean, callback: AsyncCallback<void>): void

Mutes or unmutes the microphone. This API uses an asynchronous callback to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use setMicrophoneMute in AudioVolumeGroupManager.

Required permissions: ohos.permission.MICROPHONE

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
mutebooleanYesMute status to set. The value true means to mute the microphone, and false means the opposite.
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioManager.setMicrophoneMute(true, (err: BusinessError) => {
  if (err) {
    console.error(`Failed to mute the microphone. ${err}`);
    return;
  }
  console.info('Callback invoked to indicate that the microphone is muted.');
});

setMicrophoneMute(deprecated)

setMicrophoneMute(mute: boolean): Promise<void>

Mutes or unmutes the microphone. This API uses a promise to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use setMicrophoneMute in AudioVolumeGroupManager.

Required permissions: ohos.permission.MICROPHONE

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
mutebooleanYesMute status to set. The value true means to mute the microphone, and false means the opposite.

Return value

TypeDescription
Promise<void>Promise used to return the result.

Example

audioManager.setMicrophoneMute(true).then(() => {
  console.info('Promise returned to indicate that the microphone is muted.');
});

isMicrophoneMute(deprecated)

isMicrophoneMute(callback: AsyncCallback<boolean>): void

Checks whether the microphone is muted. This API uses an asynchronous callback to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use isMicrophoneMute in AudioVolumeGroupManager.

Required permissions: ohos.permission.MICROPHONE

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<boolean>YesCallback used to return the mute status of the microphone. The value true means that the microphone is muted, and false means the opposite.

Example

import { BusinessError } from '@ohos.base';
audioManager.isMicrophoneMute((err: BusinessError, value: boolean) => {
  if (err) {
    console.error(`Failed to obtain the mute status of the microphone. ${err}`);
    return;
  }
  console.info(`Callback invoked to indicate that the mute status of the microphone is obtained ${value}.`);
});

isMicrophoneMute(deprecated)

isMicrophoneMute(): Promise<boolean>

Checks whether the microphone is muted. This API uses a promise to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use isMicrophoneMute in AudioVolumeGroupManager.

Required permissions: ohos.permission.MICROPHONE

System capability: SystemCapability.Multimedia.Audio.Device

Return value

TypeDescription
Promise<boolean>Promise used to return the mute status of the microphone. The value true means that the microphone is muted, and false means the opposite.

Example

audioManager.isMicrophoneMute().then((value: boolean) => {
  console.info(`Promise returned to indicate that the mute status of the microphone is obtained ${value}.`);
});

on('volumeChange')(deprecated)

on(type: 'volumeChange', callback: Callback<VolumeEvent>): void

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use on('volumeChange') in AudioVolumeManager.

Subscribes to system volume change events.

System API: This is a system API.

Currently, when multiple AudioManager instances are used in a single process, only the subscription of the last instance takes effect, and the subscription of other instances is overwritten (even if the last instance does not initiate a subscription). Therefore, you are advised to use a single AudioManager instance.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The event 'volumeChange' is triggered when the system volume is changed.
callbackCallback<VolumeEvent>YesCallback used to return the result.

Example

audioManager.on('volumeChange', (volumeEvent: audio.VolumeEvent) => {
  console.info(`VolumeType of stream: ${volumeEvent.volumeType} `);
  console.info(`Volume level: ${volumeEvent.volume} `);
  console.info(`Whether to updateUI: ${volumeEvent.updateUi} `);
});

on('ringerModeChange')(deprecated)

on(type: 'ringerModeChange', callback: Callback<AudioRingMode>): void

Subscribes to ringer mode change events.

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use on('ringerModeChange') in AudioVolumeGroupManager.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Communication

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The event 'ringerModeChange' is triggered when the ringer mode is changed.
callbackCallback<AudioRingMode>YesCallback used to return the result.

Example

audioManager.on('ringerModeChange', (ringerMode: audio.AudioRingMode) => {
  console.info(`Updated ringermode: ${ringerMode}`);
});

on('deviceChange')(deprecated)

on(type: 'deviceChange', callback: Callback<DeviceChangeAction>): void

Subscribes to device change events. When a device is connected or disconnected, registered clients will receive the callback.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use on('deviceChange') in AudioRoutingManager.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The event 'deviceChange' is triggered when the device connection status is changed.
callbackCallback<DeviceChangeAction>YesCallback used to return the device update details.

Example

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 : ${deviceChanged.deviceDescriptors[0].deviceRole} `);
  console.info(`device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceType} `);
});

off('deviceChange')(deprecated)

off(type: 'deviceChange', callback?: Callback<DeviceChangeAction>): void

Unsubscribes from device change events.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use off('deviceChange') in AudioRoutingManager.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The event 'deviceChange' is triggered when the device connection status is changed.
callbackCallback<DeviceChangeAction>NoCallback used to return the device update details.

Example

audioManager.off('deviceChange');

on('interrupt')

on(type: 'interrupt', interrupt: AudioInterrupt, callback: Callback<InterruptAction>): void

Subscribes to audio interruption events. When the application's audio is interrupted by another playback event, the application will receive the callback.

Same as on('audioInterrupt'), this API is used to listen for focus changes. However, this API is used in scenarios without audio streams (no AudioRenderer instance is created), such as frequency modulation (FM) and voice wakeup.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The event 'interrupt' is triggered when the audio playback of the current application is interrupted by another application.
interruptAudioInterruptYesAudio interruption event type.
callbackCallback<InterruptAction>YesCallback invoked for the audio interruption event.

Example

import audio from '@ohos.multimedia.audio';
let interAudioInterrupt: audio.AudioInterrupt = {
  streamUsage:2,
  contentType:0,
  pauseWhenDucked:true
};
audioManager.on('interrupt', interAudioInterrupt, (InterruptAction: audio.InterruptAction) => {
  if (InterruptAction.actionType === 0) {
    console.info('An event to gain the audio focus starts.');
    console.info(`Focus gain event: ${InterruptAction} `);
  }
  if (InterruptAction.actionType === 1) {
    console.info('An audio interruption event starts.');
    console.info(`Audio interruption event: ${InterruptAction} `);
  }
});

off('interrupt')

off(type: 'interrupt', interrupt: AudioInterrupt, callback?: Callback<InterruptAction>): void

Unsubscribes from audio interruption events.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The event 'interrupt' is triggered when the audio playback of the current application is interrupted by another application.
interruptAudioInterruptYesAudio interruption event type.
callbackCallback<InterruptAction>NoCallback invoked for the audio interruption event.

Example

import audio from '@ohos.multimedia.audio';
let interAudioInterrupt: audio.AudioInterrupt = {
  streamUsage:2,
  contentType:0,
  pauseWhenDucked:true
};
audioManager.off('interrupt', interAudioInterrupt, (InterruptAction: audio.InterruptAction) => {
  if (InterruptAction.actionType === 0) {
    console.info('An event to release the audio focus starts.');
    console.info(`Focus release event: ${InterruptAction} `);
  }
});

AudioVolumeManager9+

Implements audio volume management. Before calling an API in AudioVolumeManager, you must use getVolumeManager to obtain an AudioVolumeManager instance.

getVolumeGroupInfos9+

getVolumeGroupInfos(networkId: string, callback: AsyncCallback<VolumeGroupInfos>): void

Obtains the volume groups. This API uses an asynchronous callback to return the result.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
networkIdstringYesNetwork ID of the device. The network ID of the local device is audio.LOCAL_NETWORK_ID.
callbackAsyncCallback<VolumeGroupInfos>YesCallback used to return the volume group information array.

Example

import { BusinessError } from '@ohos.base';
audioVolumeManager.getVolumeGroupInfos(audio.LOCAL_NETWORK_ID, (err: BusinessError, value: audio.VolumeGroupInfos) => {
  if (err) {
    console.error(`Failed to obtain the volume group infos list. ${err}`);
    return;
  }
  console.info('Callback invoked to indicate that the volume group infos list is obtained.');
});

getVolumeGroupInfos9+

getVolumeGroupInfos(networkId: string): Promise<VolumeGroupInfos>

Obtains the volume groups. This API uses a promise to return the result.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
networkIdstringYesNetwork ID of the device. The network ID of the local device is audio.LOCAL_NETWORK_ID.

Return value

TypeDescription
Promise<VolumeGroupInfos>Volume group information array.

Example

async function getVolumeGroupInfos(){
  let volumegroupinfos: audio.VolumeGroupInfos = await audio.getAudioManager().getVolumeManager().getVolumeGroupInfos(audio.LOCAL_NETWORK_ID);
  console.info('Promise returned to indicate that the volumeGroup list is obtained.'+JSON.stringify(volumegroupinfos))
}

getVolumeGroupInfosSync10+

getVolumeGroupInfosSync(networkId: string): VolumeGroupInfos

Obtains the volume groups. This API returns the result synchronously.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
networkIdstringYesNetwork ID of the device. The network ID of the local device is audio.LOCAL_NETWORK_ID.

Return value

TypeDescription
VolumeGroupInfosVolume group information array.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101invalid parameter error

Example

import { BusinessError } from '@ohos.base';

try {
  let volumegroupinfos: audio.VolumeGroupInfos = audioVolumeManager.getVolumeGroupInfosSync(audio.LOCAL_NETWORK_ID);
  console.info(`Indicate that the volumeGroup list is obtained. ${JSON.stringify(volumegroupinfos)}`);
} catch (err) {
  let error = err as BusinessError;
  console.error(`Failed to obtain the volumeGroup list ${error}`);
}

getVolumeGroupManager9+

getVolumeGroupManager(groupId: number, callback: AsyncCallback<AudioVolumeGroupManager>): void

Obtains the volume group manager. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
groupIdnumberYesVolume group ID.
callbackAsyncCallback<AudioVolumeGroupManager>YesCallback used to return the volume group manager.

Example

import { BusinessError } from '@ohos.base';
let groupid: number = audio.DEFAULT_VOLUME_GROUP_ID;
audioVolumeManager.getVolumeGroupManager(groupid, (err: BusinessError, value: audio.AudioVolumeGroupManager) => {
  if (err) {
    console.error(`Failed to obtain the volume group infos list. ${err}`);
    return;
  }
  console.info('Callback invoked to indicate that the volume group infos list is obtained.');
});

getVolumeGroupManager9+

getVolumeGroupManager(groupId: number): Promise<AudioVolumeGroupManager>

Obtains the volume group manager. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
groupIdnumberYesVolume group ID.

Return value

TypeDescription
Promise< AudioVolumeGroupManager >Promise used to return the volume group manager.

Example

import audio from '@ohos.multimedia.audio';
let groupid: number = audio.DEFAULT_VOLUME_GROUP_ID;
let audioVolumeGroupManager: audio.AudioVolumeGroupManager|undefined = undefined;
async function getVolumeGroupManager(){
  audioVolumeGroupManager = await audioVolumeManager.getVolumeGroupManager(groupid);
  console.info('Callback invoked to indicate that the volume group infos list is obtained.');
}

getVolumeGroupManagerSync10+

getVolumeGroupManagerSync(groupId: number): AudioVolumeGroupManager

Obtains the volume group manager. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
groupIdnumberYesVolume group ID.

Return value

TypeDescription
AudioVolumeGroupManagerVolume group manager.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101invalid parameter error

Example

import { BusinessError } from '@ohos.base';

try {
  let audioVolumeGroupManager: audio.AudioVolumeGroupManager = audioVolumeManager.getVolumeGroupManagerSync(audio.DEFAULT_VOLUME_GROUP_ID);
  console.info(`Get audioVolumeGroupManager success.`);
} catch (err) {
  let error = err as BusinessError;
  console.error(`Failed to get audioVolumeGroupManager, error: ${error}`);
}

on('volumeChange')9+

on(type: 'volumeChange', callback: Callback<VolumeEvent>): void

Subscribes to system volume change events. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The event 'volumeChange' is triggered when the system volume is changed.
callbackCallback<VolumeEvent>YesCallback used to return the result.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101if input parameter value error

Example

audioVolumeManager.on('volumeChange', (volumeEvent: audio.VolumeEvent) => {
  console.info(`VolumeType of stream: ${volumeEvent.volumeType} `);
  console.info(`Volume level: ${volumeEvent.volume} `);
  console.info(`Whether to updateUI: ${volumeEvent.updateUi} `);
});

AudioVolumeGroupManager9+

Manages the volume of an audio group. Before calling any API in AudioVolumeGroupManager, you must use getVolumeGroupManager to obtain an AudioVolumeGroupManager instance.

setVolume9+

setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback<void>): void

Sets the volume for a stream. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.ACCESS_NOTIFICATION_POLICY

This permission is required only for muting or unmuting the ringer when volumeType is set to AudioVolumeType.RINGTONE.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.
volumenumberYesVolume to set. The value range can be obtained by calling getMinVolume and getMaxVolume.
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioVolumeGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err: BusinessError) => {
  if (err) {
    console.error(`Failed to set the volume. ${err}`);
    return;
  }
  console.info('Callback invoked to indicate a successful volume setting.');
});

setVolume9+

setVolume(volumeType: AudioVolumeType, volume: number): Promise<void>

Sets the volume for a stream. This API uses a promise to return the result.

Required permissions: ohos.permission.ACCESS_NOTIFICATION_POLICY

This permission is required only for muting or unmuting the ringer when volumeType is set to AudioVolumeType.RINGTONE.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.
volumenumberYesVolume to set. The value range can be obtained by calling getMinVolume and getMaxVolume.

Return value

TypeDescription
Promise<void>Promise used to return the result.

Example

audioVolumeGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => {
  console.info('Promise returned to indicate a successful volume setting.');
});

getVolume9+

getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void

Obtains the volume of a stream. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.
callbackAsyncCallback<number>YesCallback used to return the volume.

Example

import { BusinessError } from '@ohos.base';
audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA, (err: BusinessError, value: number) => {
  if (err) {
    console.error(`Failed to obtain the volume. ${err}`);
    return;
  }
  console.info('Callback invoked to indicate that the volume is obtained.');
});

getVolume9+

getVolume(volumeType: AudioVolumeType): Promise<number>

Obtains the volume of a stream. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.

Return value

TypeDescription
Promise<number>Promise used to return the volume.

Example

audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA).then((value: number) => {
  console.info(`Promise returned to indicate that the volume is obtained ${value}.`);
});

getVolumeSync10+

getVolumeSync(volumeType: AudioVolumeType): number;

Obtains the volume of a stream. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.

Return value

TypeDescription
numberVolume of the stream.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101invalid parameter error

Example

import { BusinessError } from '@ohos.base';

try {
  let value: number = audioVolumeGroupManager.getVolumeSync(audio.AudioVolumeType.MEDIA);
  console.info(`Indicate that the volume is obtained ${value}.`);
} catch (err) {
  let error = err as BusinessError;
  console.info(`Failed to obtain the volume, error ${error}.`);
}

getMinVolume9+

getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void

Obtains the minimum volume allowed for a stream. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.
callbackAsyncCallback<number>YesCallback used to return the minimum volume.

Example

import { BusinessError } from '@ohos.base';
audioVolumeGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err: BusinessError, value: number) => {
  if (err) {
    console.error(`Failed to obtain the minimum volume. ${err}`);
    return;
  }
  console.info(`Callback invoked to indicate that the minimum volume is obtained. ${value}`);
});

getMinVolume9+

getMinVolume(volumeType: AudioVolumeType): Promise<number>

Obtains the minimum volume allowed for a stream. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.

Return value

TypeDescription
Promise<number>Promise used to return the minimum volume.

Example

audioVolumeGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value: number) => {
  console.info(`Promised returned to indicate that the minimum volume is obtained ${value}.`);
});

getMinVolumeSync10+

getMinVolumeSync(volumeType: AudioVolumeType): number;

Obtains the minimum volume allowed for a stream. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.

Return value

TypeDescription
numberMinimum volume.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101invalid parameter error

Example

import { BusinessError } from '@ohos.base';

try {
  let value: number = audioVolumeGroupManager.getMinVolumeSync(audio.AudioVolumeType.MEDIA);
  console.info(`Indicate that the minimum volume is obtained ${value}.`);
} catch (err) {
  let error = err as BusinessError;
  console.error(`Failed to obtain the minimum volume, error ${error}.`);
}

getMaxVolume9+

getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void

Obtains the maximum volume allowed for a stream. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.
callbackAsyncCallback<number>YesCallback used to return the maximum volume.

Example

import { BusinessError } from '@ohos.base';
audioVolumeGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err: BusinessError, value: number) => {
  if (err) {
    console.error(`Failed to obtain the maximum volume. ${err}`);
    return;
  }
  console.info(`Callback invoked to indicate that the maximum volume is obtained. ${value}`);
});

getMaxVolume9+

getMaxVolume(volumeType: AudioVolumeType): Promise<number>

Obtains the maximum volume allowed for a stream. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.

Return value

TypeDescription
Promise<number>Promise used to return the maximum volume.

Example

audioVolumeGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data: number) => {
  console.info('Promised returned to indicate that the maximum volume is obtained.');
});

getMaxVolumeSync10+

getMaxVolumeSync(volumeType: AudioVolumeType): number;

Obtains the maximum volume allowed for a stream. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.

Return value

TypeDescription
numberMaximum volume.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101invalid parameter error

Example

import { BusinessError } from '@ohos.base';

try {
  let value: number = audioVolumeGroupManager.getMaxVolumeSync(audio.AudioVolumeType.MEDIA);
  console.info(`Indicate that the maximum volume is obtained. ${value}`);
} catch (err) {
  let error = err as BusinessError;
  console.error(`Failed to obtain the maximum volume, error ${error}.`);
}

mute9+

mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void>): void

Mutes or unmutes a stream. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.ACCESS_NOTIFICATION_POLICY

This permission is required only for muting or unmuting the ringer when volumeType is set to AudioVolumeType.RINGTONE.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.
mutebooleanYesMute status to set. The value true means to mute the stream, and false means the opposite.
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioVolumeGroupManager.mute(audio.AudioVolumeType.MEDIA, true, (err: BusinessError) => {
  if (err) {
    console.error(`Failed to mute the stream. ${err}`);
    return;
  }
  console.info('Callback invoked to indicate that the stream is muted.');
});

mute9+

mute(volumeType: AudioVolumeType, mute: boolean): Promise<void>

Mutes or unmutes a stream. This API uses a promise to return the result.

Required permissions: ohos.permission.ACCESS_NOTIFICATION_POLICY

This permission is required only for muting or unmuting the ringer when volumeType is set to AudioVolumeType.RINGTONE.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.
mutebooleanYesMute status to set. The value true means to mute the stream, and false means the opposite.

Return value

TypeDescription
Promise<void>Promise used to return the result.

Example

audioVolumeGroupManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => {
  console.info('Promise returned to indicate that the stream is muted.');
});

isMute9+

isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void

Checks whether a stream is muted. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.
callbackAsyncCallback<boolean>YesCallback used to return the mute status of the stream. The value true means that the stream is muted, and false means the opposite.

Example

import { BusinessError } from '@ohos.base';
audioVolumeGroupManager.isMute(audio.AudioVolumeType.MEDIA, (err: BusinessError, value: boolean) => {
  if (err) {
    console.error(`Failed to obtain the mute status. ${err}`);
    return;
  }
  console.info(`Callback invoked to indicate that the mute status of the stream is obtained ${value}.`);
});

isMute9+

isMute(volumeType: AudioVolumeType): Promise<boolean>

Checks whether a stream is muted. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.

Return value

TypeDescription
Promise<boolean>Promise used to return the mute status of the stream. The value true means that the stream is muted, and false means the opposite.

Example

audioVolumeGroupManager.isMute(audio.AudioVolumeType.MEDIA).then((value: boolean) => {
  console.info(`Promise returned to indicate that the mute status of the stream is obtained ${value}.`);
});

isMuteSync10+

isMuteSync(volumeType: AudioVolumeType): boolean

Checks whether a stream is muted. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.

Return value

TypeDescription
booleanReturns true if the stream is muted; returns false otherwise.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101invalid parameter error

Example

import { BusinessError } from '@ohos.base';

try {
  let value: boolean = audioVolumeGroupManager.isMuteSync(audio.AudioVolumeType.MEDIA);
  console.info(`Indicate that the mute status of the stream is obtained ${value}.`);
} catch (err) {
  let error = err as BusinessError;
  console.error(`Failed to obtain the mute status of the stream, error ${error}.`);
}

setRingerMode9+

setRingerMode(mode: AudioRingMode, callback: AsyncCallback<void>): void

Sets the ringer mode. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.ACCESS_NOTIFICATION_POLICY

This permission is required only for muting or unmuting the ringer.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
modeAudioRingModeYesRinger mode.
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioVolumeGroupManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err: BusinessError) => {
  if (err) {
    console.error(`Failed to set the ringer mode.​ ${err}`);
    return;
  }
  console.info('Callback invoked to indicate a successful setting of the ringer mode.');
});

setRingerMode9+

setRingerMode(mode: AudioRingMode): Promise<void>

Sets the ringer mode. This API uses a promise to return the result.

Required permissions: ohos.permission.ACCESS_NOTIFICATION_POLICY

This permission is required only for muting or unmuting the ringer.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
modeAudioRingModeYesRinger mode.

Return value

TypeDescription
Promise<void>Promise used to return the result.

Example

audioVolumeGroupManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => {
  console.info('Promise returned to indicate a successful setting of the ringer mode.');
});

getRingerMode9+

getRingerMode(callback: AsyncCallback<AudioRingMode>): void

Obtains the ringer mode. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<AudioRingMode>YesCallback used to return the ringer mode.

Example

import { BusinessError } from '@ohos.base';
audioVolumeGroupManager.getRingerMode((err: BusinessError, value: audio.AudioRingMode) => {
  if (err) {
    console.error(`Failed to obtain the ringer mode.​ ${err}`);
    return;
  }
  console.info(`Callback invoked to indicate that the ringer mode is obtained ${value}.`);
});

getRingerMode9+

getRingerMode(): Promise<AudioRingMode>

Obtains the ringer mode. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Volume

Return value

TypeDescription
Promise<AudioRingMode>Promise used to return the ringer mode.

Example

audioVolumeGroupManager.getRingerMode().then((value: audio.AudioRingMode) => {
  console.info(`Promise returned to indicate that the ringer mode is obtained ${value}.`);
});

getRingerModeSync10+

getRingerModeSync(): AudioRingMode

Obtains the ringer mode. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Volume

Return value

TypeDescription
AudioRingModeRinger mode.

Example

import { BusinessError } from '@ohos.base';

try {
  let value: audio.AudioRingMode = audioVolumeGroupManager.getRingerModeSync();
  console.info(`Indicate that the ringer mode is obtained ${value}.`);
} catch (err) {
  let error = err as BusinessError;
  console.error(`Failed to obtain the ringer mode, error ${error}.`);
}

on('ringerModeChange')9+

on(type: 'ringerModeChange', callback: Callback<AudioRingMode>): void

Subscribes to ringer mode change events.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The event 'ringerModeChange' is triggered when the ringer mode is changed.
callbackCallback<AudioRingMode>YesCallback used to return the result.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101if input parameter value error

Example

audioVolumeGroupManager.on('ringerModeChange', (ringerMode: audio.AudioRingMode) => {
  console.info(`Updated ringermode: ${ringerMode}`);
});

setMicrophoneMute9+

setMicrophoneMute(mute: boolean, callback: AsyncCallback<void>): void

Mutes or unmutes the microphone. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.MANAGE_AUDIO_CONFIG

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
mutebooleanYesMute status to set. The value true means to mute the microphone, and false means the opposite.
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioVolumeGroupManager.setMicrophoneMute(true, (err: BusinessError) => {
  if (err) {
    console.error(`Failed to mute the microphone. ${err}`);
    return;
  }
  console.info('Callback invoked to indicate that the microphone is muted.');
});

setMicrophoneMute9+

setMicrophoneMute(mute: boolean): Promise<void>

Mutes or unmutes the microphone. This API uses a promise to return the result.

Required permissions: ohos.permission.MANAGE_AUDIO_CONFIG

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
mutebooleanYesMute status to set. The value true means to mute the microphone, and false means the opposite.

Return value

TypeDescription
Promise<void>Promise used to return the result.

Example

audioVolumeGroupManager.setMicrophoneMute(true).then(() => {
  console.info('Promise returned to indicate that the microphone is muted.');
});

isMicrophoneMute9+

isMicrophoneMute(callback: AsyncCallback<boolean>): void

Checks whether the microphone is muted. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<boolean>YesCallback used to return the mute status of the microphone. The value true means that the microphone is muted, and false means the opposite.

Example

import { BusinessError } from '@ohos.base';
audioVolumeGroupManager.isMicrophoneMute((err: BusinessError, value: boolean) => {
  if (err) {
    console.error(`Failed to obtain the mute status of the microphone. ${err}`);
    return;
  }
  console.info(`Callback invoked to indicate that the mute status of the microphone is obtained ${value}.`);
});

isMicrophoneMute9+

isMicrophoneMute(): Promise<boolean>

Checks whether the microphone is muted. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Volume

Return value

TypeDescription
Promise<boolean>Promise used to return the mute status of the microphone. The value true means that the microphone is muted, and false means the opposite.

Example

audioVolumeGroupManager.isMicrophoneMute().then((value: boolean) => {
  console.info(`Promise returned to indicate that the mute status of the microphone is obtained ${value}.`);
});

isMicrophoneMuteSync10+

isMicrophoneMuteSync(): boolean

Checks whether the microphone is muted. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Volume

Return value

TypeDescription
booleanReturns true if the microphone is muted; returns false otherwise.

Example

import { BusinessError } from '@ohos.base';

try {
  let value: boolean = audioVolumeGroupManager.isMicrophoneMuteSync();
  console.info(`Indicate that the mute status of the microphone is obtained ${value}.`);
} catch (err) {
  let error = err as BusinessError;
  console.error(`Failed to obtain the mute status of the microphone, error ${error}.`);
}

on('micStateChange')9+

on(type: 'micStateChange', callback: Callback<MicStateChangeEvent>): void

Subscribes to system microphone state change events.

Currently, when multiple AudioManager instances are used in a single process, only the subscription of the last instance takes effect, and the subscription of other instances is overwritten (even if the last instance does not initiate a subscription). Therefore, you are advised to use a single AudioManager instance.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The event 'micStateChange' is triggered when the system microphone state is changed.
callbackCallback<MicStateChangeEvent>YesCallback used to return the changed microphone state.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101if input parameter value error

Example

audioVolumeGroupManager.on('micStateChange', (micStateChange: audio.MicStateChangeEvent) => {
  console.info(`Current microphone status is: ${micStateChange.mute} `);
});

isVolumeUnadjustable10+

isVolumeUnadjustable(): boolean

Checks whether the fixed volume mode is enabled. When the fixed volume mode is enabled, the volume cannot be adjusted. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Volume

Return value

TypeDescription
booleanReturns the status of the fixed volume mode. The value true means that the fixed volume mode is enabled, and false means the opposite.

Example

let volumeAdjustSwitch: boolean = audioVolumeGroupManager.isVolumeUnadjustable();
console.info(`Whether it is volume unadjustable: ${volumeAdjustSwitch}.`);

adjustVolumeByStep10+

adjustVolumeByStep(adjustType: VolumeAdjustType, callback: AsyncCallback<void>): void

Adjusts the volume of the stream with the highest priority by step. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.ACCESS_NOTIFICATION_POLICY

This permission is required only for muting or unmuting the ringer when volumeType is set to AudioVolumeType.RINGTONE.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
adjustTypeVolumeAdjustTypeYesVolume adjustment type.
callbackAsyncCallback<void>YesCallback used to return the result.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101Invalid parameter error. Return by callback.
6800301System error. Return by callback.

Example

import { BusinessError } from '@ohos.base';
audioVolumeGroupManager.adjustVolumeByStep(audio.VolumeAdjustType.VOLUME_UP, (err: BusinessError) => {
  if (err) {
    console.error(`Failed to adjust the volume by step. ${err}`);
    return;
  } else {
    console.info('Success to adjust the volume by step.');
  }
});

adjustVolumeByStep10+

adjustVolumeByStep(adjustType: VolumeAdjustType): Promise<void>

Adjusts the volume of the stream with the highest priority by step. This API uses a promise to return the result.

Required permissions: ohos.permission.ACCESS_NOTIFICATION_POLICY

This permission is required only for muting or unmuting the ringer when volumeType is set to AudioVolumeType.RINGTONE.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
adjustTypeVolumeAdjustTypeYesVolume adjustment type.

Return value

TypeDescription
Promise<void>Promise used to return the result.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101Invalid parameter error. Return by promise.
6800301System error. Return by promise.

Example

import { BusinessError } from '@ohos.base';
audioVolumeGroupManager.adjustVolumeByStep(audio.VolumeAdjustType.VOLUME_UP).then(() => {
  console.info('Success to adjust the volume by step.');
}).catch((error: BusinessError) => {
  console.error('Fail to adjust the volume by step.');
});

adjustSystemVolumeByStep10+

adjustSystemVolumeByStep(volumeType: AudioVolumeType, adjustType: VolumeAdjustType, callback: AsyncCallback<void>): void

Adjusts the volume of a stream by step. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.ACCESS_NOTIFICATION_POLICY

This permission is required only for muting or unmuting the ringer when volumeType is set to AudioVolumeType.RINGTONE.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.
adjustTypeVolumeAdjustTypeYesVolume adjustment type.
callbackAsyncCallback<void>YesCallback used to return the result.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101Invalid parameter error. Return by callback.
6800301System error. Return by callback.

Example

import { BusinessError } from '@ohos.base';
audioVolumeGroupManager.adjustSystemVolumeByStep(audio.AudioVolumeType.MEDIA, audio.VolumeAdjustType.VOLUME_UP, (err: BusinessError) => {
  if (err) {
    console.error(`Failed to adjust the system volume by step ${err}`);
  } else {
    console.info('Success to adjust the system volume by step.');
  }
});

adjustSystemVolumeByStep10+

adjustSystemVolumeByStep(volumeType: AudioVolumeType, adjustType: VolumeAdjustType): Promise<void>

Adjusts the volume of a stream by step. This API uses a promise to return the result.

Required permissions: ohos.permission.ACCESS_NOTIFICATION_POLICY

This permission is required only for muting or unmuting the ringer when volumeType is set to AudioVolumeType.RINGTONE.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.
adjustTypeVolumeAdjustTypeYesVolume adjustment type.

Return value

TypeDescription
Promise<void>Promise used to return the result.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101Invalid parameter error. Return by promise.
6800301System error. Return by promise.

Example

import { BusinessError } from '@ohos.base';
audioVolumeGroupManager.adjustSystemVolumeByStep(audio.AudioVolumeType.MEDIA, audio.VolumeAdjustType.VOLUME_UP).then(() => {
  console.info('Success to adjust the system volume by step.');
}).catch((error: BusinessError) => {
  console.error('Fail to adjust the system volume by step.');
});

getSystemVolumeInDb10+

getSystemVolumeInDb(volumeType: AudioVolumeType, volumeLevel: number, device: DeviceType, callback: AsyncCallback<number>): void

Obtains the volume gain. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.
volumeLevelnumberYesVolume level.
deviceDeviceTypeYesDevice type.
callbackAsyncCallback<number>YesCallback used to return the volume gain (in dB).

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101Invalid parameter error. Return by callback.
6800301System error. Return by callback.

Example

import { BusinessError } from '@ohos.base';
audioVolumeGroupManager.getSystemVolumeInDb(audio.AudioVolumeType.MEDIA, 3, audio.DeviceType.SPEAKER, (err: BusinessError, dB: number) => {
  if (err) {
    console.error(`Failed to get the volume DB. ${err}`);
  } else {
    console.info(`Success to get the volume DB. ${dB}`);
  }
});

getSystemVolumeInDb10+

getSystemVolumeInDb(volumeType: AudioVolumeType, volumeLevel: number, device: DeviceType): Promise<number>

Obtains the volume gain. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.
volumeLevelnumberYesVolume level.
deviceDeviceTypeYesDevice type.

Return value

TypeDescription
Promise<number>Promise used to return the volume gain (in dB).

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101Invalid parameter error. Return by promise.
6800301System error. Return by promise.

Example

import { BusinessError } from '@ohos.base';
audioVolumeGroupManager.getSystemVolumeInDb(audio.AudioVolumeType.MEDIA, 3, audio.DeviceType.SPEAKER).then((value: number) => {
  console.info(`Success to get the volume DB. ${value}`);
}).catch((error: BusinessError) => {
  console.error(`Fail to adjust the system volume by step. ${error}`);
});

getSystemVolumeInDbSync10+

getSystemVolumeInDbSync(volumeType: AudioVolumeType, volumeLevel: number, device: DeviceType): number

Obtains the volume gain. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Volume

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream type.
volumeLevelnumberYesVolume level.
deviceDeviceTypeYesDevice type.

Return value

TypeDescription
numberVolume gain (in dB).

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101invalid parameter error

Example

import { BusinessError } from '@ohos.base';

try {
  let value: number = audioVolumeGroupManager.getSystemVolumeInDbSync(audio.AudioVolumeType.MEDIA, 3, audio.DeviceType.SPEAKER);
  console.info(`Success to get the volume DB. ${value}`);
} catch (err) {
  let error = err as BusinessError;
  console.error(`Fail to adjust the system volume by step. ${error}`);
}

AudioStreamManager9+

Implements audio stream management. Before calling any API in AudioStreamManager, you must use getStreamManager to obtain an AudioStreamManager instance.

getCurrentAudioRendererInfoArray9+

getCurrentAudioRendererInfoArray(callback: AsyncCallback<AudioRendererChangeInfoArray>): void

Obtains the information about the current audio renderer. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<AudioRendererChangeInfoArray>YesCallback used to return the audio renderer information.

Example

import { BusinessError } from '@ohos.base';
audioStreamManager.getCurrentAudioRendererInfoArray(async (err: BusinessError, AudioRendererChangeInfoArray: audio.AudioRendererChangeInfoArray) => {
  console.info('getCurrentAudioRendererInfoArray **** Get Callback Called ****');
  if (err) {
    console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`);
  } else {
    if (AudioRendererChangeInfoArray != null) {
      for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) {
        let AudioRendererChangeInfo: audio.AudioRendererChangeInfo = AudioRendererChangeInfoArray[i];
        console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`);
        console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`);
        console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`);
        console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`);
        console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`);
        console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`);
        for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) {
          console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`);
          console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`);
          console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`);
          console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`);
          console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`);
          console.info(`SampleRate: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`);
          console.info(`ChannelCount: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`);
          console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks[0]}`);
        }
      }
    }
  }
});

getCurrentAudioRendererInfoArray9+

getCurrentAudioRendererInfoArray(): Promise<AudioRendererChangeInfoArray>

Obtains the information about the current audio renderer. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Return value

TypeDescription
Promise<AudioRendererChangeInfoArray>Promise used to return the audio renderer information.

Example

import { BusinessError } from '@ohos.base';
async function getCurrentAudioRendererInfoArray(){
  await audioStreamManager.getCurrentAudioRendererInfoArray().then((AudioRendererChangeInfoArray: audio.AudioRendererChangeInfoArray) => {
    console.info(`getCurrentAudioRendererInfoArray ######### Get Promise is called ##########`);
    if (AudioRendererChangeInfoArray != null) {
      for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) {
        let AudioRendererChangeInfo: audio.AudioRendererChangeInfo = AudioRendererChangeInfoArray[i];
        console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`);
        console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`);
        console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`);
        console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`);
        console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`);
        console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`);
        for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) {
          console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`);
          console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`);
          console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`);
          console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`);
          console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`);
          console.info(`SampleRate: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`);
          console.info(`ChannelCount: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`);
          console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks[0]}`);
        }
      }
    }
  }).catch((err: BusinessError) => {
    console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`);
  });
}

getCurrentAudioRendererInfoArraySync10+

getCurrentAudioRendererInfoArraySync(): AudioRendererChangeInfoArray

Obtains the information about the current audio renderer. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Renderer

Return value

TypeDescription
AudioRendererChangeInfoArrayAudio renderer information.

Example

import { BusinessError } from '@ohos.base';

try {
  let audioRendererChangeInfoArray: audio.AudioRendererChangeInfoArray = audioStreamManager.getCurrentAudioRendererInfoArraySync();
  console.info(`getCurrentAudioRendererInfoArraySync success.`);
  if (audioRendererChangeInfoArray != null) {
    for (let i = 0; i < audioRendererChangeInfoArray.length; i++) {
      let AudioRendererChangeInfo: audio.AudioRendererChangeInfo = audioRendererChangeInfoArray[i];
      console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`);
      console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`);
      console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`);
      console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`);
      console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`);
      console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`);
      for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) {
        console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`);
        console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`);
        console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`);
        console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`);
        console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`);
        console.info(`SampleRate: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`);
        console.info(`ChannelCount: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`);
        console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks[0]}`);
      }
    }
  }
} catch (err) {
  let error = err as BusinessError;
  console.error(`getCurrentAudioRendererInfoArraySync :ERROR: ${error}`);
}

getCurrentAudioCapturerInfoArray9+

getCurrentAudioCapturerInfoArray(callback: AsyncCallback<AudioCapturerChangeInfoArray>): void

Obtains the information about the current audio capturer. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<AudioCapturerChangeInfoArray>YesCallback used to return the audio capturer information.

Example

import { BusinessError } from '@ohos.base';
audioStreamManager.getCurrentAudioCapturerInfoArray(async (err: BusinessError, AudioCapturerChangeInfoArray: audio.AudioCapturerChangeInfoArray) => {
  console.info('getCurrentAudioCapturerInfoArray **** Get Callback Called ****');
  if (err) {
    console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`);
  } else {
    if (AudioCapturerChangeInfoArray != null) {
      for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) {
        console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`);
        console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`);
        console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`);
        console.info(`Flag  ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`);
        console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`);
        for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) {
          console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`);
          console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`);
          console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`);
          console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`);
          console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`);
          console.info(`SampleRate: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`);
          console.info(`ChannelCount: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`);
          console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks[0]}`);
        }
      }
    }
  }
});

getCurrentAudioCapturerInfoArray9+

getCurrentAudioCapturerInfoArray(): Promise<AudioCapturerChangeInfoArray>

Obtains the information about the current audio capturer. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Return value

TypeDescription
Promise<AudioCapturerChangeInfoArray>Promise used to return the audio capturer information.

Example

import { BusinessError } from '@ohos.base';
async function getCurrentAudioCapturerInfoArray(){
  await audioStreamManager.getCurrentAudioCapturerInfoArray().then((AudioCapturerChangeInfoArray: audio.AudioCapturerChangeInfoArray) => {
    console.info('getCurrentAudioCapturerInfoArray **** Get Promise Called ****');
    if (AudioCapturerChangeInfoArray != null) {
      for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) {
        console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`);
        console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`);
        console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`);
        console.info(`Flag  ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`);
        console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`);
        for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) {
          console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`);
          console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`);
          console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`);
          console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`);
          console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`);
          console.info(`SampleRate: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`);
          console.info(`ChannelCount: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`);
          console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks[0]}`);
        }
      }
    }
  }).catch((err: BusinessError) => {
    console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`);
  });
}

getCurrentAudioCapturerInfoArraySync10+

getCurrentAudioCapturerInfoArraySync(): AudioCapturerChangeInfoArray

Obtains the information about the current audio capturer. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Capturer

Return value

TypeDescription
AudioCapturerChangeInfoArrayAudio capturer information.

Example

import { BusinessError } from '@ohos.base';

try {
  let audioCapturerChangeInfoArray: audio.AudioCapturerChangeInfoArray = audioStreamManager.getCurrentAudioCapturerInfoArraySync();
  console.info('getCurrentAudioCapturerInfoArraySync success.');
  if (audioCapturerChangeInfoArray != null) {
    for (let i = 0; i < audioCapturerChangeInfoArray.length; i++) {
      console.info(`StreamId for ${i} is: ${audioCapturerChangeInfoArray[i].streamId}`);
      console.info(`ClientUid for ${i} is: ${audioCapturerChangeInfoArray[i].clientUid}`);
      console.info(`Source for ${i} is: ${audioCapturerChangeInfoArray[i].capturerInfo.source}`);
      console.info(`Flag  ${i} is: ${audioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`);
      console.info(`State for ${i} is: ${audioCapturerChangeInfoArray[i].capturerState}`);
      for (let j = 0; j < audioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) {
        console.info(`Id: ${i} : ${audioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`);
        console.info(`Type: ${i} : ${audioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`);
        console.info(`Role: ${i} : ${audioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`);
        console.info(`Name: ${i} : ${audioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`);
        console.info(`Address: ${i} : ${audioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`);
        console.info(`SampleRate: ${i} : ${audioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`);
        console.info(`ChannelCount: ${i} : ${audioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`);
        console.info(`ChannelMask: ${i} : ${audioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks[0]}`);
      }
    }
  }
} catch (err) {
  let error = err as BusinessError;
  console.error(`getCurrentAudioCapturerInfoArraySync ERROR: ${error}`);
}

on('audioRendererChange')9+

on(type: 'audioRendererChange', callback: Callback<AudioRendererChangeInfoArray>): void

Subscribes to audio renderer change events.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The event 'audioRendererChange' is triggered when the audio renderer is changed.
callbackCallback<AudioRendererChangeInfoArray>YesCallback used to return the result.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101if input parameter value error

Example

audioStreamManager.on('audioRendererChange',  (AudioRendererChangeInfoArray: audio.AudioRendererChangeInfoArray) => {
  for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) {
    let AudioRendererChangeInfo: audio.AudioRendererChangeInfo = AudioRendererChangeInfoArray[i];
    console.info(`## RendererChange on is called for ${i} ##`);
    console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`);
    console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`);
    console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`);
    console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`);
    console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`);
    console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`);
    for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) {
      console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`);
      console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`);
      console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`);
      console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`);
      console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`);
      console.info(`SampleRate: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`);
      console.info(`ChannelCount: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`);
      console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks[0]}`);
    }
  }
});

off('audioRendererChange')9+

off(type: 'audioRendererChange'): void

Unsubscribes from audio renderer change events.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The event 'audioRendererChange' is triggered when the audio renderer is changed.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101if input parameter value error

Example

audioStreamManager.off('audioRendererChange');
console.info('######### RendererChange Off is called #########');

on('audioCapturerChange')9+

on(type: 'audioCapturerChange', callback: Callback<AudioCapturerChangeInfoArray>): void

Subscribes to audio capturer change events.

System capability: SystemCapability.Multimedia.Audio.Capturer

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The event 'audioCapturerChange' is triggered when the audio capturer is changed.
callbackCallback<AudioCapturerChangeInfoArray>YesCallback used to return the result.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101if input parameter value error

Example

audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray: audio.AudioCapturerChangeInfoArray) =>  {
  for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) {
    console.info(`## CapChange on is called for element ${i} ##`);
    console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`);
    console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`);
    console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`);
    console.info(`Flag  ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`);
    console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`);
    let devDescriptor: audio.AudioCapturerChangeInfo = AudioCapturerChangeInfoArray[i].deviceDescriptors;
    for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) {
      console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`);
      console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`);
      console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`);
      console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`);
      console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`);
      console.info(`SampleRate: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`);
      console.info(`ChannelCount: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`);
      console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks[0]}`);
    }
  }
});

off('audioCapturerChange')9+

off(type: 'audioCapturerChange'): void;

Unsubscribes from audio capturer change events.

System capability: SystemCapability.Multimedia.Audio.Capturer

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The event 'audioCapturerChange' is triggered when the audio capturer is changed.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101if input parameter value error

Example

audioStreamManager.off('audioCapturerChange');
console.info('######### CapturerChange Off is called #########');


isActive9+

isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void

Checks whether a stream is active. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream types.
callbackAsyncCallback<boolean>YesCallback used to return the active status of the stream. The value true means that the stream is active, and false means the opposite.

Example

import { BusinessError } from '@ohos.base';
audioStreamManager.isActive(audio.AudioVolumeType.MEDIA, (err: BusinessError, value: boolean) => {
if (err) {
  console.error(`Failed to obtain the active status of the stream. ${err}`);
  return;
}
  console.info(`Callback invoked to indicate that the active status of the stream is obtained ${value}.`);
});

isActive9+

isActive(volumeType: AudioVolumeType): Promise<boolean>

Checks whether a stream is active. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream types.

Return value

TypeDescription
Promise<boolean>Promise used to return the active status of the stream. The value true means that the stream is active, and false means the opposite.

Example

audioStreamManager.isActive(audio.AudioVolumeType.MEDIA).then((value: boolean) => {
  console.info(`Promise returned to indicate that the active status of the stream is obtained ${value}.`);
});

isActiveSync10+

isActiveSync(volumeType: AudioVolumeType): boolean

Checks whether a stream is active. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
volumeTypeAudioVolumeTypeYesAudio stream types.

Return value

TypeDescription
booleanReturns true if the stream is active; returns false otherwise.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101invalid parameter error

Example

import { BusinessError } from '@ohos.base';

try {
  let value: boolean = audioStreamManager.isActiveSync(audio.AudioVolumeType.MEDIA);
  console.info(`Indicate that the active status of the stream is obtained ${value}.`);
} catch (err) {
  let error = err as BusinessError;
  console.error(`Failed to obtain the active status of the stream ${error}.`);
}

getAudioEffectInfoArray10+

getAudioEffectInfoArray(usage: StreamUsage, callback: AsyncCallback<AudioEffectInfoArray>): void

Obtains information about the sound effect mode in use. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
usageStreamUsageYesAudio stream usage.
callbackAsyncCallback<AudioEffectInfoArray>YesCallback used to return the information about the sound effect mode obtained.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101Invalid parameter error. Return by callback.

Example

import { BusinessError } from '@ohos.base';
audioStreamManager.getAudioEffectInfoArray(audio.StreamUsage.STREAM_USAGE_MEDIA, async (err: BusinessError, audioEffectInfoArray: audio.AudioEffectInfoArray) => {
  console.info('getAudioEffectInfoArray **** Get Callback Called ****');
  if (err) {
    console.error(`getAudioEffectInfoArray :ERROR: ${err}`);
    return;
  } else {
    console.info(`The effect modes are: ${audioEffectInfoArray}`);
  }
});

getAudioEffectInfoArray10+

getAudioEffectInfoArray(usage: StreamUsage): Promise<AudioEffectInfoArray>

Obtains information about the sound effect mode in use. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
usageStreamUsageYesAudio stream usage.

Return value

TypeDescription
Promise<AudioEffectInfoArray>Promise used to return the information about the sound effect mode obtained.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101Invalid parameter error. Return by promise.

Example

import { BusinessError } from '@ohos.base';
audioStreamManager.getAudioEffectInfoArray(audio.StreamUsage.STREAM_USAGE_MEDIA).then((audioEffectInfoArray: audio.AudioEffectInfoArray) => {
  console.info('getAudioEffectInfoArray ######### Get Promise is called ##########');
  console.info(`The effect modes are: ${audioEffectInfoArray}`);
}).catch((err: BusinessError) => {
  console.error(`getAudioEffectInfoArray :ERROR: ${err}`);
});

getAudioEffectInfoArraySync10+

getAudioEffectInfoArraySync(usage: StreamUsage): AudioEffectInfoArray

Obtains information about the sound effect mode in use. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
usageStreamUsageYesAudio stream usage.

Return value

TypeDescription
AudioEffectInfoArrayInformation about the sound effect mode.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101invalid parameter error

Example

import { BusinessError } from '@ohos.base';

try {
  let audioEffectInfoArray: audio.AudioEffectInfoArray = audioStreamManager.getAudioEffectInfoArraySync(audio.StreamUsage.STREAM_USAGE_MEDIA);
  console.info(`The effect modes are: ${audioEffectInfoArray}`);
} catch (err) {
  let error = err as BusinessError;
  console.error(`getAudioEffectInfoArraySync ERROR: ${error}`);
}

AudioRoutingManager9+

Implements audio routing management. Before calling any API in AudioRoutingManager, you must use getRoutingManager to obtain an AudioRoutingManager instance.

getDevices9+

getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void

Obtains the audio devices with a specific flag. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
deviceFlagDeviceFlagYesAudio device flag.
callbackAsyncCallback<AudioDeviceDescriptors>YesCallback used to return the device list.

Example

import { BusinessError } from '@ohos.base';
audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err: BusinessError, value: audio.AudioDeviceDescriptors) => {
  if (err) {
    console.error(`Failed to obtain the device list. ${err}`);
    return;
  }
  console.info('Callback invoked to indicate that the device list is obtained.');
});

getDevices9+

getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors>

Obtains the audio devices with a specific flag. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
deviceFlagDeviceFlagYesAudio device flag.

Return value

TypeDescription
Promise<AudioDeviceDescriptors>Promise used to return the device list.

Example

audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data: audio.AudioDeviceDescriptors) => {
  console.info('Promise returned to indicate that the device list is obtained.');
});

getDevicesSync10+

getDevicesSync(deviceFlag: DeviceFlag): AudioDeviceDescriptors

Obtains the audio devices with a specific flag. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
deviceFlagDeviceFlagYesAudio device flag.

Return value

TypeDescription
AudioDeviceDescriptorsDevice list.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101invalid parameter error

Example

import { BusinessError } from '@ohos.base';

try {
  let data: audio.AudioDeviceDescriptors = audioRoutingManager.getDevicesSync(audio.DeviceFlag.OUTPUT_DEVICES_FLAG);
  console.info(`Indicate that the device list is obtained ${data}`);
} catch (err) {
  let error = err as BusinessError;
  console.error(`Failed to obtain the device list. ${error}`);
}

on('deviceChange')9+

on(type: 'deviceChange', deviceFlag: DeviceFlag, callback: Callback<DeviceChangeAction>): void

Subscribes to device change events. When a device is connected or disconnected, registered clients will receive the callback.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The event 'deviceChange' is triggered when the device connection status is changed.
deviceFlagDeviceFlagYesAudio device flag.
callbackCallback<DeviceChangeAction>YesCallback used to return the device update details.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101if input parameter value error

Example

audioRoutingManager.on('deviceChange', audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (deviceChanged: audio.DeviceChangeAction) => {
  console.info('device change type : ' + deviceChanged.type);
  console.info('device descriptor size : ' + deviceChanged.deviceDescriptors.length);
  console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceRole);
  console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceType);
});

off('deviceChange')9+

off(type: 'deviceChange', callback?: Callback<DeviceChangeAction>): void

Unsubscribes from device change events.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The event 'deviceChange' is triggered when the device connection status is changed.
callbackCallback<DeviceChangeAction>NoCallback used to return the device update details.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101if input parameter value error

Example

audioRoutingManager.off('deviceChange');

selectInputDevice9+

selectInputDevice(inputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void

Selects an audio input device. Only one input device can be selected. This API uses an asynchronous callback to return the result.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
inputAudioDevicesAudioDeviceDescriptorsYesInput device.
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import audio from '@ohos.multimedia.audio';
import { BusinessError } from '@ohos.base';
let inputAudioDeviceDescriptor: audio.AudioDeviceDescriptors = [{
  deviceRole : audio.DeviceRole.INPUT_DEVICE,
  deviceType : audio.DeviceType.EARPIECE,
  id : 1,
  name : "",
  address : "",
  sampleRates : [44100],
  channelCounts : [2],
  channelMasks : [0],
  networkId : audio.LOCAL_NETWORK_ID,
  interruptGroupId : 1,
  volumeGroupId : 1,
  displayName : "",
}];

async function selectInputDevice(){
  audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor, (err: BusinessError) => {
    if (err) {
      console.error(`Result ERROR: ${err}`);
    } else {
      console.info('Select input devices result callback: SUCCESS');
    }
  });
}

selectInputDevice9+

selectInputDevice(inputAudioDevices: AudioDeviceDescriptors): Promise<void>

System API: This is a system API.

Selects an audio input device. Only one input device can be selected. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
inputAudioDevicesAudioDeviceDescriptorsYesInput device.

Return value

TypeDescription
Promise<void>Promise used to return the result.

Example

import audio from '@ohos.multimedia.audio';
import { BusinessError } from '@ohos.base';
let inputAudioDeviceDescriptor: audio.AudioDeviceDescriptors = [{
  deviceRole : audio.DeviceRole.INPUT_DEVICE,
  deviceType : audio.DeviceType.EARPIECE,
  id : 1,
  name : "",
  address : "",
  sampleRates : [44100],
  channelCounts : [2],
  channelMasks : [0],
  networkId : audio.LOCAL_NETWORK_ID,
  interruptGroupId : 1,
  volumeGroupId : 1,
  displayName : "",
}];

async function getRoutingManager(){
  audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor).then(() => {
    console.info('Select input devices result promise: SUCCESS');
  }).catch((err: BusinessError) => {
    console.error(`Result ERROR: ${err}`);
  });
}

setCommunicationDevice9+

setCommunicationDevice(deviceType: CommunicationDeviceType, active: boolean, callback: AsyncCallback<void>): void

Sets a communication device to the active state. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Communication

Parameters

NameTypeMandatoryDescription
deviceTypeCommunicationDeviceTypeYesCommunication device type.
activebooleanYesActive state to set. The value true means to set the device to the active state, and false means the opposite.
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioRoutingManager.setCommunicationDevice(audio.CommunicationDeviceType.SPEAKER, true, (err: BusinessError) => {
  if (err) {
    console.error(`Failed to set the active status of the device. ${err}`);
    return;
  }
  console.info('Callback invoked to indicate that the device is set to the active status.');
});

setCommunicationDevice9+

setCommunicationDevice(deviceType: CommunicationDeviceType, active: boolean): Promise<void>

Sets a communication device to the active state. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Communication

Parameters

NameTypeMandatoryDescription
deviceTypeCommunicationDeviceTypeYesCommunication device type.
activebooleanYesActive state to set. The value true means to set the device to the active state, and false means the opposite.

Return value

TypeDescription
Promise<void>Promise used to return the result.

Example

audioRoutingManager.setCommunicationDevice(audio.CommunicationDeviceType.SPEAKER, true).then(() => {
  console.info('Promise returned to indicate that the device is set to the active status.');
});

isCommunicationDeviceActive9+

isCommunicationDeviceActive(deviceType: CommunicationDeviceType, callback: AsyncCallback<boolean>): void

Checks whether a communication device is active. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Communication

Parameters

NameTypeMandatoryDescription
deviceTypeCommunicationDeviceTypeYesCommunication device type.
callbackAsyncCallback<boolean>YesCallback used to return the active state of the device.

Example

import { BusinessError } from '@ohos.base';
audioRoutingManager.isCommunicationDeviceActive(audio.CommunicationDeviceType.SPEAKER, (err: BusinessError, value: boolean) => {
  if (err) {
    console.error(`Failed to obtain the active status of the device. ${err}`);
    return;
  }
  console.info('Callback invoked to indicate that the active status of the device is obtained.');
});

isCommunicationDeviceActive9+

isCommunicationDeviceActive(deviceType: CommunicationDeviceType): Promise<boolean>

Checks whether a communication device is active. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Communication

Parameters

NameTypeMandatoryDescription
deviceTypeCommunicationDeviceTypeYesCommunication device type.

Return value

TypeDescription
Promise<boolean>Promise used to return the active state of the device.

Example

audioRoutingManager.isCommunicationDeviceActive(audio.CommunicationDeviceType.SPEAKER).then((value: boolean) => {
  console.info(`Promise returned to indicate that the active status of the device is obtained ${value}.`);
});

isCommunicationDeviceActiveSync10+

isCommunicationDeviceActiveSync(deviceType: CommunicationDeviceType): boolean

Checks whether a communication device is active. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Communication

Parameters

NameTypeMandatoryDescription
deviceTypeCommunicationDeviceTypeYesCommunication device type.

Return value

TypeDescription
booleanActive state of the device.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101invalid parameter error

Example

import { BusinessError } from '@ohos.base';

try {
  let value: boolean = audioRoutingManager.isCommunicationDeviceActiveSync(audio.CommunicationDeviceType.SPEAKER);
  console.info(`Indicate that the active status of the device is obtained ${value}.`);
} catch (err) {
  let error = err as BusinessError;
  console.error(`Failed to obtain the active status of the device ${error}.`);
}

selectOutputDevice9+

selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void

Selects an audio output device. Currently, only one output device can be selected. This API uses an asynchronous callback to return the result.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
outputAudioDevicesAudioDeviceDescriptorsYesOutput device.
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import audio from '@ohos.multimedia.audio';
import { BusinessError } from '@ohos.base';
let outputAudioDeviceDescriptor: audio.AudioDeviceDescriptors = [{
  deviceRole : audio.DeviceRole.OUTPUT_DEVICE,
  deviceType : audio.DeviceType.SPEAKER,
  id : 1,
  name : "",
  address : "",
  sampleRates : [44100],
  channelCounts : [2],
  channelMasks : [0],
  networkId : audio.LOCAL_NETWORK_ID,
  interruptGroupId : 1,
  volumeGroupId : 1,
  displayName : "",
}];

async function selectOutputDevice(){
  audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor, (err: BusinessError) => {
    if (err) {
      console.error(`Result ERROR: ${err}`);
    } else {
      console.info('Select output devices result callback: SUCCESS'); }
  });
}

selectOutputDevice9+

selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors): Promise<void>

System API: This is a system API.

Selects an audio output device. Currently, only one output device can be selected. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
outputAudioDevicesAudioDeviceDescriptorsYesOutput device.

Return value

TypeDescription
Promise<void>Promise used to return the result.

Example

import audio from '@ohos.multimedia.audio';
import { BusinessError } from '@ohos.base';
let outputAudioDeviceDescriptor: audio.AudioDeviceDescriptors = [{
  deviceRole : audio.DeviceRole.OUTPUT_DEVICE,
  deviceType : audio.DeviceType.SPEAKER,
  id : 1,
  name : "",
  address : "",
  sampleRates : [44100],
  channelCounts : [2],
  channelMasks : [0],
  networkId : audio.LOCAL_NETWORK_ID,
  interruptGroupId : 1,
  volumeGroupId : 1,
  displayName : "",
}];

async function selectOutputDevice(){
  audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor).then(() => {
    console.info('Select output devices result promise: SUCCESS');
  }).catch((err: BusinessError) => {
    console.error(`Result ERROR: ${err}`);
  });
}

selectOutputDeviceByFilter9+

selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void

System API: This is a system API.

Selects an audio output device based on the filter criteria. Currently, only one output device can be selected. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
filterAudioRendererFilterYesFilter criteria.
outputAudioDevicesAudioDeviceDescriptorsYesOutput device.
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import audio from '@ohos.multimedia.audio';
import { BusinessError } from '@ohos.base';
let outputAudioRendererFilter: audio.AudioRendererFilter = {
  uid : 20010041,
  rendererInfo : {
    content : audio.ContentType.CONTENT_TYPE_MUSIC,
    usage : audio.StreamUsage.STREAM_USAGE_MEDIA,
    rendererFlags : 0
  },
  rendererId : 0
};

let outputAudioDeviceDescriptor: audio.AudioDeviceDescriptors = [{
  deviceRole : audio.DeviceRole.OUTPUT_DEVICE,
  deviceType : audio.DeviceType.SPEAKER,
  id : 1,
  name : "",
  address : "",
  sampleRates : [44100],
  channelCounts : [2],
  channelMasks : [0],
  networkId : audio.LOCAL_NETWORK_ID,
  interruptGroupId : 1,
  volumeGroupId : 1,
  displayName : "",
}];

async function selectOutputDeviceByFilter(){
  audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor, (err: BusinessError) => {
    if (err) {
      console.error(`Result ERROR: ${err}`);
    } else {
      console.info('Select output devices by filter result callback: SUCCESS'); }
  });
}

selectOutputDeviceByFilter9+

selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors): Promise<void>

System API: This is a system API.

Selects an audio output device based on the filter criteria. Currently, only one output device can be selected. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
filterAudioRendererFilterYesFilter criteria.
outputAudioDevicesAudioDeviceDescriptorsYesOutput device.

Return value

TypeDescription
Promise<void>Promise used to return the result.

Example

import audio from '@ohos.multimedia.audio';
import { BusinessError } from '@ohos.base';
let outputAudioRendererFilter: audio.AudioRendererFilter = {
  uid : 20010041,
  rendererInfo : {
    content : audio.ContentType.CONTENT_TYPE_MUSIC,
    usage : audio.StreamUsage.STREAM_USAGE_MEDIA,
    rendererFlags : 0
  },
  rendererId : 0
};

let outputAudioDeviceDescriptor: audio.AudioDeviceDescriptors = [{
  deviceRole : audio.DeviceRole.OUTPUT_DEVICE,
  deviceType : audio.DeviceType.SPEAKER,
  id : 1,
  name : "",
  address : "",
  sampleRates : [44100],
  channelCounts : [2],
  channelMasks : [0],
  networkId : audio.LOCAL_NETWORK_ID,
  interruptGroupId : 1,
  volumeGroupId : 1,
  displayName : "",
}];

async function selectOutputDeviceByFilter(){
  audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor).then(() => {
    console.info('Select output devices by filter result promise: SUCCESS');
  }).catch((err: BusinessError) => {
    console.error(`Result ERROR: ${err}`);
  })
}

getPreferOutputDeviceForRendererInfo10+

getPreferOutputDeviceForRendererInfo(rendererInfo: AudioRendererInfo, callback: AsyncCallback<AudioDeviceDescriptors>): void

Obtains the output device with the highest priority based on the audio renderer information. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
rendererInfoAudioRendererInfoYesAudio renderer information.
callbackAsyncCallback<AudioDeviceDescriptors>YesCallback used to return the information about the output device with the highest priority.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101if input parameter value error. Return by callback.
6800301System error. Return by callback.

Example

import audio from '@ohos.multimedia.audio';
import { BusinessError } from '@ohos.base';
let rendererInfo: audio.AudioRendererInfo = {
  usage : audio.StreamUsage.STREAM_USAGE_MUSIC,
  rendererFlags : 0
}

async function getPreferOutputDevice() {
  audioRoutingManager.getPreferOutputDeviceForRendererInfo(rendererInfo, (err: BusinessError, desc: audio.AudioDeviceDescriptors) => {
    if (err) {
      console.error(`Result ERROR: ${err}`);
    } else {
      console.info(`device descriptor: ${desc}`);
    }
  });
}

getPreferOutputDeviceForRendererInfo10+

getPreferOutputDeviceForRendererInfo(rendererInfo: AudioRendererInfo): Promise<AudioDeviceDescriptors>

Obtains the output device with the highest priority based on the audio renderer information. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
rendererInfoAudioRendererInfoYesAudio renderer information.

Return value

TypeDescription
Promise<AudioDeviceDescriptors>Promise used to return the information about the output device with the highest priority.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101if input parameter value error. Return by promise.
6800301System error. Return by promise.

Example

import audio from '@ohos.multimedia.audio';
import { BusinessError } from '@ohos.base';
let rendererInfo: audio.AudioRendererInfo = {
  usage : audio.StreamUsage.STREAM_USAGE_MUSIC,
  rendererFlags : 0
}

async function getPreferOutputDevice() {
  audioRoutingManager.getPreferOutputDeviceForRendererInfo(rendererInfo).then((desc: audio.AudioDeviceDescriptors) => {
    console.info(`device descriptor: ${desc}`);
  }).catch((err: BusinessError) => {
    console.error(`Result ERROR: ${err}`);
  })
}

getPreferredOutputDeviceForRendererInfoSync10+

getPreferredOutputDeviceForRendererInfoSync(rendererInfo: AudioRendererInfo): AudioDeviceDescriptors

Obtains the output device with the highest priority based on the audio renderer information. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
rendererInfoAudioRendererInfoYesAudio renderer information.

Return value

TypeDescription
AudioDeviceDescriptorsInformation about the output device with the highest priority.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101invalid parameter error.

Example

import audio from '@ohos.multimedia.audio';
import { BusinessError } from '@ohos.base';

let rendererInfo: audio.AudioRendererInfo = {
  usage : audio.StreamUsage.STREAM_USAGE_MUSIC,
  rendererFlags : 0
}

try {
  let desc: audio.AudioDeviceDescriptors = audioRoutingManager.getPreferredOutputDeviceForRendererInfoSync(rendererInfo);
  console.info(`device descriptor: ${desc}`);
} catch (err) {
  let error = err as BusinessError;
  console.error(`Result ERROR: ${error}`);
}

on('preferOutputDeviceChangeForRendererInfo')10+

on(type: 'preferOutputDeviceChangeForRendererInfo', rendererInfo: AudioRendererInfo, callback: Callback<AudioDeviceDescriptors>): void

Subscribes to the change of the output device with the highest priority. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The event 'preferOutputDeviceChangeForRendererInfo' is triggered when the output device with the highest priority is changed.
rendererInfoAudioRendererInfoYesAudio renderer information.
callbackCallback<AudioDeviceDescriptors>YesCallback used to return the information about the output device with the highest priority.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101if input parameter value error

Example

import audio from '@ohos.multimedia.audio';
let rendererInfo: audio.AudioRendererInfo = {
  usage : audio.StreamUsage.STREAM_USAGE_MUSIC,
  rendererFlags : 0
}

audioRoutingManager.on('preferOutputDeviceChangeForRendererInfo', rendererInfo, (desc: audio.AudioDeviceDescriptors) => {
  console.info(`device descriptor: ${desc}`);
});

off('preferOutputDeviceChangeForRendererInfo')10+

off(type: 'preferOutputDeviceChangeForRendererInfo', callback?: Callback<AudioDeviceDescriptors>): void

Unsubscribes from the change of the output device with the highest priority.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The event 'preferOutputDeviceChangeForRendererInfo' is triggered when the output device with the highest priority is changed.
callbackCallback<AudioDeviceDescriptors>NoCallback used for unsubscription.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101if input parameter value error

Example

audioRoutingManager.off('preferOutputDeviceChangeForRendererInfo');

getPreferredInputDeviceForCapturerInfo10+

getPreferredInputDeviceForCapturerInfo(capturerInfo: AudioCapturerInfo, callback: AsyncCallback<AudioDeviceDescriptors>): void

Obtains the input device with the highest priority based on the audio capturer information. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
capturerInfoAudioCapturerInfoYesAudio capturer information.
callbackAsyncCallback<AudioDeviceDescriptors>YesCallback used to return the information about the input device with the highest priority.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101Invalid parameter error. Return by callback.
6800301System error. Return by callback.

Example

import audio from '@ohos.multimedia.audio';
import { BusinessError } from '@ohos.base';
let capturerInfo: audio.AudioCapturerInfo = {
  source: audio.SourceType.SOURCE_TYPE_MIC,
  capturerFlags: 0
}

audioRoutingManager.getPreferredInputDeviceForCapturerInfo(capturerInfo, (err: BusinessError, desc: audio.AudioDeviceDescriptors) => {
  if (err) {
    console.error(`Result ERROR: ${err}`);
  } else {
    console.info(`device descriptor: ${desc}`);
  }
});

getPreferredInputDeviceForCapturerInfo10+

getPreferredInputDeviceForCapturerInfo(capturerInfo: AudioCapturerInfo): Promise<AudioDeviceDescriptors>

Obtains the input device with the highest priority based on the audio capturer information. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
capturerInfoAudioCapturerInfoYesAudio capturer information.

Return value

TypeDescription
Promise<AudioDeviceDescriptors>Promise used to return the information about the input device with the highest priority.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101Invalid parameter error. Return by promise.
6800301System error. Return by promise.

Example

import audio from '@ohos.multimedia.audio';
import { BusinessError } from '@ohos.base';
let capturerInfo: audio.AudioCapturerInfo = {
  source: audio.SourceType.SOURCE_TYPE_MIC,
  capturerFlags: 0
}

audioRoutingManager.getPreferredInputDeviceForCapturerInfo(capturerInfo).then((desc: audio.AudioDeviceDescriptors) => {
  console.info(`device descriptor: ${desc}`);
}).catch((err: BusinessError) => {
  console.error(`Result ERROR: ${err}`);
});

getPreferredInputDeviceForCapturerInfoSync10+

getPreferredInputDeviceForCapturerInfoSync(capturerInfo: AudioCapturerInfo): AudioDeviceDescriptors

Obtains the input device with the highest priority based on the audio capturer information. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
capturerInfoAudioCapturerInfoYesAudio capturer information.

Return value

TypeDescription
AudioDeviceDescriptorsInformation about the input device with the highest priority.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101invalid parameter error

Example

import audio from '@ohos.multimedia.audio';
import { BusinessError } from '@ohos.base';

let capturerInfo: audio.AudioCapturerInfo = {
  source: audio.SourceType.SOURCE_TYPE_MIC,
  capturerFlags: 0
}

try {
  let desc: audio.AudioDeviceDescriptors = audioRoutingManager.getPreferredInputDeviceForCapturerInfoSync(capturerInfo);
  console.info(`device descriptor: ${desc}`);
} catch (err) {
  let error = err as BusinessError;
  console.error(`Result ERROR: ${error}`);
}

on('preferredInputDeviceChangeForCapturerInfo')10+

on(type: 'preferredInputDeviceChangeForCapturerInfo', capturerInfo: AudioCapturerInfo, callback: Callback<AudioDeviceDescriptors>): void

Subscribes to the change of the input device with the highest priority. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The event 'preferredInputDeviceChangeForCapturerInfo' is triggered when the input device with the highest priority is changed.
capturerInfoAudioCapturerInfoYesAudio capturer information.
callbackCallback<AudioDeviceDescriptors>YesCallback used to return the information about the input device with the highest priority.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101if input parameter value error

Example

import audio from '@ohos.multimedia.audio';
let capturerInfo: audio.AudioCapturerInfo = {
  source: audio.SourceType.SOURCE_TYPE_MIC,
  capturerFlags: 0
}

audioRoutingManager.on('preferredInputDeviceChangeForCapturerInfo', capturerInfo, (desc: audio.AudioDeviceDescriptors) => {
  console.info(`device descriptor: ${desc}`);
});

off('preferredInputDeviceChangeForCapturerInfo')10+

off(type: 'preferredInputDeviceChangeForCapturerInfo', callback?: Callback<AudioDeviceDescriptors>): void

Unsubscribes from the change of the input device with the highest priority.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The event 'preferredInputDeviceChangeForCapturerInfo' is triggered when the input device with the highest priority is changed.
callbackCallback<AudioDeviceDescriptors>NoCallback used for unsubscription.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101if input parameter value error

Example

audioRoutingManager.off('preferredInputDeviceChangeForCapturerInfo');

AudioRendererChangeInfoArray9+

Defines an AudioRenderChangeInfo array, which is read-only.

System capability: SystemCapability.Multimedia.Audio.Renderer

AudioRendererChangeInfo9+

Describes the audio renderer change event.

System capability: SystemCapability.Multimedia.Audio.Renderer

NameTypeReadableWritableDescription
streamIdnumberYesNoUnique ID of an audio stream.
clientUidnumberYesNoUID of the audio renderer client.
This is a system API.
rendererInfoAudioRendererInfoYesNoAudio renderer information.
rendererStateAudioStateYesNoAudio state.
This is a system API.
deviceDescriptorsAudioDeviceDescriptorsYesNoAudio device description.

Example

import audio from '@ohos.multimedia.audio';

const audioManager = audio.getAudioManager();
let audioStreamManager = audioManager.getStreamManager();
let resultFlag = false;

audioStreamManager.on('audioRendererChange',  (AudioRendererChangeInfoArray) => {
  for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) {
    console.info(`## RendererChange on is called for ${i} ##`);
    console.info(`StreamId for ${i} is: ${AudioRendererChangeInfoArray[i].streamId}`);
    console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfoArray[i].clientUid}`);
    console.info(`Content for ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.content}`);
    console.info(`Stream for ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.usage}`);
    console.info(`Flag ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.rendererFlags}`);
    console.info(`State for ${i} is: ${AudioRendererChangeInfoArray[i].rendererState}`);
    let devDescriptor = AudioRendererChangeInfoArray[i].deviceDescriptors;
    for (let j = 0; j < AudioRendererChangeInfoArray[i].deviceDescriptors.length; j++) {
      console.info(`Id: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].id}`);
      console.info(`Type: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceType}`);
      console.info(`Role: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceRole}`);
      console.info(`Name: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].name}`);
      console.info(`Addr: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].address}`);
      console.info(`SR: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`);
      console.info(`C ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`);
      console.info(`CM: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelMasks[0]}`);
    }
    if (AudioRendererChangeInfoArray[i].rendererState == 1 && devDescriptor != null) {
      resultFlag = true;
      console.info(`ResultFlag for ${i} is: ${resultFlag}`);
    }
  }
});

AudioCapturerChangeInfoArray9+

Defines an AudioCapturerChangeInfo array, which is read-only.

System capability: SystemCapability.Multimedia.Audio.Capturer

AudioCapturerChangeInfo9+

Describes the audio capturer change event.

System capability: SystemCapability.Multimedia.Audio.Capturer

NameTypeReadableWritableDescription
streamIdnumberYesNoUnique ID of an audio stream.
clientUidnumberYesNoUID of the audio capturer client.
This is a system API.
capturerInfoAudioCapturerInfoYesNoAudio capturer information.
capturerStateAudioStateYesNoAudio state.
This is a system API.
deviceDescriptorsAudioDeviceDescriptorsYesNoAudio device description.
muted11+booleanYesNoWhether the audio capturer is muted. The value true means that the audio capturer is muted, and false means the opposite.

Example

import audio from '@ohos.multimedia.audio';

const audioManager = audio.getAudioManager();
let audioStreamManager = audioManager.getStreamManager();

let resultFlag = false;
audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) =>  {
  for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) {
    console.info(`## CapChange on is called for element ${i} ##`);
    console.info(`StrId for  ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`);
    console.info(`CUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`);
    console.info(`Src for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`);
    console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`);
    console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`);
    let devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors;
    for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) {
      console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`);
      console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`);
      console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`);
      console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`);
      console.info(`Addr: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`);
      console.info(`SR: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`);
      console.info(`C ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`);
      console.info(`CM ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks[0]}`);
    }
    if (AudioCapturerChangeInfoArray[i].capturerState == 1 && devDescriptor != null) {
      resultFlag = true;
      console.info(`ResultFlag for element ${i} is: ${resultFlag}`);
    }
  }
});

AudioEffectInfoArray10+

Defines an array that contains the audio effect mode corresponding to a specific audio content type (specified by ContentType) and audio stream usage (specified by StreamUsage). The AudioEffectMode array is read-only.

AudioDeviceDescriptors

Defines an AudioDeviceDescriptor array, which is read-only.

AudioDeviceDescriptor

Describes an audio device.

System capability: SystemCapability.Multimedia.Audio.Device

NameTypeReadableWritableDescription
deviceRoleDeviceRoleYesNoDevice role.
deviceTypeDeviceTypeYesNoDevice type.
id9+numberYesNoDevice ID, which is unique.
name9+stringYesNoDevice name.
For a Bluetooth device, you must request the ohos.permission.USE_BLUETOOTH permission.
address9+stringYesNoDevice address.
For a Bluetooth device, you must request the ohos.permission.USE_BLUETOOTH permission.
sampleRates9+Array<number>YesNoSupported sampling rates.
channelCounts9+Array<number>YesNoNumber of channels supported.
channelMasks9+Array<number>YesNoSupported channel masks.
displayName10+stringYesNoDisplay name of the device.
networkId9+stringYesNoID of the device network.
This is a system API.
interruptGroupId9+numberYesNoID of the interruption group to which the device belongs.
This is a system API.
volumeGroupId9+numberYesNoID of the volume group to which the device belongs.
This is a system API.
encodingTypes11+Array<AudioEncodingType>YesNoSupported encoding types.

Example

import audio from '@ohos.multimedia.audio';

function displayDeviceProp(value: audio.AudioDeviceDescriptor) {
  deviceRoleValue = value.deviceRole;
  deviceTypeValue = value.deviceType;
}

let deviceRoleValue: audio.DeviceRole|undefined = undefined;;
let deviceTypeValue: audio.DeviceType|undefined = undefined;;
audio.getAudioManager().getDevices(1).then((value: audio.AudioDeviceDescriptors) => {
  console.info('AudioFrameworkTest: Promise: getDevices OUTPUT_DEVICES_FLAG');
  value.forEach(displayDeviceProp);
  if (deviceTypeValue != undefined && deviceRoleValue != undefined){
    console.info('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG :  PASS');
  } else {
    console.error('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG :  FAIL');
  }
});

AudioRendererFilter9+

Implements filter criteria. Before calling selectOutputDeviceByFilter, you must obtain an AudioRendererFilter instance.

System API: This is a system API.

NameTypeMandatoryDescription
uidnumberNoApplication ID.
System capability: SystemCapability.Multimedia.Audio.Core
rendererInfoAudioRendererInfoNoAudio renderer information.
System capability: SystemCapability.Multimedia.Audio.Renderer
rendererIdnumberNoUnique ID of an audio stream.
System capability: SystemCapability.Multimedia.Audio.Renderer

Example

import audio from '@ohos.multimedia.audio';
let outputAudioRendererFilter: audio.AudioRendererFilter = {
  uid : 20010041,
  rendererInfo : {
    content : audio.ContentType.CONTENT_TYPE_MUSIC,
    usage : audio.StreamUsage.STREAM_USAGE_MEDIA,
    rendererFlags : 0
  },
  rendererId : 0
};

AudioRenderer8+

Provides APIs for audio rendering. Before calling any API in AudioRenderer, you must use createAudioRenderer to create an AudioRenderer instance.

Attributes

System capability: SystemCapability.Multimedia.Audio.Renderer

NameTypeReadableWritableDescription
state8+AudioStateYesNoAudio renderer state.

Example

import audio from '@ohos.multimedia.audio';
let state: audio.AudioState = audioRenderer.state;

getRendererInfo8+

getRendererInfo(callback: AsyncCallback<AudioRendererInfo>): void

Obtains the renderer information of this AudioRenderer instance. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<AudioRendererInfo>YesCallback used to return the renderer information.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.getRendererInfo((err: BusinessError, rendererInfo: audio.AudioRendererInfo) => {
  console.info('Renderer GetRendererInfo:');
  console.info(`Renderer content: ${rendererInfo.content}`);
  console.info(`Renderer usage: ${rendererInfo.usage}`);
  console.info(`Renderer flags: ${rendererInfo.rendererFlags}`);
});

getRendererInfo8+

getRendererInfo(): Promise<AudioRendererInfo>

Obtains the renderer information of this AudioRenderer instance. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Return value

TypeDescription
Promise<AudioRendererInfo>Promise used to return the renderer information.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.getRendererInfo().then((rendererInfo: audio.AudioRendererInfo) => {
  console.info('Renderer GetRendererInfo:');
  console.info(`Renderer content: ${rendererInfo.content}`);
  console.info(`Renderer usage: ${rendererInfo.usage}`);
  console.info(`Renderer flags: ${rendererInfo.rendererFlags}`)
}).catch((err: BusinessError) => {
  console.error(`AudioFrameworkRenderLog: RendererInfo :ERROR: ${err}`);
});

getRendererInfoSync10+

getRendererInfoSync(): AudioRendererInfo

Obtains the renderer information of this AudioRenderer instance. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Renderer

Return value

TypeDescription
AudioRendererInfoAudio renderer information.

Example

import { BusinessError } from '@ohos.base';

try {
  let rendererInfo: audio.AudioRendererInfo = audioRenderer.getRendererInfoSync();
  console.info(`Renderer content: ${rendererInfo.content}`);
  console.info(`Renderer usage: ${rendererInfo.usage}`);
  console.info(`Renderer flags: ${rendererInfo.rendererFlags}`)
} catch (err) {
  let error = err as BusinessError;
  console.error(`AudioFrameworkRenderLog: RendererInfo :ERROR: ${error}`);
}

getStreamInfo8+

getStreamInfo(callback: AsyncCallback<AudioStreamInfo>): void

Obtains the stream information of this AudioRenderer instance. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<AudioStreamInfo>YesCallback used to return the stream information.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.getStreamInfo((err: BusinessError, streamInfo: audio.AudioStreamInfo) => {
  console.info('Renderer GetStreamInfo:');
  console.info(`Renderer sampling rate: ${streamInfo.samplingRate}`);
  console.info(`Renderer channel: ${streamInfo.channels}`);
  console.info(`Renderer format: ${streamInfo.sampleFormat}`);
  console.info(`Renderer encoding type: ${streamInfo.encodingType}`);
});

getStreamInfo8+

getStreamInfo(): Promise<AudioStreamInfo>

Obtains the stream information of this AudioRenderer instance. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Return value

TypeDescription
Promise<AudioStreamInfo>Promise used to return the stream information.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.getStreamInfo().then((streamInfo: audio.AudioStreamInfo) => {
  console.info('Renderer GetStreamInfo:');
  console.info(`Renderer sampling rate: ${streamInfo.samplingRate}`);
  console.info(`Renderer channel: ${streamInfo.channels}`);
  console.info(`Renderer format: ${streamInfo.sampleFormat}`);
  console.info(`Renderer encoding type: ${streamInfo.encodingType}`);
}).catch((err: BusinessError) => {
  console.error(`ERROR: ${err}`);
});

getStreamInfoSync10+

getStreamInfoSync(): AudioStreamInfo

Obtains the stream information of this AudioRenderer instance. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Renderer

Return value

TypeDescription
AudioStreamInfoStream information.

Example

import { BusinessError } from '@ohos.base';

try {
  let streamInfo: audio.AudioStreamInfo = audioRenderer.getStreamInfoSync();
  console.info(`Renderer sampling rate: ${streamInfo.samplingRate}`);
  console.info(`Renderer channel: ${streamInfo.channels}`);
  console.info(`Renderer format: ${streamInfo.sampleFormat}`);
  console.info(`Renderer encoding type: ${streamInfo.encodingType}`);
} catch (err) {
  let error = err as BusinessError;
  console.error(`ERROR: ${error}`);
}

getAudioStreamId9+

getAudioStreamId(callback: AsyncCallback<number>): void

Obtains the stream ID of this AudioRenderer instance. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<number>YesCallback used to return the stream ID.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.getAudioStreamId((err: BusinessError, streamid: number) => {
  console.info(`Renderer GetStreamId: ${streamid}`);
});

getAudioStreamId9+

getAudioStreamId(): Promise<number>

Obtains the stream ID of this AudioRenderer instance. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Return value

TypeDescription
Promise<number>Promise used to return the stream ID.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.getAudioStreamId().then((streamid: number) => {
  console.info(`Renderer getAudioStreamId: ${streamid}`);
}).catch((err: BusinessError) => {
  console.error(`ERROR: ${err}`);
});

getAudioStreamIdSync10+

getAudioStreamIdSync(): number

Obtains the stream ID of this AudioRenderer instance. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Renderer

Return value

TypeDescription
numberStream ID.

Example

import { BusinessError } from '@ohos.base';

try {
  let streamid: number = audioRenderer.getAudioStreamIdSync();
  console.info(`Renderer getAudioStreamIdSync: ${streamid}`);
} catch (err) {
  let error = err as BusinessError;
  console.error(`ERROR: ${error}`);
}

setAudioEffectMode10+

setAudioEffectMode(mode: AudioEffectMode, callback: AsyncCallback<void>): void

Sets an audio effect mode. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
modeAudioEffectModeYesAudio effect mode to set.
callbackAsyncCallback<void>YesCallback used to return the result.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101Invalid parameter error. Return by callback.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.setAudioEffectMode(audio.AudioEffectMode.EFFECT_DEFAULT, (err: BusinessError) => {
  if (err) {
    console.error('Failed to set params');
  } else {
    console.info('Callback invoked to indicate a successful audio effect mode setting.');
  }
});

setAudioEffectMode10+

setAudioEffectMode(mode: AudioEffectMode): Promise<void>

Sets an audio effect mode. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
modeAudioEffectModeYesAudio effect mode to set.

Return value

TypeDescription
Promise<void>Promise used to return the result.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101Invalid parameter error. Return by promise.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.setAudioEffectMode(audio.AudioEffectMode.EFFECT_DEFAULT).then(() => {
  console.info('setAudioEffectMode SUCCESS');
}).catch((err: BusinessError) => {
  console.error(`ERROR: ${err}`);
});

getAudioEffectMode10+

getAudioEffectMode(callback: AsyncCallback<AudioEffectMode>): void

Obtains the audio effect mode in use. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<AudioEffectMode>YesCallback used to return the audio effect mode.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.getAudioEffectMode((err: BusinessError, effectmode: audio.AudioEffectMode) => {
  if (err) {
    console.error('Failed to get params');
  } else {
    console.info(`getAudioEffectMode: ${effectmode}`);
  }
});

getAudioEffectMode10+

getAudioEffectMode(): Promise<AudioEffectMode>

Obtains the audio effect mode in use. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Return value

TypeDescription
Promise<AudioEffectMode>Promise used to return the audio effect mode.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.getAudioEffectMode().then((effectmode: audio.AudioEffectMode) => {
  console.info(`getAudioEffectMode: ${effectmode}`);
}).catch((err: BusinessError) => {
  console.error(`ERROR: ${err}`);
});

start8+

start(callback: AsyncCallback<void>): void

Starts the renderer. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.start((err: BusinessError) => {
  if (err) {
    console.error('Renderer start failed.');
  } else {
    console.info('Renderer start success.');
  }
});

start8+

start(): Promise<void>

Starts the renderer. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Return value

TypeDescription
Promise<void>Promise used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.start().then(() => {
  console.info('Renderer started');
}).catch((err: BusinessError) => {
  console.error(`ERROR: ${err}`);
});

pause8+

pause(callback: AsyncCallback<void>): void

Pauses rendering. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.pause((err: BusinessError) => {
  if (err) {
    console.error('Renderer pause failed');
  } else {
    console.info('Renderer paused.');
  }
});

pause8+

pause(): Promise<void>

Pauses rendering. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Return value

TypeDescription
Promise<void>Promise used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.pause().then(() => {
  console.info('Renderer paused');
}).catch((err: BusinessError) => {
  console.error(`ERROR: ${err}`);
});

drain8+

drain(callback: AsyncCallback<void>): void

Drains the playback buffer. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.drain((err: BusinessError) => {
  if (err) {
    console.error('Renderer drain failed');
  } else {
    console.info('Renderer drained.');
  }
});

drain8+

drain(): Promise<void>

Drains the playback buffer. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Return value

TypeDescription
Promise<void>Promise used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.drain().then(() => {
  console.info('Renderer drained successfully');
}).catch((err: BusinessError) => {
  console.error(`ERROR: ${err}`);
});

stop8+

stop(callback: AsyncCallback<void>): void

Stops rendering. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.stop((err: BusinessError) => {
  if (err) {
    console.error('Renderer stop failed');
  } else {
    console.info('Renderer stopped.');
  }
});

stop8+

stop(): Promise<void>

Stops rendering. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Return value

TypeDescription
Promise<void>Promise used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.stop().then(() => {
  console.info('Renderer stopped successfully');
}).catch((err: BusinessError) => {
  console.error(`ERROR: ${err}`);
});

release8+

release(callback: AsyncCallback<void>): void

Releases the renderer. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.release((err: BusinessError) => {
  if (err) {
    console.error('Renderer release failed');
  } else {
    console.info('Renderer released.');
  }
});

release8+

release(): Promise<void>

Releases the renderer. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Return value

TypeDescription
Promise<void>Promise used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.release().then(() => {
  console.info('Renderer released successfully');
}).catch((err: BusinessError) => {
  console.error(`ERROR: ${err}`);
});

write8+

write(buffer: ArrayBuffer, callback: AsyncCallback<number>): void

Writes the buffer. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
bufferArrayBufferYesBuffer to be written.
callbackAsyncCallback<number>YesCallback used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned.

Example

import { BusinessError } from '@ohos.base';
let bufferSize: number;
class Options {
  offset?: number;
  length?: number;
}
audioRenderer.getBufferSize().then((data: number)=> {
  console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`);
  bufferSize = data;
  console.info(`Buffer size: ${bufferSize}`);
  let path = getContext().cacheDir;
  let filePath = path + '/StarWars10s-2C-48000-4SW.wav';
  let file: fs.File = fs.openSync(filePath, fs.OpenMode.READ_ONLY);
  fs.stat(filePath).then(async (stat: fs.Stat) => {
    let buf = new ArrayBuffer(bufferSize);
    let len = stat.size % bufferSize == 0 ? Math.floor(stat.size / bufferSize) : Math.floor(stat.size / bufferSize + 1);
    for (let i = 0;i < len; i++) {
      let options: Options = {
        offset: i * bufferSize,
        length: bufferSize
      }
      let readsize: number = await fs.read(file.fd, buf, options)
      let writeSize: number = await new Promise((resolve,reject)=>{
        audioRenderer.write(buf,(err: BusinessError, writeSize: number)=>{
          if(err){
            reject(err)
          }else{
            resolve(writeSize)
          }
        })
      })
    }
  });
  }).catch((err: BusinessError) => {
    console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`);
});



write8+

write(buffer: ArrayBuffer): Promise<number>

Writes the buffer. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Return value

TypeDescription
Promise<number>Promise used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned.

Example

import { BusinessError } from '@ohos.base';
let bufferSize: number;
class Options {
  offset?: number;
  length?: number;
}
audioRenderer.getBufferSize().then((data: number) => {
  console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`);
  bufferSize = data;
  console.info(`BufferSize: ${bufferSize}`);
  let path = getContext().cacheDir;
  let filePath = path + '/StarWars10s-2C-48000-4SW.wav';
  let file: fs.File = fs.openSync(filePath, fs.OpenMode.READ_ONLY);
  fs.stat(filePath).then(async (stat: fs.Stat) => {
    let buf = new ArrayBuffer(bufferSize);
    let len = stat.size % bufferSize == 0 ? Math.floor(stat.size / bufferSize) : Math.floor(stat.size / bufferSize + 1);
    for (let i = 0;i < len; i++) {
      let options: Options = {
        offset: i * bufferSize,
        length: bufferSize
      }
      let readsize: number = await fs.read(file.fd, buf, options)
      try{
        let writeSize: number = await audioRenderer.write(buf);
      } catch(err) {
        let error = err as BusinessError;
        console.error(`audioRenderer.write err: ${error}`);
      }
    }
  });
  }).catch((err: BusinessError) => {
    console.info(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`);
});

getAudioTime8+

getAudioTime(callback: AsyncCallback<number>): void

Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<number>YesCallback used to return the timestamp.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.getAudioTime((err: BusinessError, timestamp: number) => {
  console.info(`Current timestamp: ${timestamp}`);
});

getAudioTime8+

getAudioTime(): Promise<number>

Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Return value

TypeDescription
Promise<number>Promise used to return the timestamp.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.getAudioTime().then((timestamp: number) => {
  console.info(`Current timestamp: ${timestamp}`);
}).catch((err: BusinessError) => {
  console.error(`ERROR: ${err}`);
});

getAudioTimeSync10+

getAudioTimeSync(): number

Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Renderer

Return value

TypeDescription
numberTimestamp.

Example

import { BusinessError } from '@ohos.base';

try {
  let timestamp: number = audioRenderer.getAudioTimeSync();
  console.info(`Current timestamp: ${timestamp}`);
} catch (err) {
  let error = err as BusinessError;
  console.error(`ERROR: ${error}`);
}

getBufferSize8+

getBufferSize(callback: AsyncCallback<number>): void

Obtains a reasonable minimum buffer size in bytes for rendering. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<number>YesCallback used to return the buffer size.

Example

import { BusinessError } from '@ohos.base';
let bufferSize: number;
audioRenderer.getBufferSize((err: BusinessError, data: number) => {
  if (err) {
    console.error('getBufferSize error');
  } else {
    console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`);
    bufferSize = data;
  }
});

getBufferSize8+

getBufferSize(): Promise<number>

Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Return value

TypeDescription
Promise<number>Promise used to return the buffer size.

Example

import { BusinessError } from '@ohos.base';
let bufferSize: number;
audioRenderer.getBufferSize().then((data: number) => {
  console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`);
  bufferSize = data;
}).catch((err: BusinessError) => {
  console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`);
});

getBufferSizeSync10+

getBufferSizeSync(): number

Obtains a reasonable minimum buffer size in bytes for rendering. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Renderer

Return value

TypeDescription
numberBuffer size.

Example

import { BusinessError } from '@ohos.base';

let bufferSize: number = 0;
try {
  bufferSize = audioRenderer.getBufferSizeSync();
  console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${bufferSize}`);
} catch (err) {
  let error = err as BusinessError;
  console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${error}`);
}

setRenderRate8+

setRenderRate(rate: AudioRendererRate, callback: AsyncCallback<void>): void

Sets the render rate. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
rateAudioRendererRateYesAudio render rate.
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL, (err: BusinessError) => {
  if (err) {
    console.error('Failed to set params');
  } else {
    console.info('Callback invoked to indicate a successful render rate setting.');
  }
});

setRenderRate8+

setRenderRate(rate: AudioRendererRate): Promise<void>

Sets the render rate. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
rateAudioRendererRateYesAudio render rate.

Return value

TypeDescription
Promise<void>Promise used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL).then(() => {
  console.info('setRenderRate SUCCESS');
}).catch((err: BusinessError) => {
  console.error(`ERROR: ${err}`);
});

getRenderRate8+

getRenderRate(callback: AsyncCallback<AudioRendererRate>): void

Obtains the current render rate. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<AudioRendererRate>YesCallback used to return the audio render rate.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.getRenderRate((err: BusinessError, renderrate: audio.AudioRendererRate) => {
  console.info(`getRenderRate: ${renderrate}`);
});

getRenderRate8+

getRenderRate(): Promise<AudioRendererRate>

Obtains the current render rate. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Return value

TypeDescription
Promise<AudioRendererRate>Promise used to return the audio render rate.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.getRenderRate().then((renderRate: audio.AudioRendererRate) => {
  console.info(`getRenderRate: ${renderRate}`);
}).catch((err: BusinessError) => {
  console.error(`ERROR: ${err}`);
});

getRenderRateSync10+

getRenderRateSync(): AudioRendererRate

Obtains the current render rate. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Renderer

Return value

TypeDescription
AudioRendererRateAudio render rate.

Example

import { BusinessError } from '@ohos.base';

try {
  let renderRate: audio.AudioRendererRate = audioRenderer.getRenderRateSync();
  console.info(`getRenderRate: ${renderRate}`);
} catch (err) {
  let error = err as BusinessError;
  console.error(`ERROR: ${error}`);
}

setInterruptMode9+

setInterruptMode(mode: InterruptMode): Promise<void>

Sets the audio interruption mode for the application. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Interrupt

Parameters

NameTypeMandatoryDescription
modeInterruptModeYesAudio interruption mode.

Return value

TypeDescription
Promise<void>Promise used to return the result. If the operation is successful, undefined is returned. Otherwise, error is returned.

Example

import { BusinessError } from '@ohos.base';
let mode = 0;
audioRenderer.setInterruptMode(mode).then(() => {
  console.info('setInterruptMode Success!');
}).catch((err: BusinessError) => {
  console.error(`setInterruptMode Fail: ${err}`);
});

setInterruptMode9+

setInterruptMode(mode: InterruptMode, callback: AsyncCallback<void>): void

Sets the audio interruption mode for the application. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Interrupt

Parameters

NameTypeMandatoryDescription
modeInterruptModeYesAudio interruption mode.
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import { BusinessError } from '@ohos.base';
let mode = 1;
audioRenderer.setInterruptMode(mode, (err: BusinessError) => {
  if(err){
    console.error(`setInterruptMode Fail: ${err}`);
  }
  console.info('setInterruptMode Success!');
});

setInterruptModeSync10+

setInterruptModeSync(mode: InterruptMode): void

Sets the audio interruption mode for the application. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Interrupt

Parameters

NameTypeMandatoryDescription
modeInterruptModeYesAudio interruption mode.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101invalid parameter error

Example

import { BusinessError } from '@ohos.base';

try {
  audioRenderer.setInterruptModeSync(0);
  console.info('setInterruptMode Success!');
} catch (err) {
  let error = err as BusinessError;
  console.error(`setInterruptMode Fail: ${error}`);
}

setVolume9+

setVolume(volume: number): Promise<void>

Sets the volume for the application. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
volumenumberYesVolume to set, which can be within the range from 0.0 to 1.0.

Return value

TypeDescription
Promise<void>Promise used to return the result. If the operation is successful, undefined is returned. Otherwise, error is returned.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.setVolume(0.5).then(() => {
  console.info('setVolume Success!');
}).catch((err: BusinessError) => {
  console.error(`setVolume Fail: ${err}`);
});

setVolume9+

setVolume(volume: number, callback: AsyncCallback<void>): void

Sets the volume for the application. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
volumenumberYesVolume to set, which can be within the range from 0.0 to 1.0.
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.setVolume(0.5, (err: BusinessError) => {
  if(err){
    console.error(`setVolume Fail: ${err}`);
  }
  console.info('setVolume Success!');
});

getMinStreamVolume10+

getMinStreamVolume(callback: AsyncCallback<number>): void

Obtains the minimum volume of the application from the perspective of an audio stream. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<number>YesCallback used to return the minimum volume, ranging from 0 to 1.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.getMinStreamVolume((err: BusinessError, minVolume: number) => {
  if (err) {
    console.error(`getMinStreamVolume error: ${err}`);
  } else {
    console.info(`getMinStreamVolume Success! ${minVolume}`);
  }
});

getMinStreamVolume10+

getMinStreamVolume(): Promise<number>

Obtains the minimum volume of the application from the perspective of an audio stream. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Return value

TypeDescription
Promise<number>Promise used to return the minimum volume, ranging from 0 to 1.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.getMinStreamVolume().then((value: number) => {
  console.info(`Get min stream volume Success! ${value}`);
}).catch((err: BusinessError) => {
  console.error(`Get min stream volume Fail: ${err}`);
});

getMinStreamVolumeSync10+

getMinStreamVolumeSync(): number

Obtains the minimum volume of the application from the perspective of an audio stream. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Renderer

Return value

TypeDescription
numberMinimum volume, ranging from 0 to 1.

Example

import { BusinessError } from '@ohos.base';

try {
  let value: number = audioRenderer.getMinStreamVolumeSync();
  console.info(`Get min stream volume Success! ${value}`);
} catch (err) {
  let error = err as BusinessError;
  console.error(`Get min stream volume Fail: ${error}`);
}

getMaxStreamVolume10+

getMaxStreamVolume(callback: AsyncCallback<number>): void

Obtains the maximum volume of the application from the perspective of an audio stream. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<number>YesCallback used to return the maximum volume, ranging from 0 to 1.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.getMaxStreamVolume((err: BusinessError, maxVolume: number) => {
  if (err) {
    console.error(`getMaxStreamVolume Fail: ${err}`);
  } else {
    console.info(`getMaxStreamVolume Success! ${maxVolume}`);
  }
});

getMaxStreamVolume10+

getMaxStreamVolume(): Promise<number>

Obtains the maximum volume of the application from the perspective of an audio stream. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Return value

TypeDescription
Promise<number>Promise used to return the maximum volume, ranging from 0 to 1.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.getMaxStreamVolume().then((value: number) => {
  console.info(`Get max stream volume Success! ${value}`);
}).catch((err: BusinessError) => {
  console.error(`Get max stream volume Fail: ${err}`);
});

getMaxStreamVolumeSync10+

getMaxStreamVolumeSync(): number

Obtains the maximum volume of the application from the perspective of an audio stream. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Renderer

Return value

TypeDescription
numberMaximum volume, ranging from 0 to 1.

Example

import { BusinessError } from '@ohos.base';

try {
  let value: number = audioRenderer.getMaxStreamVolumeSync();
  console.info(`Get max stream volume Success! ${value}`);
} catch (err) {
  let error = err as BusinessError;
  console.error(`Get max stream volume Fail: ${error}`);
}

getUnderflowCount10+

getUnderflowCount(callback: AsyncCallback<number>): void

Obtains the number of underflow audio frames in the audio stream that is being played. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<number>YesCallback used to return the number of underflow audio frames.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.getUnderflowCount((err: BusinessError, underflowCount: number) => {
  if (err) {
    console.error(`getUnderflowCount Fail: ${err}`);
  } else {
    console.info(`getUnderflowCount Success! ${underflowCount}`);
  }
});

getUnderflowCount10+

getUnderflowCount(): Promise<number>

Obtains the number of underflow audio frames in the audio stream that is being played. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Renderer

Return value

TypeDescription
Promise<number>Promise used to return the number of underflow audio frames.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.getUnderflowCount().then((value: number) => {
  console.info(`Get underflow count Success! ${value}`);
}).catch((err: BusinessError) => {
  console.error(`Get underflow count Fail: ${err}`);
});

getUnderflowCountSync10+

getUnderflowCountSync(): number

Obtains the number of underflow audio frames in the audio stream that is being played. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Renderer

Return value

TypeDescription
numberNumber of underflow audio frames.

Example

import { BusinessError } from '@ohos.base';

try {
  let value: number = audioRenderer.getUnderflowCountSync();
  console.info(`Get underflow count Success! ${value}`);
} catch (err) {
  let error = err as BusinessError;
  console.error(`Get underflow count Fail: ${error}`);
}

getCurrentOutputDevices10+

getCurrentOutputDevices(callback: AsyncCallback<AudioDeviceDescriptors>): void

Obtains the output device descriptors of the audio streams. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<AudioDeviceDescriptors>YesCallback used to return the output device descriptors.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.getCurrentOutputDevices((err: BusinessError, deviceInfo: audio.AudioDeviceDescriptors) => {
  if (err) {
    console.error(`getCurrentOutputDevices Fail: ${err}`);
  } else {
    for (let i = 0; i < deviceInfo.length; i++) {
      console.info(`DeviceInfo id: ${deviceInfo[i].id}`);
      console.info(`DeviceInfo type: ${deviceInfo[i].deviceType}`);
      console.info(`DeviceInfo role: ${deviceInfo[i].deviceRole}`);
      console.info(`DeviceInfo name: ${deviceInfo[i].name}`);
      console.info(`DeviceInfo address: ${deviceInfo[i].address}`);
      console.info(`DeviceInfo samplerate: ${deviceInfo[i].sampleRates[0]}`);
      console.info(`DeviceInfo channelcount: ${deviceInfo[i].channelCounts[0]}`);
      console.info(`DeviceInfo channelmask: ${deviceInfo[i].channelMasks[0]}`);
    }
  }
});

getCurrentOutputDevices10+

getCurrentOutputDevices(): Promise<AudioDeviceDescriptors>

Obtains the output device descriptors of the audio streams. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Device

Return value

TypeDescription
Promise<AudioDeviceDescriptors>Promise used to return the output device descriptors.

Example

import { BusinessError } from '@ohos.base';
audioRenderer.getCurrentOutputDevices().then((deviceInfo: audio.AudioDeviceDescriptors) => {
  for (let i = 0; i < deviceInfo.length; i++) {
    console.info(`DeviceInfo id: ${deviceInfo[i].id}`);
    console.info(`DeviceInfo type: ${deviceInfo[i].deviceType}`);
    console.info(`DeviceInfo role: ${deviceInfo[i].deviceRole}`);
    console.info(`DeviceInfo name: ${deviceInfo[i].name}`);
    console.info(`DeviceInfo address: ${deviceInfo[i].address}`);
    console.info(`DeviceInfo samplerate: ${deviceInfo[i].sampleRates[0]}`);
    console.info(`DeviceInfo channelcount: ${deviceInfo[i].channelCounts[0]}`);
    console.info(`DeviceInfo channelmask: ${deviceInfo[i].channelMasks[0]}`);
  }
}).catch((err: BusinessError) => {
  console.error(`Get current output devices Fail: ${err}`);
});

getCurrentOutputDevicesSync10+

getCurrentOutputDevicesSync(): AudioDeviceDescriptors

Obtains the output device descriptors of the audio streams. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Device

Return value

TypeDescription
AudioDeviceDescriptorsOutput device descriptors.

Example

import { BusinessError } from '@ohos.base';

try {
  let deviceInfo: audio.AudioDeviceDescriptors = audioRenderer.getCurrentOutputDevicesSync();
  for (let i = 0; i < deviceInfo.length; i++) {
    console.info(`DeviceInfo id: ${deviceInfo[i].id}`);
    console.info(`DeviceInfo type: ${deviceInfo[i].deviceType}`);
    console.info(`DeviceInfo role: ${deviceInfo[i].deviceRole}`);
    console.info(`DeviceInfo name: ${deviceInfo[i].name}`);
    console.info(`DeviceInfo address: ${deviceInfo[i].address}`);
    console.info(`DeviceInfo samplerate: ${deviceInfo[i].sampleRates[0]}`);
    console.info(`DeviceInfo channelcount: ${deviceInfo[i].channelCounts[0]}`);
    console.info(`DeviceInfo channelmask: ${deviceInfo[i].channelMasks[0]}`);
  }
} catch (err) {
  let error = err as BusinessError;
  console.error(`Get current output devices Fail: ${error}`);
}

setChannelBlendMode11+

setChannelBlendMode(mode: ChannelBlendMode): void

Sets the audio channel blending mode. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
modeChannelBlendModeYesAudio channel blending mode.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101Input parameter value error.
6800103Operation not permit at current state.

Example

let mode = audio.ChannelBlendMode.MODE_DEFAULT;

audioRenderer.setChannelBlendMode(mode);
console.info(`BlendMode: ${mode}`);

on('audioInterrupt')9+

on(type: 'audioInterrupt', callback: Callback<InterruptEvent>): void

Subscribes to audio interruption events. This API uses a callback to obtain interrupt events.

Same as on('interrupt'), this API is used to listen for focus changes. The AudioRenderer instance proactively gains the focus when the start event occurs and releases the focus when the pause or stop event occurs. Therefore, you do not need to request to gain or release the focus.

System capability: SystemCapability.Multimedia.Audio.Interrupt

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The event 'audioInterrupt' is triggered when audio rendering is interrupted.
callbackCallback<InterruptEvent>YesCallback used to return the audio interruption event.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101if input parameter value error

Example

import audio from '@ohos.multimedia.audio';

let isPlaying: boolean; // An identifier specifying whether rendering is in progress.
let isDucked: boolean; // An identifier specifying whether the audio volume is reduced.
onAudioInterrupt();

async function onAudioInterrupt(){
  audioRenderer.on('audioInterrupt', (interruptEvent: audio.InterruptEvent) => {
    if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) {
      // The system forcibly interrupts audio rendering. The application must update the status and displayed content accordingly.
      switch (interruptEvent.hintType) {
        case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
          // The audio stream has been paused and temporarily loses the focus. It will receive the interruptEvent corresponding to resume when it is able to regain the focus.
          console.info('Force paused. Update playing status and stop writing');
          isPlaying = false; // A simplified processing indicating several operations for switching the application to the paused state.
          break;
        case audio.InterruptHint.INTERRUPT_HINT_STOP:
          // The audio stream has been stopped and permanently loses the focus. The user must manually trigger the operation to resume rendering.
          console.info('Force stopped. Update playing status and stop writing');
          isPlaying = false; // A simplified processing indicating several operations for switching the application to the paused state.
          break;
        case audio.InterruptHint.INTERRUPT_HINT_DUCK:
          // The audio stream is rendered at a reduced volume.
          console.info('Force ducked. Update volume status');
          isDucked = true; // A simplified processing indicating several operations for updating the volume status.
          break;
        case audio.InterruptHint.INTERRUPT_HINT_UNDUCK:
          // The audio stream is rendered at the normal volume.
          console.info('Force ducked. Update volume status');
          isDucked = false; // A simplified processing indicating several operations for updating the volume status.
          break;
        default:
          console.info('Invalid interruptEvent');
          break;
      }
    } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) {
      // The application can choose to take action or ignore.
      switch (interruptEvent.hintType) {
        case audio.InterruptHint.INTERRUPT_HINT_RESUME:
          // It is recommended that the application continue rendering. (The audio stream has been forcibly paused and temporarily lost the focus. It can resume rendering now.)
          console.info('Resume force paused renderer or ignore');
          // To continue rendering, the application must perform the required operations.
          break;
        case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
          // It is recommended that the application pause rendering.
          console.info('Choose to pause or ignore');
          // To pause rendering, the application must perform the required operations.
          break;
        case audio.InterruptHint.INTERRUPT_HINT_STOP:
          // It is recommended that the application stop rendering.
          console.info('Choose to stop or ignore');
          // To stop rendering, the application must perform the required operations.
          break;
        case audio.InterruptHint.INTERRUPT_HINT_DUCK:
          // It is recommended that the application reduce the volume for rendering.
          console.info('Choose to duck or ignore');
          // To decrease the volume for rendering, the application must perform the required operations.
          break;
        case audio.InterruptHint.INTERRUPT_HINT_UNDUCK:
          // It is recommended that the application resume rendering at the normal volume.
          console.info('Choose to unduck or ignore');
          // To resume rendering at the normal volume, the application must perform the required operations.
          break;
        default:
          break;
      }
    }
  });
}

on('markReach')8+

on(type: 'markReach', frame: number, callback: Callback<number>): void

Subscribes to mark reached events. When the number of frames rendered reaches the value of the frame parameter, a callback is invoked.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is fixed at 'markReach'.
framenumberYesNumber of frames to trigger the event. The value must be greater than 0.
callbackCallback<number>YesCallback invoked when the event is triggered.

Example

audioRenderer.on('markReach', 1000, (position: number) => {
  if (position == 1000) {
    console.info('ON Triggered successfully');
  }
});

off('markReach') 8+

off(type: 'markReach'): void

Unsubscribes from mark reached events.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is fixed at 'markReach'.

Example

audioRenderer.off('markReach');

on('periodReach') 8+

on(type: 'periodReach', frame: number, callback: Callback<number>): void

Subscribes to period reached events. When the number of frames rendered reaches the value of the frame parameter, a callback is triggered and the specified value is returned.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is fixed at 'periodReach'.
framenumberYesNumber of frames to trigger the event. The value must be greater than 0.
callbackCallback<number>YesCallback invoked when the event is triggered.

Example

audioRenderer.on('periodReach', 1000, (position: number) => {
  if (position == 1000) {
    console.info('ON Triggered successfully');
  }
});

off('periodReach') 8+

off(type: 'periodReach'): void

Unsubscribes from period reached events.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is fixed at 'periodReach'.

Example

audioRenderer.off('periodReach')

on('stateChange')8+

on(type: 'stateChange', callback: Callback<AudioState>): void

Subscribes to state change events.

System capability: SystemCapability.Multimedia.Audio.Renderer

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value stateChange means the state change event.
callbackCallback<AudioState>YesCallback used to return the state change.

Example

audioRenderer.on('stateChange', (state: audio.AudioState) => {
  if (state == 1) {
    console.info('audio renderer state is: STATE_PREPARED');
  }
  if (state == 2) {
    console.info('audio renderer state is: STATE_RUNNING');
  }
});

on('outputDeviceChange') 10+

on(type: 'outputDeviceChange', callback: Callback<AudioDeviceDescriptors>): void;

Subscribes to audio output device change events.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The event 'outputDeviceChange' is triggered when the audio output device is changed.
callbackCallback<AudioDeviceDescriptors>YesCallback used to return the audio output device change.

Error codes

IDError Message
6800101if input parameter value error.

Example

audioRenderer.on('outputDeviceChange', (deviceInfo: audio.AudioDeviceDescriptors) => {
  console.info(`DeviceInfo id: ${deviceInfo[0].id}`);
  console.info(`DeviceInfo name: ${deviceInfo[0].name}`);
  console.info(`DeviceInfo address: ${deviceInfo[0].address}`);
});

off('outputDeviceChange') 10+

off(type: 'outputDeviceChange', callback?: Callback<AudioDeviceDescriptors>): void;

Unsubscribes from audio output device change events.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The event 'outputDeviceChange' is triggered when the audio output device is changed.
callbackCallback<AudioDeviceDescriptors>NoCallback used for unsubscription.

Error codes

IDError Message
6800101if input parameter value error.

Example

audioRenderer.off('outputDeviceChange', (deviceInfo: audio.AudioDeviceDescriptors) => {
  console.info(`DeviceInfo id: ${deviceInfo[0].id}`);
  console.info(`DeviceInfo name: ${deviceInfo[0].name}`);
  console.info(`DeviceInfo address: ${deviceInfo[0].address}`);
});

AudioCapturer8+

Provides APIs for audio capture. Before calling any API in AudioCapturer, you must use createAudioCapturer to create an AudioCapturer instance.

Attributes

System capability: SystemCapability.Multimedia.Audio.Capturer

NameTypeReadableWritableDescription
state8+AudioStateYesNoAudio capturer state.

Example

import audio from '@ohos.multimedia.audio';
let state: audio.AudioState = audioCapturer.state;

getCapturerInfo8+

getCapturerInfo(callback: AsyncCallback<AudioCapturerInfo>): void

Obtains the capturer information of this AudioCapturer instance. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Capturer

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<AudioCapturerInfo>YesCallback used to return the capturer information.

Example

import { BusinessError } from '@ohos.base';
audioCapturer.getCapturerInfo((err: BusinessError, capturerInfo: audio.AudioCapturerInfo) => {
  if (err) {
    console.error('Failed to get capture info');
  } else {
    console.info('Capturer getCapturerInfo:');
    console.info(`Capturer source: ${capturerInfo.source}`);
    console.info(`Capturer flags: ${capturerInfo.capturerFlags}`);
  }
});

getCapturerInfo8+

getCapturerInfo(): Promise<AudioCapturerInfo>

Obtains the capturer information of this AudioCapturer instance. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Capturer

Return value

TypeDescription
Promise<AudioCapturerInfo>Promise used to return the capturer information.

Example

import { BusinessError } from '@ohos.base';
audioCapturer.getCapturerInfo().then((audioParamsGet: audio.AudioCapturerInfo) => {
  if (audioParamsGet != undefined) {
    console.info('AudioFrameworkRecLog: Capturer CapturerInfo:');
    console.info(`AudioFrameworkRecLog: Capturer SourceType: ${audioParamsGet.source}`);
    console.info(`AudioFrameworkRecLog: Capturer capturerFlags: ${audioParamsGet.capturerFlags}`);
  } else {
    console.info(`AudioFrameworkRecLog: audioParamsGet is : ${audioParamsGet}`);
    console.info('AudioFrameworkRecLog: audioParams getCapturerInfo are incorrect');
  }
}).catch((err: BusinessError) => {
  console.error(`AudioFrameworkRecLog: CapturerInfo :ERROR: ${err}`);
})

getCapturerInfoSync10+

getCapturerInfoSync(): AudioCapturerInfo

Obtains the capturer information of this AudioCapturer instance. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Capturer

Return value

TypeDescription
AudioCapturerInfoCapturer information.

Example

import { BusinessError } from '@ohos.base';

try {
  let audioParamsGet: audio.AudioCapturerInfo = audioCapturer.getCapturerInfoSync();
  console.info(`AudioFrameworkRecLog: Capturer SourceType: ${audioParamsGet.source}`);
  console.info(`AudioFrameworkRecLog: Capturer capturerFlags: ${audioParamsGet.capturerFlags}`);
} catch (err) {
  let error = err as BusinessError;
  console.error(`AudioFrameworkRecLog: CapturerInfo :ERROR: ${error}`);
}

getStreamInfo8+

getStreamInfo(callback: AsyncCallback<AudioStreamInfo>): void

Obtains the stream information of this AudioCapturer instance. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Capturer

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<AudioStreamInfo>YesCallback used to return the stream information.

Example

import { BusinessError } from '@ohos.base';
audioCapturer.getStreamInfo((err: BusinessError, streamInfo: audio.AudioStreamInfo) => {
  if (err) {
    console.error('Failed to get stream info');
  } else {
    console.info('Capturer GetStreamInfo:');
    console.info(`Capturer sampling rate: ${streamInfo.samplingRate}`);
    console.info(`Capturer channel: ${streamInfo.channels}`);
    console.info(`Capturer format: ${streamInfo.sampleFormat}`);
    console.info(`Capturer encoding type: ${streamInfo.encodingType}`);
  }
});

getStreamInfo8+

getStreamInfo(): Promise<AudioStreamInfo>

Obtains the stream information of this AudioCapturer instance. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Capturer

Return value

TypeDescription
Promise<AudioStreamInfo>Promise used to return the stream information.

Example

import { BusinessError } from '@ohos.base';
audioCapturer.getStreamInfo().then((audioParamsGet: audio.AudioStreamInfo) => {
  console.info('getStreamInfo:');
  console.info(`sampleFormat: ${audioParamsGet.sampleFormat}`);
  console.info(`samplingRate: ${audioParamsGet.samplingRate}`);
  console.info(`channels: ${audioParamsGet.channels}`);
  console.info(`encodingType: ${audioParamsGet.encodingType}`);
}).catch((err: BusinessError) => {
  console.error(`getStreamInfo :ERROR: ${err}`);
});

getStreamInfoSync10+

getStreamInfoSync(): AudioStreamInfo

Obtains the stream information of this AudioCapturer instance. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Capturer

Return value

TypeDescription
AudioStreamInfoStream information.

Example

import { BusinessError } from '@ohos.base';

try {
  let audioParamsGet: audio.AudioStreamInfo = audioCapturer.getStreamInfoSync();
  console.info(`sampleFormat: ${audioParamsGet.sampleFormat}`);
  console.info(`samplingRate: ${audioParamsGet.samplingRate}`);
  console.info(`channels: ${audioParamsGet.channels}`);
  console.info(`encodingType: ${audioParamsGet.encodingType}`);
} catch (err) {
  let error = err as BusinessError;
  console.error(`getStreamInfo :ERROR: ${error}`);
}

getAudioStreamId9+

getAudioStreamId(callback: AsyncCallback<number>): void

Obtains the stream ID of this AudioCapturer instance. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Capturer

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<number>YesCallback used to return the stream ID.

Example

import { BusinessError } from '@ohos.base';
audioCapturer.getAudioStreamId((err: BusinessError, streamid: number) => {
  console.info(`audioCapturer GetStreamId: ${streamid}`);
});

getAudioStreamId9+

getAudioStreamId(): Promise<number>

Obtains the stream ID of this AudioCapturer instance. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Capturer

Return value

TypeDescription
Promise<number>Promise used to return the stream ID.

Example

import { BusinessError } from '@ohos.base';
audioCapturer.getAudioStreamId().then((streamid: number) => {
  console.info(`audioCapturer getAudioStreamId: ${streamid}`);
}).catch((err: BusinessError) => {
  console.error(`ERROR: ${err}`);
});

getAudioStreamIdSync10+

getAudioStreamIdSync(): number

Obtains the stream ID of this AudioCapturer instance. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Capturer

Return value

TypeDescription
numberStream ID.

Example

import { BusinessError } from '@ohos.base';

try {
  let streamid: number = audioCapturer.getAudioStreamIdSync();
  console.info(`audioCapturer getAudioStreamIdSync: ${streamid}`);
} catch (err) {
  let error = err as BusinessError;
  console.error(`ERROR: ${error}`);
}

start8+

start(callback: AsyncCallback<void>): void

Starts capturing. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Capturer

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioCapturer.start((err: BusinessError) => {
  if (err) {
    console.error('Capturer start failed.');
  } else {
    console.info('Capturer start success.');
  }
});

start8+

start(): Promise<void>

Starts capturing. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Capturer

Return value

TypeDescription
Promise<void>Promise used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioCapturer.start().then(() => {
  console.info('AudioFrameworkRecLog: ---------START---------');
  console.info('AudioFrameworkRecLog: Capturer started: SUCCESS');
  console.info(`AudioFrameworkRecLog: AudioCapturer: STATE: ${audioCapturer.state}`);
  console.info('AudioFrameworkRecLog: Capturer started: SUCCESS');
  if ((audioCapturer.state == audio.AudioState.STATE_RUNNING)) {
    console.info('AudioFrameworkRecLog: AudioCapturer is in Running State');
  }
}).catch((err: BusinessError) => {
  console.info(`AudioFrameworkRecLog: Capturer start :ERROR : ${err}`);
});

stop8+

stop(callback: AsyncCallback<void>): void

Stops capturing. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Capturer

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioCapturer.stop((err: BusinessError) => {
  if (err) {
    console.error('Capturer stop failed');
  } else {
    console.info('Capturer stopped.');
  }
});

stop8+

stop(): Promise<void>

Stops capturing. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Capturer

Return value

TypeDescription
Promise<void>Promise used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioCapturer.stop().then(() => {
  console.info('AudioFrameworkRecLog: ---------STOP RECORD---------');
  console.info('AudioFrameworkRecLog: Capturer stopped: SUCCESS');
  if ((audioCapturer.state == audio.AudioState.STATE_STOPPED)){
    console.info('AudioFrameworkRecLog: State is Stopped:');
  }
}).catch((err: BusinessError) => {
  console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`);
});

release8+

release(callback: AsyncCallback<void>): void

Releases this AudioCapturer instance. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Capturer

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioCapturer.release((err: BusinessError) => {
  if (err) {
    console.error('capturer release failed');
  } else {
    console.info('capturer released.');
  }
});

release8+

release(): Promise<void>

Releases this AudioCapturer instance. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Capturer

Return value

TypeDescription
Promise<void>Promise used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioCapturer.release().then(() => {
  console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------');
  console.info('AudioFrameworkRecLog: Capturer release : SUCCESS');
  console.info(`AudioFrameworkRecLog: AudioCapturer : STATE : ${audioCapturer.state}`);
}).catch((err: BusinessError) => {
  console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`);
});

read8+

read(size: number, isBlockingRead: boolean, callback: AsyncCallback<ArrayBuffer>): void

Reads the buffer. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Capturer

Parameters

NameTypeMandatoryDescription
sizenumberYesNumber of bytes to read.
isBlockingReadbooleanYesWhether to block the read operation.
callbackAsyncCallback<ArrayBuffer>YesCallback used to return the buffer.

Example

import { BusinessError } from '@ohos.base';
let bufferSize: number = 0;
audioCapturer.getBufferSize().then((data: number) => {
  console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`);
  bufferSize = data;
}).catch((err: BusinessError) => {
  console.error(`AudioFrameworkRecLog: getBufferSize: ERROR: ${err}`);
});
audioCapturer.read(bufferSize, true, (err: BusinessError, buffer: number) => {
  if (!err) {
    console.info('Success in reading the buffer data');
  }
});

read8+

read(size: number, isBlockingRead: boolean): Promise<ArrayBuffer>

Reads the buffer. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Capturer

Parameters

NameTypeMandatoryDescription
sizenumberYesNumber of bytes to read.
isBlockingReadbooleanYesWhether to block the read operation.

Return value

TypeDescription
Promise<ArrayBuffer>Promise used to return the result. If the operation is successful, the buffer data read is returned; otherwise, an error code is returned.

Example

import { BusinessError } from '@ohos.base';
let bufferSize: number = 0;
audioCapturer.getBufferSize().then((data: number) => {
  console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`);
  bufferSize = data;
}).catch((err: BusinessError) => {
  console.info(`AudioFrameworkRecLog: getBufferSize: ERROR ${err}`);
});
console.info(`Buffer size: ${bufferSize}`);
audioCapturer.read(bufferSize, true).then((buffer: number) => {
  console.info('buffer read successfully');
}).catch((err: BusinessError) => {
  console.info(`ERROR : ${err}`);
});

getAudioTime8+

getAudioTime(callback: AsyncCallback<number>): void

Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Capturer

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<number>YesCallback used to return the result.

Example

import { BusinessError } from '@ohos.base';
audioCapturer.getAudioTime((err: BusinessError, timestamp: number) => {
  console.info(`Current timestamp: ${timestamp}`);
});

getAudioTime8+

getAudioTime(): Promise<number>

Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Capturer

Return value

TypeDescription
Promise<number>Promise used to return the timestamp.

Example

import { BusinessError } from '@ohos.base';
audioCapturer.getAudioTime().then((audioTime: number) => {
  console.info(`AudioFrameworkRecLog: AudioCapturer getAudioTime : Success ${audioTime}`);
}).catch((err: BusinessError) => {
  console.info(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`);
});

getAudioTimeSync10+

getAudioTimeSync(): number

Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Capturer

Return value

TypeDescription
numberTimestamp.

Example

import { BusinessError } from '@ohos.base';

try {
  let audioTime: number = audioCapturer.getAudioTimeSync();
  console.info(`AudioFrameworkRecLog: AudioCapturer getAudioTimeSync : Success ${audioTime}`);
} catch (err) {
  let error = err as BusinessError;
  console.info(`AudioFrameworkRecLog: AudioCapturer getAudioTimeSync : ERROR : ${error}`);
}

getBufferSize8+

getBufferSize(callback: AsyncCallback<number>): void

Obtains a reasonable minimum buffer size in bytes for capturing. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Multimedia.Audio.Capturer

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<number>YesCallback used to return the buffer size.

Example

import { BusinessError } from '@ohos.base';
audioCapturer.getBufferSize((err: BusinessError, bufferSize: number) => {
  if (!err) {
    console.info(`BufferSize : ${bufferSize}`);
    audioCapturer.read(bufferSize, true).then((buffer: number) => {
      console.info(`Buffer read is ${buffer}`);
    }).catch((err: BusinessError) => {
      console.error(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`);
    });
  }
});

getBufferSize8+

getBufferSize(): Promise<number>

Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a promise to return the result.

System capability: SystemCapability.Multimedia.Audio.Capturer

Return value

TypeDescription
Promise<number>Promise used to return the buffer size.

Example

import { BusinessError } from '@ohos.base';
let bufferSize: number = 0;
audioCapturer.getBufferSize().then((data: number) => {
  console.info(`AudioFrameworkRecLog: getBufferSize :SUCCESS ${data}`);
  bufferSize = data;
}).catch((err: BusinessError) => {
  console.info(`AudioFrameworkRecLog: getBufferSize :ERROR : ${err}`);
});

getBufferSizeSync10+

getBufferSizeSync(): number

Obtains a reasonable minimum buffer size in bytes for capturing. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Capturer

Return value

TypeDescription
numberBuffer size.

Example

import { BusinessError } from '@ohos.base';

let bufferSize: number = 0;
try {
  bufferSize = audioCapturer.getBufferSizeSync();
  console.info(`AudioFrameworkRecLog: getBufferSizeSync :SUCCESS ${bufferSize}`);
} catch (err) {
  let error = err as BusinessError;
  console.info(`AudioFrameworkRecLog: getBufferSizeSync :ERROR : ${error}`);
}

getCurrentInputDevices11+

getCurrentInputDevices(): AudioDeviceDescriptors

Obtains the descriptors of the current input devices. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Device

Return value

TypeDescription
AudioDeviceDescriptorsAn array of the audio device descriptors.

Example

let deviceDescriptors: audio.AudioDeviceDescriptors = audioCapturer.getCurrentInputDevices();
console.info(`Device id: ${deviceDescriptors[0].id}`);
console.info(`Device type: ${deviceDescriptors[0].deviceType}`);
console.info(`Device role: ${deviceDescriptors[0].deviceRole}`);
console.info(`Device name: ${deviceDescriptors[0].name}`);
console.info(`Device address: ${deviceDescriptors[0].address}`);
console.info(`Device samplerates: ${deviceDescriptors[0].sampleRates[0]}`);
console.info(`Device channelcounts: ${deviceDescriptors[0].channelCounts[0]}`);
console.info(`Device channelmask: ${deviceDescriptors[0].channelMasks[0]}`);
console.info(`Device encodingTypes: ${deviceDescriptors[0].encodingTypes[0]}`);

getCurrentAudioCapturerChangeInfo11+

getCurrentAudioCapturerChangeInfo(): AudioCapturerChangeInfo

Obtains the configuration changes of the current audio capturer. This API returns the result synchronously.

System capability: SystemCapability.Multimedia.Audio.Device

Return value

TypeDescription
AudioCapturerChangeInfoConfiguration changes of the audio capturer.

Example

let info: audio.AudioCapturerChangeInfo = audioCapturer.getCurrentAudioCapturerChangeInfo();
console.info(`Info streamId: ${info.streamId}`);
console.info(`Info source: ${info.capturerInfo.source}`);
console.info(`Info capturerFlags: ${info.capturerInfo.capturerFlags}`);
console.info(`Info capturerState: ${info.capturerState}`);
console.info(`Info muted: ${info.muted}`);
console.info(`Info type: ${info.deviceDescriptors[0].deviceType}`);
console.info(`Info role: ${info.deviceDescriptors[0].deviceRole}`);
console.info(`Info name: ${info.deviceDescriptors[0].name}`);
console.info(`Info address: ${info.deviceDescriptors[0].address}`);
console.info(`Info samplerates: ${info.deviceDescriptors[0].sampleRates[0]}`);
console.info(`Info channelcounts: ${info.deviceDescriptors[0].channelCounts[0]}`);
console.info(`Info channelmask: ${info.deviceDescriptors[0].channelMasks[0]}`);
console.info(`Info encodingTypes: ${info.deviceDescriptors[0].encodingTypes[0]}`);

on('audioInterrupt')10+

on(type: 'audioInterrupt', callback: Callback<InterruptEvent>): void

Subscribes to audio interruption events. This API uses a callback to obtain interrupt events.

Same as on('interrupt'), this API is used to listen for focus changes. The AudioCapturer instance proactively gains the focus when the start event occurs and releases the focus when the pause or stop event occurs. Therefore, you do not need to request to gain or release the focus.

System capability: SystemCapability.Multimedia.Audio.Interrupt

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The event 'audioInterrupt' is triggered when audio capturing is interrupted.
callbackCallback<InterruptEvent>YesCallback used to return the audio interruption event.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101if input parameter value error

Example

import audio from '@ohos.multimedia.audio';
let isCapturing: boolean; // An identifier specifying whether capturing is in progress.
onAudioInterrupt();

async function onAudioInterrupt(){
  audioCapturer.on('audioInterrupt', (interruptEvent: audio.InterruptEvent) => {
    if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) {
      // The system forcibly interrupts audio capturing. The application must update the status and displayed content accordingly.
      switch (interruptEvent.hintType) {
        case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
          // The audio stream has been paused and temporarily loses the focus. It will receive the interruptEvent corresponding to resume when it is able to regain the focus.
          console.info('Force paused. Update capturing status and stop reading');
          isCapturing = false; // A simplified processing indicating several operations for switching the application to the paused state.
          break;
        case audio.InterruptHint.INTERRUPT_HINT_STOP:
          // The audio stream has been stopped and permanently loses the focus. The user must manually trigger the operation to resume capturing.
          console.info('Force stopped. Update capturing status and stop reading');
          isCapturing = false; // A simplified processing indicating several operations for switching the application to the paused state.
          break;
        default:
          console.info('Invalid interruptEvent');
          break;
      }
    } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) {
      // The application can choose to take action or ignore.
      switch (interruptEvent.hintType) {
        case audio.InterruptHint.INTERRUPT_HINT_RESUME:
          // It is recommended that the application continue capturing. (The audio stream has been forcibly paused and temporarily lost the focus. It can resume capturing now.)
          console.info('Resume force paused renderer or ignore');
          // To continue capturing, the application must perform the required operations.
          break;
        case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
          // It is recommended that the application pause capturing.
          console.info('Choose to pause or ignore');
          // To pause capturing, the application must perform the required operations.
          break;
        case audio.InterruptHint.INTERRUPT_HINT_STOP:
          // It is recommended that the application stop capturing.
          console.info('Choose to stop or ignore');
          // To stop capturing, the application must perform the required operations.
          break;
        default:
          break;
      }
    }
  });
}

off('audioInterrupt')10+

off(type: 'audioInterrupt'): void

Unsubscribes from audio interruption events.

System capability: SystemCapability.Multimedia.Audio.Interrupt

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The event 'audioInterrupt' is triggered when audio capturing is interrupted.

Error codes

For details about the error codes, see Audio Error Codes.

IDError Message
6800101if input parameter value error

Example

audioCapturer.off('audioInterrupt');

on('inputDeviceChange')11+

on(type: 'inputDeviceChange', callback: Callback<AudioDeviceDescriptors>): void

Subscribes to audio input device change events.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The event 'inputDeviceChange' is triggered when the audio input device is changed.
callbackCallback<AudioDeviceDescriptors>YesCallback used to return the result.

Error codes

IDError Message
6800101Input parameter value error.

Example

audioCapturer.on('inputDeviceChange', (deviceChangeInfo: audio.AudioDeviceDescriptors) => {
  console.info(`inputDevice id: ${deviceChangeInfo[0].id}`);
  console.info(`inputDevice deviceRole: ${deviceChangeInfo[0].deviceRole}`);
  console.info(`inputDevice deviceType: ${deviceChangeInfo[0].deviceType}`);
});

off('inputDeviceChange')11+

off(type: 'inputDeviceChange', callback?: Callback<AudioDeviceDescriptors>): void

Unsubscribes from audio input device change events.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The event 'inputDeviceChange' is triggered when the audio input device is changed.
callbackCallback<AudioDeviceDescriptors>NoCallback used for unsubscription.

Error codes

IDError Message
6800101Input parameter value error.

Example

audioCapturer.off('inputDeviceChange');

on('audioCapturerChange')11+

on(type: 'audioCapturerChange', callback: Callback<AudioCapturerChangeInfo>): void

Subscribes to audio capturer change events.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The event 'audioCapturerChange' is triggered when the audio capturer is changed.
callbackCallback<AudioCapturerChangeInfo>YesCallback used to return the result.

Error codes

IDError Message
6800101Input parameter value error.

Example

audioCapturer.on('audioCapturerChange', (capturerChangeInfo: audio.AudioCapturerChangeInfo) => {
  console.info(`audioCapturerChange id: ${capturerChangeInfo[0].id}`);
  console.info(`audioCapturerChange deviceRole: ${capturerChangeInfo[0].deviceRole}`);
  console.info(`audioCapturerChange deviceType: ${capturerChangeInfo[0].deviceType}`);
});

off('audioCapturerChange')11+

off(type: 'audioCapturerChange', callback?: Callback<AudioCapturerChangeInfo>): void

Unsubscribes from audio capturer change events.

System capability: SystemCapability.Multimedia.Audio.Device

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The event 'audioCapturerChange' is triggered when the audio capturer is changed.
callbackCallback<AudioCapturerChangeInfo>NoCallback used for unsubscription.

Error codes

IDError Message
6800101Input parameter value error.

Example

audioCapturer.off('audioCapturerChange');

on('markReach')8+

on(type: 'markReach', frame: number, callback: Callback<number>): void

Subscribes to mark reached events. When the number of frames captured reaches the value of the frame parameter, a callback is invoked.

System capability: SystemCapability.Multimedia.Audio.Capturer

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is fixed at 'markReach'.
framenumberYesNumber of frames to trigger the event. The value must be greater than 0.
callbackCallback<number>YesCallback invoked when the event is triggered.

Example

audioCapturer.on('markReach', 1000, (position: number) => {
  if (position == 1000) {
    console.info('ON Triggered successfully');
  }
});

off('markReach')8+

off(type: 'markReach'): void

Unsubscribes from mark reached events.

System capability: SystemCapability.Multimedia.Audio.Capturer

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is fixed at 'markReach'.

Example

audioCapturer.off('markReach');

on('periodReach')8+

on(type: 'periodReach', frame: number, callback: Callback<number>): void

Subscribes to period reached events. When the number of frames captured reaches the value of the frame parameter, a callback is triggered and the specified value is returned.

System capability: SystemCapability.Multimedia.Audio.Capturer

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is fixed at 'periodReach'.
framenumberYesNumber of frames to trigger the event. The value must be greater than 0.
callbackCallback<number>YesCallback invoked when the event is triggered.

Example

audioCapturer.on('periodReach', 1000, (position: number) => {
  if (position == 1000) {
    console.info('ON Triggered successfully');
  }
});

off('periodReach')8+

off(type: 'periodReach'): void

Unsubscribes from period reached events.

System capability: SystemCapability.Multimedia.Audio.Capturer

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value is fixed at 'periodReach'.

Example

audioCapturer.off('periodReach')

on('stateChange')8+

on(type: 'stateChange', callback: Callback<AudioState>): void

Subscribes to state change events.

System capability: SystemCapability.Multimedia.Audio.Capturer

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value stateChange means the state change event.
callbackCallback<AudioState>YesCallback used to return the state change.

Example

audioCapturer.on('stateChange', (state: audio.AudioState) => {
  if (state == 1) {
    console.info('audio capturer state is: STATE_PREPARED');
  }
  if (state == 2) {
    console.info('audio capturer state is: STATE_RUNNING');
  }
});

ToneType9+

Enumerates the tone types of the player.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Tone

NameValueDescription
TONE_TYPE_DIAL_00DTMF tone of key 0.
TONE_TYPE_DIAL_11DTMF tone of key 1.
TONE_TYPE_DIAL_22DTMF tone of key 2.
TONE_TYPE_DIAL_33DTMF tone of key 3.
TONE_TYPE_DIAL_44DTMF tone of key 4.
TONE_TYPE_DIAL_55DTMF tone of key 5.
TONE_TYPE_DIAL_66DTMF tone of key 6.
TONE_TYPE_DIAL_77DTMF tone of key 7.
TONE_TYPE_DIAL_88DTMF tone of key 8.
TONE_TYPE_DIAL_99DTMF tone of key 9.
TONE_TYPE_DIAL_S10DTMF tone of the star key (*).
TONE_TYPE_DIAL_P11DTMF tone of the pound key (#).
TONE_TYPE_DIAL_A12DTMF tone of key A.
TONE_TYPE_DIAL_B13DTMF tone of key B.
TONE_TYPE_DIAL_C14DTMF tone of key C.
TONE_TYPE_DIAL_D15DTMF tone of key D.
TONE_TYPE_COMMON_SUPERVISORY_DIAL100Supervisory tone - dial tone.
TONE_TYPE_COMMON_SUPERVISORY_BUSY101Supervisory tone - busy.
TONE_TYPE_COMMON_SUPERVISORY_CONGESTION102Supervisory tone - congestion.
TONE_TYPE_COMMON_SUPERVISORY_RADIO_ACK103Supervisory tone - radio path acknowledgment.
TONE_TYPE_COMMON_SUPERVISORY_RADIO_NOT_AVAILABLE104Supervisory tone - radio path not available.
TONE_TYPE_COMMON_SUPERVISORY_CALL_WAITING106Supervisory tone - call waiting tone.
TONE_TYPE_COMMON_SUPERVISORY_RINGTONE107Supervisory tone - ringing tone.
TONE_TYPE_COMMON_PROPRIETARY_BEEP200Proprietary tone - beep tone.
TONE_TYPE_COMMON_PROPRIETARY_ACK201Proprietary tone - ACK.
TONE_TYPE_COMMON_PROPRIETARY_PROMPT203Proprietary tone - PROMPT.
TONE_TYPE_COMMON_PROPRIETARY_DOUBLE_BEEP204Proprietary tone - double beep tone.

TonePlayer9+

Provides APIs for playing and managing DTMF tones, such as dial tones, ringback tones, supervisory tones, and proprietary tones.

System API: This is a system API.

load9+

load(type: ToneType, callback: AsyncCallback<void>): void

Loads the DTMF tone configuration. This API uses an asynchronous callback to return the result.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Tone

Parameters

NameTypeMandatoryDescription
typeToneTypeYesTone type.
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import { BusinessError } from '@ohos.base';
tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_5, (err: BusinessError) => {
  if (err) {
    console.error(`callback call load failed error: ${err.message}`);
    return;
  } else {
    console.info('callback call load success');
  }
});

load9+

load(type: ToneType): Promise<void>

Loads the DTMF tone configuration. This API uses a promise to return the result.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Tone

Parameters

NameTypeMandatoryDescription
typeToneTypeYesTone type.

Return value

TypeDescription
Promise<void>Promise used to return the result.

Example

tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_1).then(() => {
  console.info('promise call load ');
}).catch(() => {
  console.error('promise call load fail');
});

start9+

start(callback: AsyncCallback<void>): void

Starts DTMF tone playing. This API uses an asynchronous callback to return the result.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Tone

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import { BusinessError } from '@ohos.base';
tonePlayer.start((err: BusinessError) => {
  if (err) {
    console.error(`callback call start failed error: ${err.message}`);
    return;
  } else {
    console.info('callback call start success');
  }
});

start9+

start(): Promise<void>

Starts DTMF tone playing. This API uses a promise to return the result.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Tone

Return value

TypeDescription
Promise<void>Promise used to return the result.

Example

tonePlayer.start().then(() => {
  console.info('promise call start');
}).catch(() => {
  console.error('promise call start fail');
});

stop9+

stop(callback: AsyncCallback<void>): void

Stops the tone that is being played. This API uses an asynchronous callback to return the result.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Tone

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import { BusinessError } from '@ohos.base';
tonePlayer.stop((err: BusinessError) => {
  if (err) {
    console.error(`callback call stop error: ${err.message}`);
    return;
  } else {
    console.error('callback call stop success ');
  }
});

stop9+

stop(): Promise<void>

Stops the tone that is being played. This API uses a promise to return the result.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Tone

Return value

TypeDescription
Promise<void>Promise used to return the result.

Example

tonePlayer.stop().then(() => {
  console.info('promise call stop finish');
}).catch(() => {
  console.error('promise call stop fail');
});

release9+

release(callback: AsyncCallback<void>): void

Releases the resources associated with the TonePlayer instance. This API uses an asynchronous callback to return the result.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Tone

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<void>YesCallback used to return the result.

Example

import { BusinessError } from '@ohos.base';
tonePlayer.release((err: BusinessError) => {
  if (err) {
    console.error(`callback call release failed error: ${err.message}`);
    return;
  } else {
    console.info('callback call release success ');
  }
});

release9+

release(): Promise<void>

Releases the resources associated with the TonePlayer instance. This API uses a promise to return the result.

System API: This is a system API.

System capability: SystemCapability.Multimedia.Audio.Tone

Return value

TypeDescription
Promise<void>Promise used to return the result.

Example

tonePlayer.release().then(() => {
  console.info('promise call release');
}).catch(() => {
  console.error('promise call release fail');
});

ActiveDeviceType(deprecated)

Enumerates the active device types.

NOTE

This API is deprecated since API version 9. You are advised to use CommunicationDeviceType instead.

System capability: SystemCapability.Multimedia.Audio.Device

NameValueDescription
SPEAKER2Speaker.
BLUETOOTH_SCO7Bluetooth device using Synchronous Connection Oriented (SCO) links.

InterruptActionType(deprecated)

Enumerates the returned event types for audio interruption events.

NOTE

This API is supported since API version 7 and deprecated since API version 9.

System capability: SystemCapability.Multimedia.Audio.Renderer

NameValueDescription
TYPE_ACTIVATED0Focus gain event.
TYPE_INTERRUPT1Audio interruption event.

AudioInterrupt(deprecated)

Describes input parameters of audio interruption events.

NOTE

This API is supported since API version 7 and deprecated since API version 9.

System capability: SystemCapability.Multimedia.Audio.Renderer

NameTypeMandatoryDescription
streamUsageStreamUsageYesAudio stream usage.
contentTypeContentTypeYesAudio content type.
pauseWhenDuckedbooleanYesWhether audio playback can be paused during audio interruption. The value true means that audio playback can be paused during audio interruption, and false means the opposite.

InterruptAction(deprecated)

Describes the callback invoked for audio interruption or focus gain events.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use InterruptEvent.

System capability: SystemCapability.Multimedia.Audio.Renderer

NameTypeMandatoryDescription
actionTypeInterruptActionTypeYesReturned event type. The value TYPE_ACTIVATED means the focus gain event, and TYPE_INTERRUPT means the audio interruption event.
typeInterruptTypeNoType of the audio interruption event.
hintInterruptHintNoHint provided along with the audio interruption event.
activatedbooleanNoWhether the focus is gained or released. The value true means that the focus is gained or released, and false means that the focus fails to be gained or released.

你可能感兴趣的鸿蒙文章

harmony 鸿蒙APIs

harmony 鸿蒙System Common Events (To Be Deprecated Soon)

harmony 鸿蒙System Common Events

harmony 鸿蒙API Reference Document Description

harmony 鸿蒙Enterprise Device Management Overview (for System Applications Only)

harmony 鸿蒙BundleStatusCallback

harmony 鸿蒙@ohos.bundle.innerBundleManager (innerBundleManager)

harmony 鸿蒙@ohos.distributedBundle (Distributed Bundle Management)

harmony 鸿蒙@ohos.bundle (Bundle)

harmony 鸿蒙@ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)

  • 所属分类: 后端技术
  • 本文标签: 软件 鸿蒙
  • 版权声明: 本文链接 https://seaxiang.com/blog/d35d7ccbc1744828896523571f5e18b0