HarmonyOS实战开发:@ohos.multimedia.audio (音频管理)

音频管理提供管理音频的一些基础能力,包括对音频音量、音频设备的管理,以及对音频数据的采集和渲染等。

该模块提供以下音频相关的常用功能:

  • AudioManager:音频管理。
  • AudioRenderer:音频渲染,用于播放PCM(Pulse Code Modulation)音频数据。
  • AudioCapturer:音频采集,用于录制PCM音频数据。
  • TonePlayer:用于管理和播放DTMF(Dual Tone Multi Frequency,双音多频)音调,如拨号音、通话回铃音等。

说明: 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。

导入模块

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

常量

名称类型可读可写说明
LOCAL_NETWORK_ID9+字符串本地设备网络id。
此接口为系统接口。
系统能力: SystemCapability.Multimedia.Audio.Device
DEFAULT_VOLUME_GROUP_ID9+默认音量组id。
系统能力: SystemCapability.Multimedia.Audio.Volume
DEFAULT_INTERRUPT_GROUP_ID9+默认音频中断组id。
系统能力: SystemCapability.Multimedia.Audio.Interrupt

示例:

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

获取音频管理器。

系统能力: SystemCapability.Multimedia.Audio.Core

返回值:

类型说明
AudioManager音频管理对象。

示例:

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

let audioManager = audio.getAudioManager();

audio.createAudioRenderer8+

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

获取音频渲染器。使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
选项AudioRendererOptions配置渲染器。
回调AsyncCallback<AudioRenderer>回调函数。当获取音频渲染器成功,err为undefined,data为获取到的音频渲染器对象;否则为错误对象。

示例:

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 = {
  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>

获取音频渲染器。使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
选项AudioRendererOptions配置渲染器。

返回值:

类型说明
Promise<AudioRenderer>Promise对象,返回音频渲染器对象。

示例:

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 = {
  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

获取音频采集器。使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

需要权限: ohos.permission.MICROPHONE

仅设置Mic音频源(即SourceType为SOURCE_TYPE_MIC)时需要该权限。

参数:

参数名类型必填说明
选项AudioCapturerOptions配置音频采集器。
回调AsyncCallback<AudioCapturer>回调函数。当获取音频采集器成功,err为undefined,data为获取到的音频采集器对象;否则为错误对象。

示例:

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>

获取音频采集器。使用Promise 方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

需要权限: ohos.permission.MICROPHONE

仅设置Mic音频源(即SourceType为SOURCE_TYPE_MIC)时需要该权限。

参数:

参数名类型必填说明
optionsAudioCapturerOptions配置音频采集器。

返回值:

类型说明
Promise<AudioCapturer>Promise对象,返回音频采集器对象。

示例:

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

创建DTMF播放器。使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Tone

系统接口: 该接口为系统接口

参数:

参数名类型必填说明
optionsAudioRendererInfo配置音频渲染器信息。
回调AsyncCallback<TonePlayer>回调函数。当获取DTMF播放器成功,err为undefined,data为获取到的DTMF播放器对象;否则为错误对象。

示例:

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>

创建DTMF播放器。使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Tone

系统接口: 该接口为系统接口

参数:

参数名类型必填说明
选项AudioRendererInfo配置音频渲染器信息。

返回值:

类型说明
Promise<TonePlayer>Promise对象,返回DTMF播放器对象。

示例:

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

枚举,音频流类型。

系统能力: SystemCapability.Multimedia.Audio.Volume

名称说明
VOICE_CALL8+0语音电话。
RINGTONE2铃声。
MEDIA3媒体。
ALARM10+4闹钟。
ACCESSIBILITY10+5无障碍。
VOICE_ASSISTANT8+9语音助手。
ULTRASONIC10+10超声波。
此接口为系统接口。
ALL9+100所有公共音频流。
此接口为系统接口。

InterruptRequestResultType9+

枚举,音频中断请求结果类型。

系统能力: SystemCapability.Multimedia.Audio.Interrupt

系统接口: 该接口为系统接口

名称说明
INTERRUPT_REQUEST_GRANT0请求音频中断成功。
INTERRUPT_REQUEST_REJECT1请求音频中断失败,可能具有较高优先级类型。

InterruptMode9+

枚举,焦点模型。

系统能力: SystemCapability.Multimedia.Audio.Interrupt

名称说明
SHARE_MODE0共享焦点模式。
INDEPENDENT_MODE1独立焦点模式。

DeviceFlag

枚举,可获取的设备种类。

系统能力: SystemCapability.Multimedia.Audio.Device

名称说明
NONE_DEVICES_FLAG9+0无设备。
此接口为系统接口。
OUTPUT_DEVICES_FLAG1输出设备。
INPUT_DEVICES_FLAG2输入设备。
ALL_DEVICES_FLAG3所有设备。
DISTRIBUTED_OUTPUT_DEVICES_FLAG9+4分布式输出设备。
此接口为系统接口。
DISTRIBUTED_INPUT_DEVICES_FLAG9+8分布式输入设备。
此接口为系统接口。
ALL_DISTRIBUTED_DEVICES_FLAG9+12分布式输入和输出设备。
此接口为系统接口。

DeviceRole

枚举,设备角色。

系统能力: SystemCapability.Multimedia.Audio.Device

名称说明
INPUT_DEVICE1输入设备角色。
OUTPUT_DEVICE2输出设备角色。

DeviceType

枚举,设备类型。

系统能力: SystemCapability.Multimedia.Audio.Device

名称说明
INVALID0无效设备。
EARPIECE1听筒。
SPEAKER2扬声器。
WIRED_HEADSET3有线耳机,带麦克风。
WIRED_HEADPHONES4有线耳机,无麦克风。
BLUETOOTH_SCO7蓝牙设备SCO(Synchronous Connection Oriented)连接。
BLUETOOTH_A2DP8蓝牙设备A2DP(Advanced Audio Distribution Profile)连接。
MIC15麦克风。
USB_HEADSET22USB耳机,带麦克风。
DEFAULT9+1000默认设备类型。

CommunicationDeviceType9+

枚举,用于通信的可用设备类型。

系统能力: SystemCapability.Multimedia.Audio.Communication

名称说明
SPEAKER2扬声器。

AudioRingMode

枚举,铃声模式。

系统能力: SystemCapability.Multimedia.Audio.Communication

名称说明
RINGER_MODE_SILENT0静音模式。
RINGER_MODE_VIBRATE1震动模式。
RINGER_MODE_NORMAL2响铃模式。

AudioSampleFormat8+

枚举,音频采样格式。

系统能力: SystemCapability.Multimedia.Audio.Core

名称说明
SAMPLE_FORMAT_INVALID-1无效格式。
SAMPLE_FORMAT_U80无符号8位整数。
SAMPLE_FORMAT_S16LE1带符号的16位整数,小尾数。
SAMPLE_FORMAT_S24LE2带符号的24位整数,小尾数。
由于系统限制,该采样格式仅部分设备支持,请根据实际情况使用。
SAMPLE_FORMAT_S32LE3带符号的32位整数,小尾数。
由于系统限制,该采样格式仅部分设备支持,请根据实际情况使用。
SAMPLE_FORMAT_F32LE9+4带符号的32位浮点数,小尾数。
由于系统限制,该采样格式仅部分设备支持,请根据实际情况使用。

AudioErrors9+

枚举,音频错误码。

系统能力: SystemCapability.Multimedia.Audio.Core

名称说明
ERROR_INVALID_PARAM6800101无效入参。
ERROR_NO_MEMORY6800102分配内存失败。
ERROR_ILLEGAL_STATE6800103状态不支持。
ERROR_UNSUPPORTED6800104参数选项不支持。
ERROR_TIMEOUT6800105处理超时。
ERROR_STREAM_LIMIT6800201音频流数量达到限制。
ERROR_SYSTEM6800301系统处理异常。

AudioChannel8+

枚举, 音频声道。

系统能力: SystemCapability.Multimedia.Audio.Core

名称说明
CHANNEL_10x1 << 0单声道。
CHANNEL_20x1 << 1双声道。

AudioSamplingRate8+

枚举,音频采样率,具体设备支持的采样率规格会存在差异。

系统能力: SystemCapability.Multimedia.Audio.Core

名称说明
SAMPLE_RATE_80008000采样率为8000。
SAMPLE_RATE_1102511025采样率为11025。
SAMPLE_RATE_1200012000采样率为12000。
SAMPLE_RATE_1600016000采样率为16000。
SAMPLE_RATE_2205022050采样率为22050。
SAMPLE_RATE_2400024000采样率为24000。
SAMPLE_RATE_3200032000采样率为32000。
SAMPLE_RATE_4410044100采样率为44100。
SAMPLE_RATE_4800048000采样率为48000。
SAMPLE_RATE_6400064000采样率为64000。
SAMPLE_RATE_9600096000采样率为96000。

AudioEncodingType8+

枚举,音频编码类型。

系统能力: SystemCapability.Multimedia.Audio.Core

名称说明
ENCODING_TYPE_INVALID-1无效。
ENCODING_TYPE_RAW0PCM编码。

ContentType(deprecated)

枚举,音频内容类型。

说明: 从 API version 7 开始支持,从 API version 10 开始废弃。建议使用StreamUsage替代。

系统能力: SystemCapability.Multimedia.Audio.Core

名称说明
CONTENT_TYPE_UNKNOWN0未知类型。
CONTENT_TYPE_SPEECH1语音。
CONTENT_TYPE_MUSIC2音乐。
CONTENT_TYPE_MOVIE3电影。
CONTENT_TYPE_SONIFICATION4通知音。
CONTENT_TYPE_RINGTONE8+5铃声。

StreamUsage

枚举,音频流使用类型。

系统能力: SystemCapability.Multimedia.Audio.Core

名称说明
STREAM_USAGE_UNKNOWN0未知类型。
STREAM_USAGE_MEDIA(deprecated)1媒体。
从API version 7开始支持,从API version 10 开始废弃。建议使用该枚举中的STREAM_USAGE_MUSIC、STREAM_USAGE_MOVIE、STREAM_USAGE_GAME或STREAM_USAGE_AUDIOBOOK替代。
STREAM_USAGE_MUSIC10+1音乐。
STREAM_USAGE_VOICE_COMMUNICATION2语音通信。
STREAM_USAGE_VOICE_ASSISTANT9+3语音播报。
STREAM_USAGE_ALARM10+4闹钟。
STREAM_USAGE_VOICE_MESSAGE10+5语音消息。
STREAM_USAGE_NOTIFICATION_RINGTONE(deprecated)6通知铃声。
从 API version 10 开始废弃。建议使用该枚举中的STREAM_USAGE_RINGTONE替代。
STREAM_USAGE_RINGTONE10+6铃声。
STREAM_USAGE_NOTIFICATION10+7通知。
STREAM_USAGE_ACCESSIBILITY10+8无障碍。
STREAM_USAGE_SYSTEM10+9系统音(如屏幕锁定或按键音)。
此接口为系统接口。
STREAM_USAGE_MOVIE10+10电影或视频。
STREAM_USAGE_GAME10+11游戏音效。
STREAM_USAGE_AUDIOBOOK10+12有声读物。
STREAM_USAGE_NAVIGATION10+13导航。
STREAM_USAGE_DTMF10+14拨号音。
此接口为系统接口。
STREAM_USAGE_ENFORCED_TONE10+15强制音(如相机快门音)。
此接口为系统接口。
STREAM_USAGE_ULTRASONIC10+16超声波。
此接口为系统接口。

InterruptRequestType9+

枚举,音频中断请求类型。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Interrupt

名称说明
INTERRUPT_REQUEST_TYPE_DEFAULT0默认类型,可中断音频请求。

AudioState8+

枚举,音频状态。

系统能力: SystemCapability.Multimedia.Audio.Core

名称说明
STATE_INVALID-1无效状态。
STATE_NEW0创建新实例状态。
STATE_PREPARED1准备状态。
STATE_RUNNING2运行状态。
STATE_STOPPED3停止状态。
STATE_RELEASED4释放状态。
STATE_PAUSED5暂停状态。

AudioEffectMode10+

枚举,音效模式。

系统能力: SystemCapability.Multimedia.Audio.Renderer

名称说明
EFFECT_NONE0关闭音效。
EFFECT_DEFAULT1默认音效。

AudioRendererRate8+

枚举,音频渲染速度。

系统能力: SystemCapability.Multimedia.Audio.Renderer

名称说明
RENDER_RATE_NORMAL0正常速度。
RENDER_RATE_DOUBLE12倍速。
RENDER_RATE_HALF20.5倍数。

InterruptType

枚举,中断类型。

系统能力: SystemCapability.Multimedia.Audio.Renderer

名称说明
INTERRUPT_TYPE_BEGIN1音频播放中断事件开始。
INTERRUPT_TYPE_END2音频播放中断事件结束。

InterruptForceType9+

枚举,强制打断类型。

系统能力: SystemCapability.Multimedia.Audio.Renderer

名称说明
INTERRUPT_FORCE0由系统进行操作,强制打断音频播放。
INTERRUPT_SHARE1由应用进行操作,可以选择打断或忽略。

InterruptHint

枚举,中断提示。

系统能力: SystemCapability.Multimedia.Audio.Renderer

名称说明
INTERRUPT_HINT_NONE8+0无提示。
INTERRUPT_HINT_RESUME1提示音频恢复。
INTERRUPT_HINT_PAUSE2提示音频暂停。
INTERRUPT_HINT_STOP3提示音频停止。
INTERRUPT_HINT_DUCK4提示音频躲避。(躲避:音量减弱,而不会停止)
INTERRUPT_HINT_UNDUCK8+5提示音量恢复。

AudioStreamInfo8+

音频流信息。

系统能力: SystemCapability.Multimedia.Audio.Core

名称类型必填说明
samplingRateAudioSamplingRate音频文件的采样率。
channelsAudioChannel音频文件的通道数。
sampleFormatAudioSampleFormat音频采样格式。
encodingTypeAudioEncodingType音频编码格式。

AudioRendererInfo8+

音频渲染器信息。

系统能力: SystemCapability.Multimedia.Audio.Core

名称类型必填说明
contentContentType音频内容类型。
API version 8、9为必填参数,从API version 10开始,变更为可选参数。
usageStreamUsage音频流使用类型。
rendererFlagsnumber音频渲染器标志。
0代表普通音频渲染器,1代表低时延音频渲染器。js接口暂不支持低时延音频渲染器。

InterruptResult9+

音频中断结果。

系统能力: SystemCapability.Multimedia.Audio.Interrupt

系统接口: 该接口为系统接口

名称类型必填说明
requestResultInterruptRequestResultType表示音频请求中断类型。
interruptNodenumber音频请求中断的节点。

AudioRendererOptions8+

音频渲染器选项信息。

名称类型必填说明
streamInfoAudioStreamInfo表示音频流信息。
系统能力: SystemCapability.Multimedia.Audio.Renderer
rendererInfoAudioRendererInfo表示渲染器信息。
系统能力: SystemCapability.Multimedia.Audio.Renderer
privacyType10+AudioPrivacyType表示音频流是否可以被其他应用录制,默认值为0。
系统能力: SystemCapability.Multimedia.Audio.PlaybackCapture

AudioPrivacyType10+

枚举类型,用于标识对应播放音频流是否支持被其他应用录制。

系统能力: SystemCapability.Multimedia.Audio.PlaybackCapture

名称说明
PRIVACY_TYPE_PUBLIC0表示音频流可以被其他应用录制。
PRIVACY_TYPE_PRIVATE1表示音频流不可以被其他应用录制。

InterruptEvent9+

播放中断时,应用接收的中断事件。

系统能力: SystemCapability.Multimedia.Audio.Renderer

名称类型必填说明
eventTypeInterruptType中断事件类型,开始或是结束。
forceTypeInterruptForceType操作是由系统执行或是由应用程序执行。
hintTypeInterruptHint中断提示。

VolumeEvent9+

音量改变时,应用接收的事件。

系统能力: SystemCapability.Multimedia.Audio.Volume

名称类型必填说明
volumeTypeAudioVolumeType音量流类型。
volumenumber音量等级,可设置范围通过getMinVolume和getMaxVolume获取。
updateUiboolean在UI中显示音量变化,true为显示,false为不显示。
volumeGroupIdnumber音量组id。可用于getGroupManager入参。
此接口为系统接口。
networkIdstring网络id。
此接口为系统接口。

MicStateChangeEvent9+

麦克风状态变化时,应用接收的事件。

系统能力: SystemCapability.Multimedia.Audio.Device

名称类型必填说明
muteboolean回调返回系统麦克风静音状态,true为静音,false为非静音。

ConnectType9+

枚举,设备连接类型。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Volume

名称说明
CONNECT_TYPE_LOCAL1本地设备。
CONNECT_TYPE_DISTRIBUTED2分布式设备。

VolumeGroupInfos9+

音量组信息,数组类型,为VolumeGroupInfo的数组,只读。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Volume

VolumeGroupInfo9+

音量组信息。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Volume

名称类型可读可写说明
networkId9+string组网络id。
groupId9+number组设备组id。
mappingId9+number组映射id。
groupName9+string组名。
type9+ConnectType连接设备类型。

DeviceChangeAction

描述设备连接状态变化和设备信息。

系统能力: SystemCapability.Multimedia.Audio.Device

名称类型必填说明
typeDeviceChangeType设备连接状态变化。
deviceDescriptorsAudioDeviceDescriptors设备信息。

DeviceChangeType

枚举,设备连接状态变化。

系统能力: SystemCapability.Multimedia.Audio.Device

名称说明
CONNECT0设备连接。
DISCONNECT1断开设备连接。

AudioCapturerOptions8+

音频采集器选项信息。

名称类型必填说明
streamInfoAudioStreamInfo表示音频流信息。
系统能力: SystemCapability.Multimedia.Audio.Capturer
capturerInfoAudioCapturerInfo表示采集器信息。
系统能力: SystemCapability.Multimedia.Audio.Capturer
playbackCaptureConfig10+AudioPlaybackCaptureConfig音频内录的配置信息。
系统能力: SystemCapability.Multimedia.Audio.PlaybackCapture

AudioCapturerInfo8+

描述音频采集器信息。

系统能力: SystemCapability.Multimedia.Audio.Core

名称类型必填说明
SourceType音源类型。
capturerFlags音频采集器标志。

SourceType8+

枚举,音源类型。

名称说明
SOURCE_TYPE_INVALID-1无效的音频源。
系统能力: SystemCapability.Multimedia.Audio.Core
SOURCE_TYPE_MIC0Mic音频源。
系统能力: SystemCapability.Multimedia.Audio.Core
SOURCE_TYPE_VOICE_RECOGNITION9+1语音识别源。
系统能力: SystemCapability.Multimedia.Audio.Core
SOURCE_TYPE_PLAYBACK_CAPTURE10+2播放音频流(内录)录制音频源。
系统能力: SystemCapability.Multimedia.Audio.PlaybackCapture
SOURCE_TYPE_WAKEUP 10+3语音唤醒音频流录制音频源。
系统能力: SystemCapability.Multimedia.Audio.Core
需要权限: ohos.permission.MANAGE_INTELLIGENT_VOICE
此接口为系统接口
SOURCE_TYPE_VOICE_COMMUNICATION7语音通话场景的音频源。
系统能力: SystemCapability.Multimedia.Audio.Core

AudioPlaybackCaptureConfig10+

播放音频流录制(内录)的配置信息。

系统能力: SystemCapability.Multimedia.Audio.PlaybackCapture

名称类型必填说明
filterOptionsCaptureFilterOptions需要录制的播放音频流的筛选信息。

CaptureFilterOptions10+

待录制的播放音频流的筛选信息。

需要权限: ohos.permission.CAPTURE_VOICE_DOWNLINK_AUDIO

当应用指定录制的StreamUsage值中包含SOURCE_TYPE_VOICE_COMMUNICATION的播放音频流时,需要校验应用是否拥有该权限。

系统能力: SystemCapability.Multimedia.Audio.PlaybackCapture

名称类型必填说明
usagesArray<StreamUsage>指定需要录制的播放音频流的StreamUsage类型。可同时指定0个或多个StreamUsage。Array为空时,默认录制StreamUsage为STREAM_USAGE_MEDIA的播放音频流。

AudioScene8+

枚举,音频场景。

系统能力: SystemCapability.Multimedia.Audio.Communication

名称说明
AUDIO_SCENE_DEFAULT0默认音频场景。
AUDIO_SCENE_RINGING1响铃模式。
此接口为系统接口。
AUDIO_SCENE_PHONE_CALL2电话模式。
此接口为系统接口。
AUDIO_SCENE_VOICE_CHAT3语音聊天模式。

VolumeAdjustType10+

枚举,音量调节类型。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Volume

名称说明
VOLUME_UP0向上调节音量。
此接口为系统接口。
VOLUME_DOWN1向下调节音量。
此接口为系统接口。

AudioManager

管理音频音量和音频设备。在调用AudioManager的接口前,需要先通过getAudioManager创建实例。

setAudioParameter

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

音频参数设置,使用callback方式异步返回结果。

本接口的使用场景为根据硬件设备支持能力扩展音频配置。在不同的设备平台上,所支持的音频参数会存在差异。示例代码内使用样例参数,实际支持的音频配置参数见具体设备平台的资料描述。

需要权限: ohos.permission.MODIFY_AUDIO_SETTINGS

系统能力: SystemCapability.Multimedia.Audio.Core

参数:

参数名类型必填说明
keystring被设置的音频参数的键。
valuestring被设置的音频参数的值。
callbackAsyncCallback<void>回调函数。当音频参数设置成功,err为undefined,否则为错误对象。

示例:

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>

音频参数设置,使用Promise方式异步返回结果。

本接口的使用场景为根据硬件设备支持能力扩展音频配置。在不同的设备平台上,所支持的音频参数会存在差异。示例代码内使用样例参数,实际支持的音频配置参数见具体设备平台的资料描述。

需要权限: ohos.permission.MODIFY_AUDIO_SETTINGS

系统能力: SystemCapability.Multimedia.Audio.Core

参数:

参数名类型必填说明
keystring被设置的音频参数的键。
valuestring被设置的音频参数的值。

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

示例:

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

获取指定音频参数值,使用callback方式异步返回结果。

本接口的使用场景为根据硬件设备支持能力扩展音频配置。在不同的设备平台上,所支持的音频参数会存在差异。示例代码内使用样例参数,实际支持的音频配置参数见具体设备平台的资料描述。

系统能力: SystemCapability.Multimedia.Audio.Core

参数:

参数名类型必填说明
keystring待获取的音频参数的键。
callbackAsyncCallback<string>回调函数。当获取指定音频参数值成功,err为undefined,data为获取到的指定音频参数值;否则为错误对象。

示例:

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>

获取指定音频参数值,使用Promise方式异步返回结果。

本接口的使用场景为根据硬件设备支持能力扩展音频配置。在不同的设备平台上,所支持的音频参数会存在差异。示例代码内使用样例参数,实际支持的音频配置参数见具体设备平台的资料描述。

系统能力: SystemCapability.Multimedia.Audio.Core

参数:

参数名类型必填说明
key字符串待获取的音频参数的键。

返回值:

类型说明
Promise<string>Promise对象,返回获取的音频参数的值。

示例:

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

设置音频场景模式,使用callback方式异步返回结果。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Communication

参数:

参数名类型必填说明
现场AudioScene音频场景模式。
回调AsyncCallback<void>回调函数。当设置音频场景模式成功,err为undefined,否则为错误对象。

示例:

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>

设置音频场景模式,使用Promise方式返回异步结果。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Communication

参数:

参数名类型必填说明
sceneAudioScene音频场景模式。

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

示例:

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

获取音频场景模式,使用callback方式返回异步结果。

系统能力: SystemCapability.Multimedia.Audio.Communication

参数:

参数名类型必填说明
callbackAsyncCallback<AudioScene>回调函数。当获取音频场景模式成功,err为undefined,data为获取到的音频场景模式;否则为错误对象。

示例:

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>

获取音频场景模式,使用Promise方式返回异步结果。

系统能力: SystemCapability.Multimedia.Audio.Communication

返回值:

类型说明
Promise<AudioScene>Promise对象,返回音频场景模式。

示例:

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

获取音频场景模式,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Communication

返回值:

类型说明
AudioScene音频场景模式。

示例:

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

获取音频音量管理器。

系统能力: SystemCapability.Multimedia.Audio.Volume

返回值:

类型说明
AudioVolumeManagerAudioVolumeManager实例

示例:

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

let audioVolumeManager: audio.AudioVolumeManager = audioManager.getVolumeManager();

getStreamManager9+

getStreamManager(): AudioStreamManager

获取音频流管理器。

系统能力: SystemCapability.Multimedia.Audio.Core

返回值:

类型说明
AudioStreamManagerAudioStreamManager实例

示例:

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

let audioStreamManager: audio.AudioStreamManager = audioManager.getStreamManager();

getRoutingManager9+

getRoutingManager(): AudioRoutingManager

获取音频路由设备管理器。

系统能力: SystemCapability.Multimedia.Audio.Device

返回值:

类型说明
AudioRoutingManagerAudioRoutingManager实例

示例:

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

let audioRoutingManager: audio.AudioRoutingManager = audioManager.getRoutingManager();

setVolume(deprecated)

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

设置指定流的音量,使用callback方式异步返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃。建议使用AudioVolumeGroupManager中的setVolume替代,替代接口能力仅对系统应用开放。

需要权限: ohos.permission.ACCESS_NOTIFICATION_POLICY

仅设置铃声(即volumeType为AudioVolumeType.RINGTONE)在静音和非静音状态切换时需要该权限。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。
volumenumber音量等级,可设置范围通过getMinVolume和getMaxVolume获取。
callbackAsyncCallback<void>回调函数。当设置指定流的音量成功,err为undefined,否则为错误对象。

示例:

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>

设置指定流的音量,使用Promise方式异步返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃。建议使用AudioVolumeGroupManager中的setVolume替代,替代接口能力仅对系统应用开放。

需要权限: ohos.permission.ACCESS_NOTIFICATION_POLICY

仅设置铃声(即volumeType为AudioVolumeType.RINGTONE)在静音和非静音状态切换时需要该权限。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。
volumenumber音量等级,可设置范围通过getMinVolume和getMaxVolume获取。

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

示例:

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

获取指定流的音量,使用callback方式异步返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的getVolume替代。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。
callbackAsyncCallback<number>回调函数。当获取指定流的音量成功,err为undefined,data为获取到的指定流的音量;否则为错误对象。

示例:

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>

获取指定流的音量,使用Promise方式异步返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的getVolume替代。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。

返回值:

类型说明
Promise<number>Promise对象,返回音量大小。

示例:

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

获取指定流的最小音量,使用callback方式异步返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的getMinVolume替代。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。
回调AsyncCallback<number>回调函数。当获取指定流的最小音量成功,err为undefined,data为获取到的指定流的最小音量;否则为错误对象。

示例:

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>

获取指定流的最小音量,使用Promise方式异步返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的getMinVolume替代。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。

返回值:

类型说明
Promise<number>Promise对象,返回最小音量。

示例:

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

获取指定流的最大音量,使用callback方式异步返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的getMaxVolume替代。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。
callbackAsyncCallback<number>回调函数。当获取指定流的最大音量成功,err为undefined,data为获取到的指定流的最大音量;否则为错误对象。

示例:

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>

获取指定流的最大音量,使用Promise方式异步返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的getMaxVolume替代。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。

返回值:

类型说明
Promise<number>Promise对象,返回最大音量。

示例:

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

设置指定音量流静音,使用callback方式异步返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃。建议使用AudioVolumeGroupManager中的mute替代,替代接口能力仅对系统应用开放。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。
muteboolean静音状态,true为静音,false为非静音。
callbackAsyncCallback<void>回调函数。当设置指定音量流静音成功,err为undefined,否则为错误对象。

示例:

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>

设置指定音量流静音,使用Promise方式异步返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃。建议使用AudioVolumeGroupManager中的mute替代,替代接口能力仅对系统应用开放。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。
muteboolean静音状态,true为静音,false为非静音。

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

示例:

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

获取指定音量流是否被静音,使用callback方式异步返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的isMute替代。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。
callbackAsyncCallback<boolean>回调函数。当获取指定音量流是否被静音成功,err为undefined,data为true为静音,false为非静音;否则为错误对象。

示例:

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>

获取指定音量流是否被静音,使用Promise方式异步返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的isMute替代。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。

返回值:

类型说明
Promise<boolean>Promise对象,返回流静音状态,true为静音,false为非静音。

示例:

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

获取指定音量流是否为活跃状态,使用callback方式异步返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioStreamManager中的isActive替代。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。
回调AsyncCallback<boolean>回调函数。当获取指定音量流是否为活跃状态成功,err为undefined,data为true为活跃,false为不活跃;否则为错误对象。

示例:

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>

获取指定音量流是否为活跃状态,使用Promise方式异步返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioStreamManager中的isActive替代。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。

返回值:

类型说明
Promise<boolean>Promise对象,返回流的活跃状态,true为活跃,false为不活跃。

示例:

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

设置铃声模式,使用callback方式异步返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃。建议使用AudioVolumeGroupManager中的setRingerMode替代,替代接口能力仅对系统应用开放。

需要权限: ohos.permission.ACCESS_NOTIFICATION_POLICY

仅在静音和非静音状态切换时需要该权限。

系统能力: SystemCapability.Multimedia.Audio.Communication

参数:

参数名类型必填说明
modeAudioRingMode音频铃声模式。
callbackAsyncCallback<void>回调函数。当设置铃声模式成功,err为undefined,否则为错误对象。

示例:

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>

设置铃声模式,使用Promise方式异步返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃。建议使用AudioVolumeGroupManager中的setRingerMode替代,替代接口能力仅对系统应用开放。

需要权限: ohos.permission.ACCESS_NOTIFICATION_POLICY

仅在静音和非静音状态切换时需要该权限。

系统能力: SystemCapability.Multimedia.Audio.Communication

参数:

参数名类型必填说明
modeAudioRingMode音频铃声模式。

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

示例:

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

获取铃声模式,使用callback方式异步返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的getRingerMode替代。

系统能力: SystemCapability.Multimedia.Audio.Communication

参数:

参数名类型必填说明
callbackAsyncCallback<AudioRingMode>回调函数。当获取铃声模式成功,err为undefined,data为获取到的铃声模式;否则为错误对象。

示例:

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>

获取铃声模式,使用Promise方式异步返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的getRingerMode替代。

系统能力: SystemCapability.Multimedia.Audio.Communication

返回值:

类型说明
Promise<AudioRingMode>Promise对象,返回系统的铃声模式。

示例:

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

getDevices(deprecated)

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

获取音频设备列表,使用callback方式异步返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioRoutingManager中的getDevices替代。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
deviceFlagDeviceFlag设备类型的flag。
callbackAsyncCallback<AudioDeviceDescriptors>回调函数。当获取音频设备列表成功,err为undefined,data为获取到的音频设备列表;否则为错误对象。

示例:

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.');
});Copy to clipboardErrorCopied

getDevices(deprecated)

getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors>

获取音频设备列表,使用Promise方式异步返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioRoutingManager中的getDevices替代。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
deviceFlagDeviceFlag设备类型的flag。

返回值:

类型说明
Promise<AudioDeviceDescriptors>Promise对象,返回设备列表。

示例:

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

setDeviceActive(deprecated)

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

设置设备激活状态,使用callback方式异步返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioRoutingManager中的setCommunicationDevice替代。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
deviceTypeActiveDeviceType活跃音频设备类型。
activeboolean设备激活状态。
callbackAsyncCallback<void>回调函数。当设置设备激活状态成功,err为undefined,否则为错误对象。

示例:

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.');
});Copy to clipboardErrorCopied

setDeviceActive(deprecated)

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

设置设备激活状态,使用Promise方式异步返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioRoutingManager中的setCommunicationDevice替代。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
deviceTypeActiveDeviceType活跃音频设备类型。
activeboolean设备激活状态。

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

示例:

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

isDeviceActive(deprecated)

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

获取指定设备的激活状态,使用callback方式异步返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioRoutingManager中的isCommunicationDeviceActive替代。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
deviceTypeActiveDeviceType活跃音频设备类型。
callbackAsyncCallback<boolean>回调函数。当获取指定设备的激活状态成功,err为undefined,data为true为激活,false为未激活;否则为错误对象。

示例:

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.');
});Copy to clipboardErrorCopied

isDeviceActive(deprecated)

isDeviceActive(deviceType: ActiveDeviceType): Promise<boolean>

获取指定设备的激活状态,使用Promise方式异步返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioRoutingManager中的isCommunicationDeviceActive替代。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
deviceTypeActiveDeviceType活跃音频设备类型。

返回值:

TypeDescription
Promise<boolean>Promise对象,返回设备的激活状态,true激活,false未激活。

示例:

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

setMicrophoneMute(deprecated)

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

设置麦克风静音状态,使用callback方式异步返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的setMicrophoneMute替代。

需要权限: ohos.permission.MICROPHONE

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
mute布尔待设置的静音状态,true为静音,false为非静音。
回调AsyncCallback<void>回调函数。当设置麦克风静音状态成功,err为undefined,否则为错误对象。

示例:

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>

设置麦克风静音状态,使用Promise方式异步返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的setMicrophoneMute替代。

需要权限: ohos.permission.MICROPHONE

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
mute布尔待设置的静音状态,true为静音,false为非静音。

返回值:

类型说明
承诺<无效>Promise对象,无返回结果。

示例:

audioManager.setMicrophoneMute(true).then(() => {
  console.info('Promise returned to indicate that the microphone is muted.');
});复制到剪贴板错误复制

isMicrophoneMute(deprecated)

isMicrophoneMute(callback: AsyncCallback<boolean>): void

获取麦克风静音状态,使用callback方式异步返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的isMicrophoneMute替代。

需要权限: ohos.permission.MICROPHONE

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
回调AsyncCallback<boolean>回调函数。当获取麦克风静音状态成功,err为undefined,data为true为静音,false为非静音;否则为错误对象。

示例:

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>

获取麦克风静音状态,使用Promise方式异步返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的isMicrophoneMute替代。

需要权限: ohos.permission.MICROPHONE

系统能力: SystemCapability.Multimedia.Audio.Device

返回值:

类型说明
Promise<boolean>Promise对象,返回系统麦克风静音状态,true为静音,false为非静音。

示例:

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

on('volumeChange')(deprecated)

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

说明: 从 API version 8 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeManager中的on('volumeChange')替代。

监听系统音量变化事件,使用callback方式返回结果。

系统接口: 该接口为系统接口

目前此订阅接口在单进程多AudioManager实例的使用场景下,仅最后一个实例的订阅生效,其他实例的订阅会被覆盖(即使最后一个实例没有进行订阅),因此推荐使用单一AudioManager实例进行开发。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
typestring事件回调类型,支持的事件为:'volumeChange'(系统音量变化事件,检测到系统音量改变时,触发该事件)。
callbackCallback<VolumeEvent>回调函数,返回变化后的音量信息。

示例:

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} `);
});Copy to clipboardErrorCopied

on('ringerModeChange')(deprecated)

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

监听铃声模式变化事件,使用callback方式返回结果。

说明: 从 API version 8 开始支持,从 API version 9 开始废弃,建议使用AudioVolumeGroupManager中的on('ringerModeChange')替代。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Communication

参数:

参数名类型必填说明
typestring事件回调类型,支持的事件为:'ringerModeChange'(铃声模式变化事件,检测到铃声模式改变时,触发该事件)。
callbackCallback<AudioRingMode>回调函数,返回变化后的铃音模式。

示例:

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

on('deviceChange')(deprecated)

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

设备更改。音频设备连接状态变化,使用callback方式返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioRoutingManager中的on('deviceChange')替代。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
typestring订阅的事件的类型。支持事件:'deviceChange'
callbackCallback<DeviceChangeAction>回调函数,返回设备更新详情。

示例:

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} `);
});Copy to clipboardErrorCopied

off('deviceChange')(deprecated)

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

取消订阅音频设备连接变化事件,使用callback方式返回结果。

说明: 从 API version 7 开始支持,从 API version 9 开始废弃,建议使用AudioRoutingManager中的off('deviceChange')替代。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
typestring订阅的事件的类型。支持事件:'deviceChange'
callbackCallback<DeviceChangeAction>回调函数,返回设备更新详情。

示例:

audioManager.off('deviceChange');Copy to clipboardErrorCopied

on('interrupt')

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

请求焦点并开始监听音频打断事件(当应用程序的音频被另一个播放事件中断,回调通知此应用程序),使用callback方式返回结果。

on('audioInterrupt')作用一致,均用于监听焦点变化。为无音频流的场景(未曾创建AudioRenderer对象),比如FM、语音唤醒等提供焦点变化监听功能。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
typestring音频打断事件回调类型,支持的事件为:'interrupt'(多应用之间第二个应用会打断第一个应用,触发该事件)。
interruptAudioInterrupt音频打断事件类型的参数。
callbackCallback<InterruptAction>回调函数,返回音频打断时,应用接收的中断事件信息。

示例:

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} `);
  }
});Copy to clipboardErrorCopied

off('interrupt')

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

取消监听音频打断事件(删除监听事件,取消打断),使用callback方式返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
typestring音频打断事件回调类型,支持的事件为:'interrupt'(多应用之间第二个应用会打断第一个应用,触发该事件)。
interruptAudioInterrupt音频打断事件类型的参数。
callbackCallback<InterruptAction>回调函数,返回删除监听事件,取消打断时,应用接收的中断事件信息。

示例:

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} `);
  }
});Copy to clipboardErrorCopied

AudioVolumeManager9+

音量管理。在使用AudioVolumeManager的接口前,需要使用getVolumeManager获取AudioVolumeManager实例。

getVolumeGroupInfos9+

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

获取音量组信息列表,使用callback方式异步返回结果。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
networkIdstring设备的网络id。本地设备audio.LOCAL_NETWORK_ID。
callbackAsyncCallback<VolumeGroupInfos>回调函数。当获取音量组信息列表成功,err为undefined,data为获取到的音量组信息列表;否则为错误对象。

示例:

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.');
});Copy to clipboardErrorCopied

getVolumeGroupInfos9+

getVolumeGroupInfos(networkId: string): Promise<VolumeGroupInfos>

获取音量组信息列表,使用Promise方式异步返回结果。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
networkIdstring设备的网络id。本地设备audio.LOCAL_NETWORK_ID。

返回值:

类型说明
Promise<VolumeGroupInfos>Promise对象,返回音量组信息列表。

示例:

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))
}Copy to clipboardErrorCopied

getVolumeGroupInfosSync10+

getVolumeGroupInfosSync(networkId: string): VolumeGroupInfos

获取音量组信息列表,同步返回结果。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
networkIdstring设备的网络id。本地设备audio.LOCAL_NETWORK_ID。

返回值:

类型说明
VolumeGroupInfos音量组信息列表。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101invalid parameter error

示例:

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}`);
}Copy to clipboardErrorCopied

getVolumeGroupManager9+

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

获取音频组管理器,使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
groupIdnumber音量组id。
callbackAsyncCallback<AudioVolumeGroupManager>回调函数。当获取音频组管理器成功,err为undefined,data为获取到的音频组管理器对象;否则为错误对象。

示例:

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.');
});
Copy to clipboardErrorCopied

getVolumeGroupManager9+

getVolumeGroupManager(groupId: number): Promise<AudioVolumeGroupManager>

获取音频组管理器,使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
groupIdnumber音量组id。

返回值:

类型说明
Promise< AudioVolumeGroupManager >Promise对象,返回音量组实例。

示例:

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('Promise returned to indicate that the volume group infos list is obtained.');
}Copy to clipboardErrorCopied

getVolumeGroupManagerSync10+

getVolumeGroupManagerSync(groupId: number): AudioVolumeGroupManager

获取音频组管理器,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
groupIdnumber音量组id。

返回值:

类型说明
AudioVolumeGroupManager音量组实例。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101invalid parameter error

示例:

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}`);
}Copy to clipboardErrorCopied

on('volumeChange')9+

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

监听系统音量变化事件,使用callback方式返回结果。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
类型字符串事件回调类型,支持的事件为:'volumeChange'。
回调Callback<VolumeEvent>回调函数,返回变化后的音量信息。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101if input parameter value error

示例:

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+

管理音频组音量。在调用AudioVolumeGroupManager的接口前,需要先通过 getVolumeGroupManager 创建实例。

setVolume9+

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

设置指定流的音量,使用callback方式异步返回结果。

需要权限: ohos.permission.ACCESS_NOTIFICATION_POLICY

仅设置铃声(即volumeType为AudioVolumeType.RINGTONE)在静音和非静音状态切换时需要该权限。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。
volume音量等级,可设置范围通过getMinVolume和getMaxVolume获取。
回调AsyncCallback<void>回调函数。当设置指定流的音量成功,err为undefined,否则为错误对象。

示例:

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>

设置指定流的音量,使用Promise方式异步返回结果。

需要权限: ohos.permission.ACCESS_NOTIFICATION_POLICY

仅设置铃声(即volumeType为AudioVolumeType.RINGTONE)在静音和非静音状态切换时需要该权限。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。
volumenumber音量等级,可设置范围通过getMinVolume和getMaxVolume获取。

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

示例:

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

getVolume9+

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

获取指定流的音量,使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。
callbackAsyncCallback<number>回调函数。当获取指定流的音量成功,err为undefined,data为获取到的指定流的音量;否则为错误对象。

示例:

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.');
});Copy to clipboardErrorCopied

getVolume9+

getVolume(volumeType: AudioVolumeType): Promise<number>

获取指定流的音量,使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。

返回值:

类型说明
Promise<number>Promise对象,返回音量大小。

示例:

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;

获取指定流的音量,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。

返回值:

类型说明
返回音量大小。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101invalid parameter error

示例:

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.error(`Failed to obtain the volume, error ${error}.`);
}复制到剪贴板错误复制

getMinVolume9+

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

获取指定流的最小音量,使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。
回调AsyncCallback<number>回调函数。当获取指定流的最小音量成功,err为undefined,data为获取到的指定流的最小音量;否则为错误对象。

示例:

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}`);
});Copy to clipboardErrorCopied

getMinVolume9+

getMinVolume(volumeType: AudioVolumeType): Promise<number>

获取指定流的最小音量,使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。

返回值:

类型说明
Promise<number>Promise对象,返回最小音量。

示例:

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

getMinVolumeSync10+

getMinVolumeSync(volumeType: AudioVolumeType): number;

获取指定流的最小音量,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。

返回值:

类型说明
number返回最小音量。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101invalid parameter error

示例:

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}.`);
}Copy to clipboardErrorCopied

getMaxVolume9+

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

获取指定流的最大音量,使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。
callbackAsyncCallback<number>回调函数。当获取指定流的最大音量成功,err为undefined,data为获取到的指定流的最大音量;否则为错误对象。

示例:

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}`);
});Copy to clipboardErrorCopied

getMaxVolume9+

getMaxVolume(volumeType: AudioVolumeType): Promise<number>

获取指定流的最大音量,使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。

返回值:

类型说明
Promise<number>Promise对象,返回最大音量大小。

示例:

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

getMaxVolumeSync10+

getMaxVolumeSync(volumeType: AudioVolumeType): number;

获取指定流的最大音量,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。

返回值:

类型说明
number返回最大音量大小。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101invalid parameter error

示例:

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}.`);
}Copy to clipboardErrorCopied

mute9+

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

设置指定音量流静音,使用callback方式异步返回结果。

需要权限: ohos.permission.ACCESS_NOTIFICATION_POLICY

仅设置铃声(即volumeType为AudioVolumeType.RINGTONE)在静音和非静音状态切换时需要该权限。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。
muteboolean静音状态,true为静音,false为非静音。
callbackAsyncCallback<void>回调函数。当设置指定音量流静音成功,err为undefined,否则为错误对象。

示例:

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.');
});Copy to clipboardErrorCopied

mute9+

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

设置指定音量流静音,使用Promise方式异步返回结果。

需要权限: ohos.permission.ACCESS_NOTIFICATION_POLICY

仅设置铃声(即volumeType为AudioVolumeType.RINGTONE)在静音和非静音状态切换时需要该权限。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。
muteboolean静音状态,true为静音,false为非静音。

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

示例:

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

isMute9+

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

获取指定音量流是否被静音,使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。
callbackAsyncCallback<boolean>回调函数。当获取指定音量流是否被静音成功,err为undefined,data为true为静音,false为非静音;否则为错误对象。

示例:

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}.`);
});Copy to clipboardErrorCopied

isMute9+

isMute(volumeType: AudioVolumeType): Promise<boolean>

获取指定音量流是否被静音,使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。

返回值:

类型说明
Promise<boolean>Promise对象,返回流静音状态,true为静音,false为非静音。

示例:

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

isMuteSync10+

isMuteSync(volumeType: AudioVolumeType): boolean

获取指定音量流是否被静音,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。

返回值:

类型说明
boolean返回流静音状态,true为静音,false为非静音。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101invalid parameter error

示例:

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}.`);
}Copy to clipboardErrorCopied

setRingerMode9+

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

设置铃声模式,使用callback方式异步返回结果。

需要权限: ohos.permission.ACCESS_NOTIFICATION_POLICY

仅在静音和非静音状态切换时需要该权限。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
模式AudioRingMode音频铃声模式。
回调AsyncCallback<void>回调函数。当设置铃声模式成功,err为undefined,否则为错误对象。

示例:

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>

设置铃声模式,使用Promise方式异步返回结果。

需要权限: ohos.permission.ACCESS_NOTIFICATION_POLICY

仅在静音和非静音状态切换时需要该权限。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
模式AudioRingMode音频铃声模式。

返回值:

类型说明
承诺<无效>Promise对象,无返回结果。

示例:

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

获取铃声模式,使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
回调AsyncCallback<AudioRingMode>回调函数。当获取铃声模式成功,err为undefined,data为获取到的铃声模式;否则为错误对象。

示例:

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}.`);
});Copy to clipboardErrorCopied

getRingerMode9+

getRingerMode(): Promise<AudioRingMode>

获取铃声模式,使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Volume

返回值:

类型说明
Promise<AudioRingMode>Promise对象,返回系统的铃声模式。

示例:

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

getRingerModeSync10+

getRingerModeSync(): AudioRingMode

获取铃声模式,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Volume

返回值:

类型说明
AudioRingMode返回系统的铃声模式。

示例:

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}.`);
}Copy to clipboardErrorCopied

on('ringerModeChange')9+

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

监听铃声模式变化事件,使用callback方式返回结果。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
typestring事件回调类型,支持的事件为:'ringerModeChange'(铃声模式变化事件,检测到铃声模式改变时,触发该事件)。
callbackCallback<AudioRingMode>回调函数,返回变化后的铃音模式。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101if input parameter value error

示例:

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

setMicrophoneMute9+

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

设置麦克风静音状态,使用callback方式异步返回结果。

需要权限: ohos.permission.MANAGE_AUDIO_CONFIG

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
muteboolean待设置的静音状态,true为静音,false为非静音。
callbackAsyncCallback<void>回调函数。当设置麦克风静音状态成功,err为undefined,否则为错误对象。

示例:

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.');
});Copy to clipboardErrorCopied

setMicrophoneMute9+

setMicrophoneMute(mute: boolean): Promise<void>

设置麦克风静音状态,使用Promise方式异步返回结果。

需要权限: ohos.permission.MANAGE_AUDIO_CONFIG

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
muteboolean待设置的静音状态,true为静音,false为非静音。

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

示例:

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

isMicrophoneMute9+

isMicrophoneMute(callback: AsyncCallback<boolean>): void

获取麦克风静音状态,使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
callbackAsyncCallback<boolean>回调函数。当获取麦克风静音状态成功,err为undefined,data为true为静音,false为非静音;否则为错误对象。

示例:

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}.`);
});Copy to clipboardErrorCopied

isMicrophoneMute9+

isMicrophoneMute(): Promise<boolean>

获取麦克风静音状态,使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Volume

返回值:

类型说明
Promise<boolean>Promise对象,返回系统麦克风静音状态,true为静音,false为非静音。

示例:

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

isMicrophoneMuteSync10+

isMicrophoneMuteSync(): boolean

获取麦克风静音状态,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Volume

返回值:

类型说明
boolean返回系统麦克风静音状态,true为静音,false为非静音。

示例:

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}.`);
}Copy to clipboardErrorCopied

on('micStateChange')9+

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

监听系统麦克风状态更改事件,使用callback方式返回结果。

目前此订阅接口在单进程多AudioManager实例的使用场景下,仅最后一个实例的订阅生效,其他实例的订阅会被覆盖(即使最后一个实例没有进行订阅),因此推荐使用单一AudioManager实例进行开发。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
typestring事件回调类型,支持的事件为:'micStateChange'(系统麦克风状态变化事件,检测到系统麦克风状态改变时,触发该事件)。
回调Callback<MicStateChangeEvent>回调函数,返回变更后的麦克风状态。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101if input parameter value error

示例:

audioVolumeGroupManager.on('micStateChange', (micStateChange: audio.MicStateChangeEvent) => {
  console.info(`Current microphone status is: ${micStateChange.mute} `);
});复制到剪贴板错误复制

isVolumeUnadjustable10+

isVolumeUnadjustable(): boolean

获取固定音量模式开关状态,打开时进入固定音量模式,此时音量固定无法被调节,使用同步方式返回结果。

系统能力: SystemCapability.Multimedia.Audio.Volume

返回值:

类型说明
布尔同步接口,返回固定音量模式开关状态,true为固定音量模式,false为非固定音量模式。

示例:

let volumeAdjustSwitch: boolean = audioVolumeGroupManager.isVolumeUnadjustable();
console.info(`Whether it is volume unadjustable: ${volumeAdjustSwitch}.`);复制到剪贴板错误复制

adjustVolumeByStep10+

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

调节当前最高优先级的流的音量,使音量值按步长加或减,使用callback方式异步返回结果。

需要权限: ohos.permission.ACCESS_NOTIFICATION_POLICY

仅设置铃声(即volumeType为AudioVolumeType.RINGTONE)在静音和非静音状态切换时需要该权限。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
adjustTypeVolumeAdjustType音量调节方向。
回调AsyncCallback<void>回调函数。当调节当前最高优先级的流的音量成功,err为undefined,否则为错误对象。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101Invalid parameter error. Return by callback.
6800301System error. Return by callback.

示例:

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>

单步设置当前最高优先级的流的音量,使用Promise方式异步返回结果。

需要权限: ohos.permission.ACCESS_NOTIFICATION_POLICY

仅设置铃声(即volumeType为AudioVolumeType.RINGTONE)在静音和非静音状态切换时需要该权限。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
adjustTypeVolumeAdjustType音量调节方向。

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101Invalid parameter error. Return by promise.
6800301System error. Return by promise.

示例:

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.');
});Copy to clipboardErrorCopied

adjustSystemVolumeByStep10+

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

单步设置指定流的音量,使用callback方式异步返回结果。

需要权限: ohos.permission.ACCESS_NOTIFICATION_POLICY

仅设置铃声(即volumeType为AudioVolumeType.RINGTONE)在静音和非静音状态切换时需要该权限。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。
adjustTypeVolumeAdjustType音量调节方向。
callbackAsyncCallback<void>回调函数。当单步设置指定流的音量成功,err为undefined,否则为错误对象。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101Invalid parameter error. Return by callback.
6800301System error. Return by callback.

示例:

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.');
  }
});Copy to clipboardErrorCopied

adjustSystemVolumeByStep10+

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

单步设置指定流的音量,使用Promise方式异步返回结果。

需要权限: ohos.permission.ACCESS_NOTIFICATION_POLICY

仅设置铃声(即volumeType为AudioVolumeType.RINGTONE)在静音和非静音状态切换时需要该权限。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。
adjustTypeVolumeAdjustType音量调节方向。

返回值:

类型说明
承诺<无效>Promise对象,无返回结果。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101Invalid parameter error. Return by promise.
6800301System error. Return by promise.

示例:

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

获取音量增益dB值,使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。
volumeLevel音量等级。
deviceDeviceType设备类型。
回调AsyncCallback<number>回调函数。当获取音量增益dB值成功,err为undefined,data为获取到的音量增益dB值;否则为错误对象。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101Invalid parameter error. Return by callback.
6800301System error. Return by callback.

示例:

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>

获取音量增益dB值,使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。
volumeLevelnumber音量等级。
deviceDeviceType设备类型。

返回值:

类型说明
Promise<number>Promise对象,返回对应的音量增益dB值。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101Invalid parameter error. Return by promise.
6800301System error. Return by promise.

示例:

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}`);
});Copy to clipboardErrorCopied

getSystemVolumeInDbSync10+

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

获取音量增益dB值,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Volume

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音量流类型。
volumeLevelnumber音量等级。
deviceDeviceType设备类型。

返回值:

类型说明
number返回对应的音量增益dB值。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101invalid parameter error

示例:

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}`);
}Copy to clipboardErrorCopied

AudioStreamManager9+

管理音频流。在使用AudioStreamManager的API前,需要使用getStreamManager获取AudioStreamManager实例。

getCurrentAudioRendererInfoArray9+

getCurrentAudioRendererInfoArray(callback: AsyncCallback<AudioRendererChangeInfoArray>): void

获取当前音频渲染器的信息。使用callback异步回调。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
callbackAsyncCallback<AudioRendererChangeInfoArray>回调函数。当获取当前音频渲染器的信息成功,err为undefined,data为获取到的当前音频渲染器的信息;否则为错误对象。

示例:

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]}`);
        }
      }
    }
  }
});Copy to clipboardErrorCopied

getCurrentAudioRendererInfoArray9+

getCurrentAudioRendererInfoArray(): Promise<AudioRendererChangeInfoArray>

获取当前音频渲染器的信息。使用Promise异步回调。

系统能力: SystemCapability.Multimedia.Audio.Renderer

返回值:

类型说明
Promise<AudioRendererChangeInfoArray>Promise对象,返回当前音频渲染器信息。

示例:

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

获取当前音频渲染器的信息,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

返回值:

类型说明
AudioRendererChangeInfoArray返回当前音频渲染器信息。

示例:

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

获取当前音频采集器的信息。使用callback异步回调。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
回调AsyncCallback<AudioCapturerChangeInfoArray>回调函数。当获取当前音频采集器的信息成功,err为undefined,data为获取到的当前音频采集器的信息;否则为错误对象。

示例:

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>

获取当前音频采集器的信息。使用Promise异步回调。

系统能力: SystemCapability.Multimedia.Audio.Renderer

返回值:

类型说明
Promise<AudioCapturerChangeInfoArray>Promise对象,返回当前音频渲染器信息。

示例:

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

获取当前音频采集器的信息,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

返回值:

类型说明
AudioCapturerChangeInfoArray返回当前音频采集器信息。

示例:

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

监听音频渲染器更改事件,使用callback方式返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
typestring事件类型,支持的事件:当音频渲染器发生更改时触发。'audioRendererChange'
callbackCallback<AudioRendererChangeInfoArray>回调函数,返回当前音频渲染器信息。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101if input parameter value error

示例:

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]}`);
    }
  }
});Copy to clipboardErrorCopied

off('audioRendererChange')9+

off(type: 'audioRendererChange'): void

取消监听音频渲染器更改事件。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
typestring事件类型,支持的事件:音频渲染器更改事件。'audioRendererChange'

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101if input parameter value error

示例:

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

on('audioCapturerChange')9+

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

监听音频采集器更改事件,使用callback方式返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

参数:

参数名类型必填说明
typestring事件类型,支持的事件:当音频采集器发生更改时触发。'audioCapturerChange'
callbackCallback<AudioCapturerChangeInfoArray>回调函数,返回当前音频采集器信息。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101if input parameter value error

示例:

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}`);
    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]}`);
    }
  }
});Copy to clipboardErrorCopied

off('audioCapturerChange')9+

off(type: 'audioCapturerChange'): void

取消监听音频采集器更改事件。

系统能力: SystemCapability.Multimedia.Audio.Capturer

参数:

参数名类型必填说明
typestring事件类型,支持的事件:音频采集器更改事件。'audioCapturerChange'

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101if input parameter value error

示例:

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

isActive9+

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

获取指定音频流是否为活跃状态,使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音频流类型。
callbackAsyncCallback<boolean>回调函数。当获取指定音频流是否为活跃状态成功,err为undefined,data为true为活跃,false为不活跃;否则为错误对象。

示例:

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}.`);
});Copy to clipboardErrorCopied

isActive9+

isActive(volumeType: AudioVolumeType): Promise<boolean>

获取指定音频流是否为活跃状态,使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音频流类型。

返回值:

类型说明
Promise<boolean>Promise对象,返回流的活跃状态,true为活跃,false为不活跃。

示例:

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

获取指定音频流是否为活跃状态,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
volumeTypeAudioVolumeType音频流类型。

返回值:

类型说明
布尔返回流的活跃状态,true为活跃,false为不活跃。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101invalid parameter error

示例:

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

获取当前音效模式的信息。使用callback异步回调。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
usageStreamUsage音频流使用类型。
回调AsyncCallback<AudioEffectInfoArray>回调函数。当获取当前音效模式的信息成功,err为undefined,data为获取到的当前音效模式的信息;否则为错误对象。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101Invalid parameter error. Return by callback.

示例:

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

audioStreamManager.getAudioEffectInfoArray(audio.StreamUsage.STREAM_USAGE_MUSIC, 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}`);
  }
});Copy to clipboardErrorCopied

getAudioEffectInfoArray10+

getAudioEffectInfoArray(usage: StreamUsage): Promise<AudioEffectInfoArray>

获取当前音效模式的信息。使用Promise异步回调。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
usageStreamUsage音频流使用类型。

返回值:

类型说明
Promise<AudioEffectInfoArray>Promise对象,返回当前音效模式的信息。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101Invalid parameter error. Return by promise.

示例:

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

audioStreamManager.getAudioEffectInfoArray(audio.StreamUsage.STREAM_USAGE_MUSIC).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}`);
});Copy to clipboardErrorCopied

getAudioEffectInfoArraySync10+

getAudioEffectInfoArraySync(usage: StreamUsage): AudioEffectInfoArray

获取当前音效模式的信息,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
usageStreamUsage音频流使用类型。

返回值:

类型说明
AudioEffectInfoArray返回当前音效模式的信息。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101invalid parameter error

示例:

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

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

AudioRoutingManager9+

音频路由管理。在使用AudioRoutingManager的接口前,需要使用getRoutingManager获取AudioRoutingManager实例。

getDevices9+

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

获取音频设备列表,使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
deviceFlagDeviceFlag设备类型的flag。
回调AsyncCallback<AudioDeviceDescriptors>回调函数。当获取音频设备列表成功,err为undefined,data为获取到的音频设备列表;否则为错误对象。

示例:

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>

获取音频设备列表,使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
deviceFlagDeviceFlag设备类型的flag。

返回值:

类型说明
Promise<AudioDeviceDescriptors>Promise对象,返回设备列表。

示例:

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

获取音频设备列表,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
deviceFlagDeviceFlag设备类型的flag。

返回值:

类型说明
AudioDeviceDescriptors返回设备列表。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101invalid parameter error

示例:

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}`);
}Copy to clipboardErrorCopied

on('deviceChange')9+

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

设备更改。音频设备连接状态变化,使用callback方式返回结果。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
typestring订阅的事件的类型。支持事件:'deviceChange'
deviceFlagDeviceFlag设备类型的flag。
callbackCallback<DeviceChangeAction>回调函数,返回设备更新详情。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101if input parameter value error

示例:

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);
});Copy to clipboardErrorCopied

off('deviceChange')9+

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

取消订阅音频设备连接变化事件,使用callback方式返回结果。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
typestring订阅的事件的类型。支持事件:'deviceChange'
callbackCallback<DeviceChangeAction>回调函数,返回设备更新详情。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101if input parameter value error

示例:

audioRoutingManager.off('deviceChange');Copy to clipboardErrorCopied

selectInputDevice9+

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

选择音频输入设备,当前只能选择一个输入设备,使用callback方式异步返回结果。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
inputAudioDevicesAudioDeviceDescriptors输入设备类。
callbackAsyncCallback<void>回调函数。当选择音频输入设备成功,err为undefined,否则为错误对象。

示例:

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

let inputAudioDeviceDescriptor: audio.AudioDeviceDescriptors = [{
  deviceRole : audio.DeviceRole.INPUT_DEVICE,
  deviceType : audio.DeviceType.MIC,
  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');
    }
  });
}Copy to clipboardErrorCopied

selectInputDevice9+

selectInputDevice(inputAudioDevices: AudioDeviceDescriptors): Promise<void>

系统接口: 该接口为系统接口

选择音频输入设备,当前只能选择一个输入设备,使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
inputAudioDevicesAudioDeviceDescriptors输入设备类。

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

示例:

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

let inputAudioDeviceDescriptor: audio.AudioDeviceDescriptors = [{
  deviceRole : audio.DeviceRole.INPUT_DEVICE,
  deviceType : audio.DeviceType.MIC,
  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}`);
  });
}Copy to clipboardErrorCopied

setCommunicationDevice9+

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

设置通信设备激活状态,使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Communication

参数:

参数名类型必填说明
deviceTypeCommunicationDeviceType音频设备类型。
active布尔设备激活状态,true激活,false未激活。
回调AsyncCallback<void>回调函数。当设置通信设备激活状态成功,err为undefined,否则为错误对象。

示例:

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>

设置通信设备激活状态,使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Communication

参数:

参数名类型必填说明
deviceTypeCommunicationDeviceType活跃音频设备类型。
active布尔设备激活状态,true激活,false未激活。

返回值:

类型说明
承诺<无效>Promise对象,无返回结果。

示例:

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

获取指定通信设备的激活状态,使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Communication

参数:

参数名类型必填说明
deviceTypeCommunicationDeviceType活跃音频设备类型。
回调AsyncCallback<boolean>回调函数。当获取指定通信设备的激活状态成功,err为undefined,data为true为激活,false为未激活;否则为错误对象。

示例:

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>

获取指定通信设备的激活状态,使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Communication

参数:

参数名类型必填说明
deviceTypeCommunicationDeviceType活跃音频设备类型。

返回值:

TypeDescription
Promise<boolean>Promise对象,返回设备的激活状态,true激活,false未激活。

示例:

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

获取指定通信设备的激活状态,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Communication

参数:

参数名类型必填说明
deviceTypeCommunicationDeviceType活跃音频设备类型。

返回值:

TypeDescription
布尔返回设备的激活状态,true激活,false未激活。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101invalid parameter error

示例:

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

选择音频输出设备,当前只能选择一个输出设备,使用callback方式异步返回结果。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
outputAudioDevicesAudioDeviceDescriptors输出设备类。
callbackAsyncCallback<void>回调函数。当选择音频输出设备成功,err为undefined,否则为错误对象。

示例:

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'); }
  });
}Copy to clipboardErrorCopied

selectOutputDevice9+

selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors): Promise<void>

系统接口: 该接口为系统接口

选择音频输出设备,当前只能选择一个输出设备,使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
outputAudioDevicesAudioDeviceDescriptors输出设备类。

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

示例:

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}`);
  });
}Copy to clipboardErrorCopied

selectOutputDeviceByFilter9+

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

系统接口: 该接口为系统接口

根据过滤条件,选择音频输出设备,当前只能选择一个输出设备,使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
filterAudioRendererFilter过滤条件类。
outputAudioDevicesAudioDeviceDescriptors输出设备类。
callbackAsyncCallback<void>回调函数。当选择音频输出设备成功,err为undefined,否则为错误对象。

示例:

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

let outputAudioRendererFilter: audio.AudioRendererFilter = {
  uid : 20010041,
  rendererInfo : {
    usage : audio.StreamUsage.STREAM_USAGE_MUSIC,
    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'); }
  });
}Copy to clipboardErrorCopied

selectOutputDeviceByFilter9+

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

系统接口: 该接口为系统接口

根据过滤条件,选择音频输出设备,当前只能选择一个输出设备,使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
filterAudioRendererFilter过滤条件类。
outputAudioDevicesAudioDeviceDescriptors输出设备类。

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

示例:

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

let outputAudioRendererFilter: audio.AudioRendererFilter = {
  uid : 20010041,
  rendererInfo : {
    usage : audio.StreamUsage.STREAM_USAGE_MUSIC,
    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}`);
  })
}Copy to clipboardErrorCopied

getPreferOutputDeviceForRendererInfo10+

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

根据音频信息,返回优先级最高的输出设备,使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
rendererInfoAudioRendererInfo表示渲染器信息。
callbackAsyncCallback<AudioDeviceDescriptors>回调函数。当获取优先级最高的输出设备成功,err为undefined,data为获取到的优先级最高的输出设备信息;否则为错误对象。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101Input parameter value error. Return by callback.
6800301System error. Return by callback.

示例:

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}`);
    }
  });
}Copy to clipboardErrorCopied

getPreferOutputDeviceForRendererInfo10+

getPreferOutputDeviceForRendererInfo(rendererInfo: AudioRendererInfo): Promise<AudioDeviceDescriptors>

根据音频信息,返回优先级最高的输出设备,使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
rendererInfoAudioRendererInfo表示渲染器信息。

返回值:

类型说明
Promise<AudioDeviceDescriptors>Promise对象,返回优先级最高的输出设备信息。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101Input parameter value error. Return by promise.
6800301System error. Return by promise.

示例:

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}`);
  })
}Copy to clipboardErrorCopied

getPreferredOutputDeviceForRendererInfoSync10+

getPreferredOutputDeviceForRendererInfoSync(rendererInfo: AudioRendererInfo): AudioDeviceDescriptors

根据音频信息,返回优先级最高的输出设备,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
rendererInfoAudioRendererInfo表示渲染器信息。

返回值:

类型说明
AudioDeviceDescriptors返回优先级最高的输出设备信息。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101invalid parameter error.

示例:

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

订阅最高优先级输出设备变化事件,使用callback方式返回结果。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
类型字符串订阅的事件的类型。支持事件:'preferOutputDeviceChangeForRendererInfo'
rendererInfoAudioRendererInfo表示渲染器信息。
回调Callback<AudioDeviceDescriptors>回调函数,返回优先级最高的输出设备信息。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101if input parameter value error

示例:

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

取消订阅最高优先级输出音频设备变化事件,使用callback方式返回结果。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
typestring订阅的事件的类型。支持事件:'preferOutputDeviceChangeForRendererInfo'
callbackCallback<AudioDeviceDescriptors>回调函数,返回优先级最高的输出设备信息。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101if input parameter value error

示例:

audioRoutingManager.off('preferOutputDeviceChangeForRendererInfo');Copy to clipboardErrorCopied

getPreferredInputDeviceForCapturerInfo10+

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

根据音频信息,返回优先级最高的输入设备,使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
capturerInfoAudioCapturerInfo表示采集器信息。
callbackAsyncCallback<AudioDeviceDescriptors>回调函数。当获取优先级最高的输入设备成功,err为undefined,data为获取到的优先级最高的输入设备信息;否则为错误对象。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101Invalid parameter error. Return by callback.
6800301System error. Return by callback.

示例:

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}`);
  }
});Copy to clipboardErrorCopied

getPreferredInputDeviceForCapturerInfo10+

getPreferredInputDeviceForCapturerInfo(capturerInfo: AudioCapturerInfo): Promise<AudioDeviceDescriptors>

根据音频信息,返回优先级最高的输入设备,使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
capturerInfoAudioCapturerInfo表示采集器信息。

返回值:

类型说明
Promise<AudioDeviceDescriptors>Promise对象,返回优先级最高的输入设备信息。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101Invalid parameter error. Return by promise.
6800301System error. Return by promise.

示例:

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}`);
});Copy to clipboardErrorCopied

getPreferredInputDeviceForCapturerInfoSync10+

getPreferredInputDeviceForCapturerInfoSync(capturerInfo: AudioCapturerInfo): AudioDeviceDescriptors

根据音频信息,返回优先级最高的输入设备,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
capturerInfoAudioCapturerInfo表示采集器信息。

返回值:

类型说明
AudioDeviceDescriptors返回优先级最高的输入设备信息。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101invalid parameter error

示例:

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}`);
}Copy to clipboardErrorCopied

on('preferredInputDeviceChangeForCapturerInfo')10+

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

订阅最高优先级输入设备变化事件,使用callback方式返回结果。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
typestring订阅的事件的类型。支持事件:'preferredInputDeviceChangeForCapturerInfo'
capturerInfoAudioCapturerInfo表示采集器信息。
callbackCallback<AudioDeviceDescriptors>回调函数,返回优先级最高的输入设备信息。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101if input parameter value error

示例:

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}`);
});Copy to clipboardErrorCopied

off('preferredInputDeviceChangeForCapturerInfo')10+

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

取消订阅最高优先级输入音频设备变化事件,使用callback方式返回结果。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
typestring订阅的事件的类型。支持事件:'preferredInputDeviceChangeForCapturerInfo'
callbackCallback<AudioDeviceDescriptors>回调函数,返回优先级最高的输入设备信息。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101if input parameter value error

示例:

audioRoutingManager.off('preferredInputDeviceChangeForCapturerInfo');Copy to clipboardErrorCopied

AudioRendererChangeInfoArray9+

数组类型,AudioRenderChangeInfo数组,只读。

系统能力: SystemCapability.Multimedia.Audio.Renderer

AudioRendererChangeInfo9+

描述音频渲染器更改信息。

系统能力: SystemCapability.Multimedia.Audio.Renderer

名称类型可读可写说明
streamId音频流唯一id。
clientUid音频渲染器客户端应用程序的Uid。
此接口为系统接口。
rendererInfoAudioRendererInfo音频渲染器信息。
rendererStateAudioState音频状态。
此接口为系统接口。
deviceDescriptorsAudioDeviceDescriptors音频设备描述。

示例:

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+

数组类型,AudioCapturerChangeInfo数组,只读。

系统能力: SystemCapability.Multimedia.Audio.Capturer

AudioCapturerChangeInfo9+

描述音频采集器更改信息。

系统能力: SystemCapability.Multimedia.Audio.Capturer

名称类型可读可写说明
streamId音频流唯一id。
clientUid音频采集器客户端应用程序的Uid。
此接口为系统接口。
capturerInfoAudioCapturerInfo音频采集器信息。
capturerStateAudioState音频状态。
此接口为系统接口。
deviceDescriptorsAudioDeviceDescriptors音频设备描述。

示例:

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+

待查询ContentType和StreamUsage组合场景下的音效模式数组类型,AudioEffectMode数组,只读。

AudioDeviceDescriptors

设备属性数组类型,为AudioDeviceDescriptor的数组,只读。

AudioDeviceDescriptor

描述音频设备。

系统能力: SystemCapability.Multimedia.Audio.Device

名称类型可读可写说明
deviceRoleDeviceRole设备角色。
deviceTypeDeviceType设备类型。
id9+number设备id,唯一。
name9+string设备名称。
如果是蓝牙设备,需要申请权限ohos.permission.USE_BLUETOOTH。
address9+string设备地址。
如果是蓝牙设备,需要申请权限ohos.permission.USE_BLUETOOTH。
sampleRates9+Array<number>支持的采样率。
channelCounts9+Array<number>支持的通道数。
channelMasks9+Array<number>支持的通道掩码。
displayName10+string设备显示名。
networkId9+string设备组网的ID。
此接口为系统接口。
interruptGroupId9+number设备所处的焦点组ID。
此接口为系统接口。
volumeGroupId9+number设备所处的音量组ID。
此接口为系统接口。

示例:

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');
  }
});Copy to clipboardErrorCopied

AudioRendererFilter9+

过滤条件类。在调用selectOutputDeviceByFilter接口前,需要先创建AudioRendererFilter实例。

系统接口: 该接口为系统接口

名称类型必填说明
uidnumber表示应用ID。
系统能力: SystemCapability.Multimedia.Audio.Core
rendererInfoAudioRendererInfo表示渲染器信息。
系统能力: SystemCapability.Multimedia.Audio.Renderer
rendererIdnumber音频流唯一id。
系统能力: SystemCapability.Multimedia.Audio.Renderer

示例:

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

let outputAudioRendererFilter: audio.AudioRendererFilter = {
  uid : 20010041,
  rendererInfo : {
    usage : audio.StreamUsage.STREAM_USAGE_MUSIC,
    rendererFlags : 0
  },
  rendererId : 0
};Copy to clipboardErrorCopied

AudioRenderer8+

提供音频渲染的相关接口。在调用AudioRenderer的接口前,需要先通过createAudioRenderer创建实例。

属性

系统能力: SystemCapability.Multimedia.Audio.Renderer

名称类型可读可写说明
state8+AudioState音频渲染器的状态。

示例:

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

let state: audio.AudioState = audioRenderer.state;Copy to clipboardErrorCopied

getRendererInfo8+

getRendererInfo(callback: AsyncCallback<AudioRendererInfo>): void

获取当前被创建的音频渲染器的信息,使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
callbackAsyncCallback<AudioRendererInfo>回调函数。当获取音频渲染器的信息成功,err为undefined,data为获取到的音频渲染器的信息;否则为错误对象。

示例:

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}`);
});Copy to clipboardErrorCopied

getRendererInfo8+

getRendererInfo(): Promise<AudioRendererInfo>

获取当前被创建的音频渲染器的信息,使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

返回值:

类型说明
Promise<AudioRendererInfo>Promise对象,返回音频渲染器信息。

示例:

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}`);
});Copy to clipboardErrorCopied

getRendererInfoSync10+

getRendererInfoSync(): AudioRendererInfo

获取当前被创建的音频渲染器的信息,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

返回值:

类型说明
AudioRendererInfo返回音频渲染器信息。

示例:

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

获取音频流信息,使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
回调AsyncCallback<AudioStreamInfo>回调函数。当获取音频流信息成功,err为undefined,data为获取到的音频流信息;否则为错误对象。

示例:

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>

获取音频流信息,使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

返回值:

类型说明
Promise<AudioStreamInfo>Promise对象,返回音频流信息.

示例:

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

获取音频流信息,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

返回值:

类型说明
AudioStreamInfo返回音频流信息.

示例:

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}`);
}Copy to clipboardErrorCopied

getAudioStreamId9+

getAudioStreamId(callback: AsyncCallback<number>): void

获取音频流id,使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
callbackAsyncCallback<number>回调函数。当获取音频流id成功,err为undefined,data为获取到的音频流id;否则为错误对象。

示例:

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

audioRenderer.getAudioStreamId((err: BusinessError, streamId: number) => {
  console.info(`Renderer GetStreamId: ${streamId}`);
});Copy to clipboardErrorCopied

getAudioStreamId9+

getAudioStreamId(): Promise<number>

获取音频流id,使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

返回值:

类型说明
Promise<number>Promise对象,返回音频流id。

示例:

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

audioRenderer.getAudioStreamId().then((streamId: number) => {
  console.info(`Renderer getAudioStreamId: ${streamId}`);
}).catch((err: BusinessError) => {
  console.error(`ERROR: ${err}`);
});Copy to clipboardErrorCopied

getAudioStreamIdSync10+

getAudioStreamIdSync(): number

获取音频流id,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

返回值:

类型说明
number返回音频流id。

示例:

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}`);
}Copy to clipboardErrorCopied

setAudioEffectMode10+

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

设置当前音效模式。使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
modeAudioEffectMode音效模式。
callbackAsyncCallback<void>回调函数。当设置当前音效模式成功,err为undefined,否则为错误对象。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101Invalid parameter error. Return by callback.

示例:

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.');
  }
});Copy to clipboardErrorCopied

setAudioEffectMode10+

setAudioEffectMode(mode: AudioEffectMode): Promise<void>

设置当前音效模式。使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
modeAudioEffectMode音效模式。

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101Invalid parameter error. Return by promise.

示例:

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

audioRenderer.setAudioEffectMode(audio.AudioEffectMode.EFFECT_DEFAULT).then(() => {
  console.info('setAudioEffectMode SUCCESS');
}).catch((err: BusinessError) => {
  console.error(`ERROR: ${err}`);
});Copy to clipboardErrorCopied

getAudioEffectMode10+

getAudioEffectMode(callback: AsyncCallback<AudioEffectMode>): void

获取当前音效模式。使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
callbackAsyncCallback<AudioEffectMode>回调函数。当获取当前音效模式成功,err为undefined,data为获取到的当前音效模式;否则为错误对象。

示例:

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}`);
  }
});Copy to clipboardErrorCopied

getAudioEffectMode10+

getAudioEffectMode(): Promise<AudioEffectMode>

获取当前音效模式。使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

返回值:

类型说明
Promise<AudioEffectMode>Promise对象,返回当前音效模式。

示例:

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

启动音频渲染器。使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
回调AsyncCallback<void>回调函数。当启动音频渲染器成功,err为undefined,否则为错误对象。

示例:

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>

启动音频渲染器。使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

返回值:

类型说明
承诺<无效>Promise对象,无返回结果。

示例:

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

暂停渲染。使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
callbackAsyncCallback<void>回调函数。当暂停渲染成功,err为undefined,否则为错误对象。

示例:

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

audioRenderer.pause((err: BusinessError) => {
  if (err) {
    console.error('Renderer pause failed');
  } else {
    console.info('Renderer paused.');
  }
});Copy to clipboardErrorCopied

pause8+

pause(): Promise<void>

暂停渲染。使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

示例:

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

audioRenderer.pause().then(() => {
  console.info('Renderer paused');
}).catch((err: BusinessError) => {
  console.error(`ERROR: ${err}`);
});Copy to clipboardErrorCopied

drain8+

drain(callback: AsyncCallback<void>): void

检查缓冲区是否已被耗尽。使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
callbackAsyncCallback<void>回调函数。当检查缓冲区是否已被耗尽成功,err为undefined,否则为错误对象。

示例:

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

audioRenderer.drain((err: BusinessError) => {
  if (err) {
    console.error('Renderer drain failed');
  } else {
    console.info('Renderer drained.');
  }
});Copy to clipboardErrorCopied

drain8+

drain(): Promise<void>

检查缓冲区是否已被耗尽。使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

返回值:

类型说明
承诺<无效>Promise对象,无返回结果。

示例:

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

停止渲染。使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
回调AsyncCallback<void>回调函数。当停止渲染成功,err为undefined,否则为错误对象。

示例:

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>

停止渲染。使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

返回值:

类型说明
承诺<无效>Promise对象,无返回结果。

示例:

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

释放音频渲染器。使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
callbackAsyncCallback<void>回调函数。当释放音频渲染器成功,err为undefined,否则为错误对象。

示例:

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

audioRenderer.release((err: BusinessError) => {
  if (err) {
    console.error('Renderer release failed');
  } else {
    console.info('Renderer released.');
  }
});Copy to clipboardErrorCopied

release8+

release(): Promise<void>

释放渲染器。使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

示例:

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

audioRenderer.release().then(() => {
  console.info('Renderer released successfully');
}).catch((err: BusinessError) => {
  console.error(`ERROR: ${err}`);
});Copy to clipboardErrorCopied

write8+

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

写入缓冲区。使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
bufferArrayBuffer要写入缓冲区的数据。
callbackAsyncCallback<number>回调函数。当写入缓冲区成功,err为undefined,data为获取到的写入的字节数;否则为错误对象。

示例:

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

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}`);
});

Copy to clipboardErrorCopied

write8+

write(buffer: ArrayBuffer): Promise<number>

写入缓冲区。使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
bufferArrayBuffer要写入缓冲区的数据。

返回值:

类型说明
Promise<number>Promise对象,返回写入的字节数。

示例:

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

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.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`);
});Copy to clipboardErrorCopied

getAudioTime8+

getAudioTime(callback: AsyncCallback<number>): void

获取时间戳(从 1970 年 1 月 1 日开始)。使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
回调AsyncCallback<number>回调函数。当获取时间戳成功,err为undefined,data为获取到的时间戳;否则为错误对象。

示例:

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

audioRenderer.getAudioTime((err: BusinessError, timestamp: number) => {
  console.info(`Current timestamp: ${timestamp}`);
});复制到剪贴板错误复制

getAudioTime8+

getAudioTime(): Promise<number>

获取时间戳(从 1970 年 1 月 1 日开始)。使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

返回值:

类型描述
Promise<number>Promise对象,返回时间戳。

示例:

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

获取时间戳(从 1970 年 1 月 1 日开始),同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

返回值:

类型描述
返回时间戳。

示例:

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

获取音频渲染器的最小缓冲区大小。使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
回调AsyncCallback<number>回调函数。当获取音频渲染器的最小缓冲区大小成功,err为undefined,data为获取到的最小缓冲区大小;否则为错误对象。

示例:

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>

获取音频渲染器的最小缓冲区大小。使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

返回值:

类型说明
Promise<number>Promise对象,返回缓冲区大小。

示例:

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

获取音频渲染器的最小缓冲区大小,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

返回值:

类型说明
返回缓冲区大小。

示例:

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

设置音频渲染速率。使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
rateAudioRendererRate渲染的速率。
回调AsyncCallback<void>回调函数。当设置音频渲染速率成功,err为undefined,否则为错误对象。

示例:

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>

设置音频渲染速率。使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
rateAudioRendererRate渲染的速率。

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

示例:

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

audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL).then(() => {
  console.info('setRenderRate SUCCESS');
}).catch((err: BusinessError) => {
  console.error(`ERROR: ${err}`);
});Copy to clipboardErrorCopied

getRenderRate8+

getRenderRate(callback: AsyncCallback<AudioRendererRate>): void

获取当前渲染速率。使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
callbackAsyncCallback<AudioRendererRate>回调函数。当获取当前渲染速率成功,err为undefined,data为获取到的当前渲染速率;否则为错误对象。

示例:

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

audioRenderer.getRenderRate((err: BusinessError, renderRate: audio.AudioRendererRate) => {
  console.info(`getRenderRate: ${renderRate}`);
});Copy to clipboardErrorCopied

getRenderRate8+

getRenderRate(): Promise<AudioRendererRate>

获取当前渲染速率。使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

返回值:

类型说明
Promise<AudioRendererRate>Promise对象,返回渲染速率。

示例:

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

audioRenderer.getRenderRate().then((renderRate: audio.AudioRendererRate) => {
  console.info(`getRenderRate: ${renderRate}`);
}).catch((err: BusinessError) => {
  console.error(`ERROR: ${err}`);
});Copy to clipboardErrorCopied

getRenderRateSync10+

getRenderRateSync(): AudioRendererRate

获取当前渲染速率,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

返回值:

类型说明
AudioRendererRate返回渲染速率。

示例:

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}`);
}Copy to clipboardErrorCopied

setInterruptMode9+

setInterruptMode(mode: InterruptMode): Promise<void>

设置应用的焦点模型。使用Promise异步回调。

系统能力: SystemCapability.Multimedia.Audio.Interrupt

参数:

参数名类型必填说明
modeInterruptMode焦点模型。

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

示例:

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

let mode = 0;
audioRenderer.setInterruptMode(mode).then(() => {
  console.info('setInterruptMode Success!');
}).catch((err: BusinessError) => {
  console.error(`setInterruptMode Fail: ${err}`);
});Copy to clipboardErrorCopied

setInterruptMode9+

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

设置应用的焦点模型。使用Callback回调返回执行结果。

系统能力: SystemCapability.Multimedia.Audio.Interrupt

参数:

参数名类型必填说明
modeInterruptMode焦点模型。
callbackAsyncCallback<void>回调函数。当设置应用的焦点模型成功,err为undefined,否则为错误对象。

示例:

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

let mode = 1;
audioRenderer.setInterruptMode(mode, (err: BusinessError) => {
  if(err){
    console.error(`setInterruptMode Fail: ${err}`);
  }
  console.info('setInterruptMode Success!');
});Copy to clipboardErrorCopied

setInterruptModeSync10+

setInterruptModeSync(mode: InterruptMode): void

设置应用的焦点模型,同步设置。

系统能力: SystemCapability.Multimedia.Audio.Interrupt

参数:

参数名类型必填说明
modeInterruptMode焦点模型。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101invalid parameter error

示例:

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}`);
}Copy to clipboardErrorCopied

setVolume9+

setVolume(volume: number): Promise<void>

设置应用的音量。使用Promise异步回调。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
volumenumber音量值范围为0.0-1.0。

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

示例:

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

audioRenderer.setVolume(0.5).then(() => {
  console.info('setVolume Success!');
}).catch((err: BusinessError) => {
  console.error(`setVolume Fail: ${err}`);
});Copy to clipboardErrorCopied

setVolume9+

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

设置应用的音量。使用Callback回调返回执行结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
volumenumber音量值范围为0.0-1.0。
callbackAsyncCallback<void>回调函数。当设置应用的音量成功,err为undefined,否则为错误对象。

示例:

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

audioRenderer.setVolume(0.5, (err: BusinessError) => {
  if(err){
    console.error(`setVolume Fail: ${err}`);
    return;
  }
  console.info('setVolume Success!');
});Copy to clipboardErrorCopied

getMinStreamVolume10+

getMinStreamVolume(callback: AsyncCallback<number>): void

获取应用基于音频流的最小音量。使用Callback回调返回。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
callbackAsyncCallback<number>回调函数。当获取应用基于音频流的最小音量成功,err为undefined,data为获取到的应用基于音频流的最小音量(音量范围0-1);否则为错误对象。

示例:

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

audioRenderer.getMinStreamVolume((err: BusinessError, minVolume: number) => {
  if (err) {
    console.error(`getMinStreamVolume error: ${err}`);
  } else {
    console.info(`getMinStreamVolume Success! ${minVolume}`);
  }
});Copy to clipboardErrorCopied

getMinStreamVolume10+

getMinStreamVolume(): Promise<number>

获取应用基于音频流的最小音量。使用Promise异步回调。

系统能力: SystemCapability.Multimedia.Audio.Renderer

返回值:

类型说明
Promise<number>Promise对象,返回音频流最小音量(音量范围0-1)。

示例:

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}`);
});Copy to clipboardErrorCopied

getMinStreamVolumeSync10+

getMinStreamVolumeSync(): number

获取应用基于音频流的最小音量,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

返回值:

类型说明
number返回音频流最小音量(音量范围0-1)。

示例:

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}`);
}Copy to clipboardErrorCopied

getMaxStreamVolume10+

getMaxStreamVolume(callback: AsyncCallback<number>): void

获取应用基于音频流的最大音量。使用Callback回调返回。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
callbackAsyncCallback<number>回调函数。当获取应用基于音频流的最大音量成功,err为undefined,data为获取到的应用基于音频流的最大音量(音量范围0-1);否则为错误对象。

示例:

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

audioRenderer.getMaxStreamVolume((err: BusinessError, maxVolume: number) => {
  if (err) {
    console.error(`getMaxStreamVolume Fail: ${err}`);
  } else {
    console.info(`getMaxStreamVolume Success! ${maxVolume}`);
  }
});Copy to clipboardErrorCopied

getMaxStreamVolume10+

getMaxStreamVolume(): Promise<number>

获取应用基于音频流的最大音量。使用Promise异步回调。

系统能力: SystemCapability.Multimedia.Audio.Renderer

返回值:

类型说明
Promise<number>Promise对象,返回音频流最大音量(音量范围0-1)。

示例:

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}`);
});Copy to clipboardErrorCopied

getMaxStreamVolumeSync10+

getMaxStreamVolumeSync(): number

获取应用基于音频流的最大音量,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

返回值:

类型说明
number返回音频流最大音量(音量范围0-1)。

示例:

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}`);
}Copy to clipboardErrorCopied

getUnderflowCount10+

getUnderflowCount(callback: AsyncCallback<number>): void

获取当前播放音频流的欠载音频帧数量。使用Callback回调返回。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
callbackAsyncCallback<number>回调函数。当获取当前播放音频流的欠载音频帧数量成功,err为undefined,data为获取到的当前播放音频流的欠载音频帧数量;否则为错误对象。

示例:

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

audioRenderer.getUnderflowCount((err: BusinessError, underflowCount: number) => {
  if (err) {
    console.error(`getUnderflowCount Fail: ${err}`);
  } else {
    console.info(`getUnderflowCount Success! ${underflowCount}`);
  }
});Copy to clipboardErrorCopied

getUnderflowCount10+

getUnderflowCount(): Promise<number>

获取当前播放音频流的欠载音频帧数量。使用Promise异步回调。

系统能力: SystemCapability.Multimedia.Audio.Renderer

返回值:

类型说明
Promise<number>Promise对象,返回音频流的欠载音频帧数量。

示例:

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}`);
});Copy to clipboardErrorCopied

getUnderflowCountSync10+

getUnderflowCountSync(): number

获取当前播放音频流的欠载音频帧数量,同步返回数据。

系统能力: SystemCapability.Multimedia.Audio.Renderer

返回值:

类型说明
number返回音频流的欠载音频帧数量。

示例:

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}`);
}Copy to clipboardErrorCopied

getCurrentOutputDevices10+

getCurrentOutputDevices(callback: AsyncCallback<AudioDeviceDescriptors>): void

获取音频流输出设备描述符。使用Callback回调返回。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
callbackAsyncCallback<AudioDeviceDescriptors>回调函数。当获取音频流输出设备描述符成功,err为undefined,data为获取到的音频流输出设备描述符;否则为错误对象。

示例:

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]}`);
    }
  }
});Copy to clipboardErrorCopied

getCurrentOutputDevices10+

getCurrentOutputDevices(): Promise<AudioDeviceDescriptors>

获取音频流输出设备描述符。使用Promise异步回调。

系统能力: SystemCapability.Multimedia.Audio.Device

返回值:

类型说明
Promise<AudioDeviceDescriptors>Promise对象,返回音频流的输出设备描述信息

示例:

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}`);
});Copy to clipboardErrorCopied

getCurrentOutputDevicesSync10+

getCurrentOutputDevicesSync(): AudioDeviceDescriptors

获取音频流输出设备描述符,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Device

返回值:

类型说明
AudioDeviceDescriptors返回音频流的输出设备描述信息

示例:

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}`);
}Copy to clipboardErrorCopied

on('audioInterrupt')9+

on(type: 'audioInterrupt', callback: Callback<InterruptEvent>): void

监听音频中断事件,使用callback方式返回结果。

on('interrupt')一致,均用于监听焦点变化。AudioRenderer对象在start事件发生时会主动获取焦点,在pause、stop等事件发生时会主动释放焦点,不需要开发者主动发起获取焦点或释放焦点的申请。

系统能力: SystemCapability.Multimedia.Audio.Interrupt

参数:

参数名类型必填说明
typestring事件回调类型,支持的事件为:'audioInterrupt'(中断事件被触发,音频渲染被中断。)
callbackCallback<InterruptEvent>回调函数,返回播放中断时,应用接收的中断事件信息。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101if input parameter value error

示例:

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

let isPlaying: boolean; // 标识符,表示是否正在渲染
let isDucked: boolean; // 标识符,表示是否被降低音量
onAudioInterrupt();

async function onAudioInterrupt(){
  audioRenderer.on('audioInterrupt', (interruptEvent: audio.InterruptEvent) => {
    if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) {
      // 由系统进行操作,强制打断音频渲染,应用需更新自身状态及显示内容等
      switch (interruptEvent.hintType) {
        case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
          // 音频流已被暂停,临时失去焦点,待可重获焦点时会收到resume对应的interruptEvent
          console.info('Force paused. Update playing status and stop writing');
          isPlaying = false; // 简化处理,代表应用切换至暂停状态的若干操作
          break;
        case audio.InterruptHint.INTERRUPT_HINT_STOP:
          // 音频流已被停止,永久失去焦点,若想恢复渲染,需用户主动触发
          console.info('Force stopped. Update playing status and stop writing');
          isPlaying = false; // 简化处理,代表应用切换至暂停状态的若干操作
          break;
        case audio.InterruptHint.INTERRUPT_HINT_DUCK:
          // 音频流已被降低音量渲染
          console.info('Force ducked. Update volume status');
          isDucked = true; // 简化处理,代表应用更新音量状态的若干操作
          break;
        case audio.InterruptHint.INTERRUPT_HINT_UNDUCK:
          // 音频流已被恢复正常音量渲染
          console.info('Force ducked. Update volume status');
          isDucked = false; // 简化处理,代表应用更新音量状态的若干操作
          break;
        default:
          console.info('Invalid interruptEvent');
          break;
      }
    } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) {
      // 由应用进行操作,应用可以自主选择打断或忽略
      switch (interruptEvent.hintType) {
        case audio.InterruptHint.INTERRUPT_HINT_RESUME:
          // 建议应用继续渲染(说明音频流此前被强制暂停,临时失去焦点,现在可以恢复渲染)
          console.info('Resume force paused renderer or ignore');
          // 若选择继续渲染,需在此处主动执行开始渲染的若干操作
          break;
        case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
          // 建议应用暂停渲染
          console.info('Choose to pause or ignore');
          // 若选择暂停渲染,需在此处主动执行暂停渲染的若干操作
          break;
        case audio.InterruptHint.INTERRUPT_HINT_STOP:
          // 建议应用停止渲染
          console.info('Choose to stop or ignore');
          // 若选择停止渲染,需在此处主动执行停止渲染的若干操作
          break;
        case audio.InterruptHint.INTERRUPT_HINT_DUCK:
          // 建议应用降低音量渲染
          console.info('Choose to duck or ignore');
          // 若选择降低音量渲染,需在此处主动执行降低音量渲染的若干操作
          break;
        case audio.InterruptHint.INTERRUPT_HINT_UNDUCK:
          // 建议应用恢复正常音量渲染
          console.info('Choose to unduck or ignore');
          // 若选择恢复正常音量渲染,需在此处主动执行恢复正常音量渲染的若干操作
          break;
        default:
          break;
      }
    }
  });
}Copy to clipboardErrorCopied

on('markReach')8+

on(type: 'markReach', frame: number, callback: Callback<number>): void

订阅到达标记的事件。 当渲染的帧数达到 frame 参数的值时,回调被调用,使用callback方式返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
typestring事件回调类型,支持的事件为:'markReach'。
framenumber触发事件的帧数。 该值必须大于 0。
callbackCallback<number>回调函数,返回frame 参数的值

示例:

audioRenderer.on('markReach', 1000, (position: number) => {
  if (position == 1000) {
    console.info('ON Triggered successfully');
  }
});Copy to clipboardErrorCopied

off('markReach') 8+

off(type: 'markReach'): void

取消订阅标记事件。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
typestring要取消订阅事件的类型。支持的事件为:'markReach'。

示例:

audioRenderer.off('markReach');Copy to clipboardErrorCopied

on('periodReach') 8+

on(type: 'periodReach', frame: number, callback: Callback<number>): void

订阅到达标记的事件。 当渲染的帧数达到 frame 参数的值时,触发回调并返回设定的值,使用callback方式返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
typestring事件回调类型,支持的事件为:'periodReach'。
framenumber触发事件的帧数。 该值必须大于 0。
callbackCallback<number>回调函数,返回frame 参数的值

示例:

audioRenderer.on('periodReach', 1000, (position: number) => {
  if (position == 1000) {
    console.info('ON Triggered successfully');
  }
});Copy to clipboardErrorCopied

off('periodReach') 8+

off(type: 'periodReach'): void

取消订阅标记事件。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
typestring要取消订阅事件的类型。支持的事件为:'periodReach'。

示例:

audioRenderer.off('periodReach');Copy to clipboardErrorCopied

on('stateChange') 8+

on(type: 'stateChange', callback: Callback<AudioState>): void

订阅监听状态变化,使用callback方式返回结果。

系统能力: SystemCapability.Multimedia.Audio.Renderer

参数:

参数名类型必填说明
typestring事件回调类型,支持的事件为:'stateChange'。
callbackCallback<AudioState>回调函数,返回当前音频的状态。

示例:

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');
  }
});Copy to clipboardErrorCopied

on('outputDeviceChange') 10+

on(type: 'outputDeviceChange', callback: Callback<AudioDeviceDescriptors>): void

订阅监听音频输出设备变化,使用callback方式返回结果。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
typestring事件回调类型,支持的事件为:'outputDeviceChange'。
callbackCallback<AudioDeviceDescriptors>回调函数,返回当前音频流的输出设备描述信息。

错误码:

错误码ID错误信息
6800101if input parameter value error.

示例:

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}`);
});Copy to clipboardErrorCopied

off('outputDeviceChange') 10+

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

取消订阅监听音频输出设备变化,使用callback方式返回结果。

系统能力: SystemCapability.Multimedia.Audio.Device

参数:

参数名类型必填说明
typestring事件回调类型,支持的事件为:'outputDeviceChange'。
callbackCallback<AudioDeviceDescriptors>回调函数,返回当前音频流的输出设备描述信息。

错误码:

错误码ID错误信息
6800101if input parameter value error.

示例:

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}`);
});Copy to clipboardErrorCopied

AudioCapturer8+

提供音频采集的相关接口。在调用AudioCapturer的接口前,需要先通过createAudioCapturer创建实例。

属性

系统能力: SystemCapability.Multimedia.Audio.Capturer

名称类型可读可写说明
state8+AudioState音频采集器状态。

示例:

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

let state: audio.AudioState = audioCapturer.state;Copy to clipboardErrorCopied

getCapturerInfo8+

getCapturerInfo(callback: AsyncCallback<AudioCapturerInfo>): void

获取采集器信息。使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

参数:

参数名类型必填说明
callbackAsyncCallback<AudioCapturerInfo>回调函数。当获取采集器信息成功,err为undefined,data为获取到的采集器信息;否则为错误对象。

示例:

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}`);
  }
});Copy to clipboardErrorCopied

getCapturerInfo8+

getCapturerInfo(): Promise<AudioCapturerInfo>

获取采集器信息。使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

返回值:

类型说明
Promise<AudioCapturerInfo>Promise对象,返回采集器信息。

示例:

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}`);
})Copy to clipboardErrorCopied

getCapturerInfoSync10+

getCapturerInfoSync(): AudioCapturerInfo

获取采集器信息,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

返回值:

类型说明
AudioCapturerInfo返回采集器信息。

示例:

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}`);
}Copy to clipboardErrorCopied

getStreamInfo8+

getStreamInfo(callback: AsyncCallback<AudioStreamInfo>): void

获取采集器流信息。使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

参数:

参数名类型必填说明
callbackAsyncCallback<AudioStreamInfo>回调函数。当获取采集器流信息成功,err为undefined,data为获取到的采集器流信息;否则为错误对象。

示例:

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}`);
  }
});Copy to clipboardErrorCopied

getStreamInfo8+

getStreamInfo(): Promise<AudioStreamInfo>

获取采集器流信息。使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

返回值:

类型说明
Promise<AudioStreamInfo>Promise对象,返回流信息。

示例:

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}`);
});Copy to clipboardErrorCopied

getStreamInfoSync10+

getStreamInfoSync(): AudioStreamInfo

获取采集器流信息,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

返回值:

类型说明
AudioStreamInfo返回流信息。

示例:

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

获取音频流id,使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

参数:

参数名类型必填说明
回调AsyncCallback<number>回调函数。当获取音频流id成功,err为undefined,data为获取到的音频流id;否则为错误对象。

示例:

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

audioCapturer.getAudioStreamId((err: BusinessError, streamId: number) => {
  console.info(`audioCapturer GetStreamId: ${streamId}`);
});复制到剪贴板错误复制

getAudioStreamId9+

getAudioStreamId(): Promise<number>

获取音频流id,使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

返回值:

类型说明
Promise<number>Promise对象,返回音频流id。

示例:

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

获取音频流id,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

返回值:

类型说明
返回音频流id。

示例:

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

启动音频采集器。使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

参数:

参数名类型必填说明
callbackAsyncCallback<void>回调函数。当启动音频采集器成功,err为undefined,否则为错误对象。

示例:

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

audioCapturer.start((err: BusinessError) => {
  if (err) {
    console.error('Capturer start failed.');
  } else {
    console.info('Capturer start success.');
  }
});Copy to clipboardErrorCopied

start8+

start(): Promise<void>

启动音频采集器。使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

示例:

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.error(`AudioFrameworkRecLog: Capturer start :ERROR : ${err}`);
});Copy to clipboardErrorCopied

stop8+

stop(callback: AsyncCallback<void>): void

停止采集。使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

参数:

参数名类型必填说明
callbackAsyncCallback<void>回调函数。当停止采集成功,err为undefined,否则为错误对象。

示例:

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

audioCapturer.stop((err: BusinessError) => {
  if (err) {
    console.error('Capturer stop failed');
  } else {
    console.info('Capturer stopped.');
  }
});Copy to clipboardErrorCopied

stop8+

stop(): Promise<void>

停止采集。使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

示例:

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.error(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`);
});Copy to clipboardErrorCopied

release8+

release(callback: AsyncCallback<void>): void

释放采集器。使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

参数:

参数名类型必填说明
callbackAsyncCallback<void>回调函数。当释放采集器成功,err为undefined,否则为错误对象。

示例:

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

audioCapturer.release((err: BusinessError) => {
  if (err) {
    console.error('capturer release failed');
  } else {
    console.info('capturer released.');
  }
});Copy to clipboardErrorCopied

release8+

release(): Promise<void>

释放采集器。使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

示例:

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.error(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`);
});Copy to clipboardErrorCopied

read8+

read(size: number, isBlockingRead: boolean, callback: AsyncCallback<ArrayBuffer>): void

读入缓冲区。使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

参数:

参数名类型必填说明
sizenumber读入的字节数。
isBlockingReadboolean是否阻塞读操作 ,true阻塞,false不阻塞。
callbackAsyncCallback<ArrayBuffer>回调函数。当读入缓冲区成功,err为undefined,data为获取到的缓冲区;否则为错误对象。

示例:

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: ArrayBuffer) => {
  if (!err) {
    console.info('Success in reading the buffer data');
  }
});Copy to clipboardErrorCopied

read8+

read(size: number, isBlockingRead: boolean): Promise<ArrayBuffer>

读入缓冲区。使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

参数:

参数名类型必填说明
sizenumber读入的字节数。
isBlockingReadboolean是否阻塞读操作 ,true阻塞,false不阻塞。

返回值:

类型说明
Promise<ArrayBuffer>Promise对象,返回读取的缓冲区数据。

示例:

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}`);
});
console.info(`Buffer size: ${bufferSize}`);
audioCapturer.read(bufferSize, true).then((buffer: ArrayBuffer) => {
  console.info('buffer read successfully');
}).catch((err: BusinessError) => {
  console.error(`ERROR : ${err}`);
});Copy to clipboardErrorCopied

getAudioTime8+

getAudioTime(callback: AsyncCallback<number>): void

获取时间戳(从1970年1月1日开始),单位为纳秒。使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

参数:

参数名类型必填说明
callbackAsyncCallback<number>回调函数。当获取时间戳成功,err为undefined,data为获取到的时间戳;否则为错误对象。

示例:

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

audioCapturer.getAudioTime((err: BusinessError, timestamp: number) => {
  console.info(`Current timestamp: ${timestamp}`);
});Copy to clipboardErrorCopied

getAudioTime8+

getAudioTime(): Promise<number>

获取时间戳(从1970年1月1日开始),单位为纳秒。使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

返回值:

类型说明
Promise<number>Promise对象,返回时间戳(从1970年1月1日开始),单位为纳秒。

示例:

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

audioCapturer.getAudioTime().then((audioTime: number) => {
  console.info(`AudioFrameworkRecLog: AudioCapturer getAudioTime : Success ${audioTime}`);
}).catch((err: BusinessError) => {
  console.error(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`);
});Copy to clipboardErrorCopied

getAudioTimeSync10+

getAudioTimeSync(): number

获取时间戳(从1970年1月1日开始),单位为纳秒,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

返回值:

类型说明
number返回时间戳。

示例:

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.error(`AudioFrameworkRecLog: AudioCapturer getAudioTimeSync : ERROR : ${error}`);
}Copy to clipboardErrorCopied

getBufferSize8+

getBufferSize(callback: AsyncCallback<number>): void

获取采集器合理的最小缓冲区大小。使用callback方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

参数:

参数名类型必填说明
callbackAsyncCallback<number>回调函数。当获取采集器合理的最小缓冲区大小成功,err为undefined,data为获取到的采集器合理的最小缓冲区大小;否则为错误对象。

示例:

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

audioCapturer.getBufferSize((err: BusinessError, bufferSize: number) => {
  if (!err) {
    console.info(`BufferSize : ${bufferSize}`);
    audioCapturer.read(bufferSize, true).then((buffer: ArrayBuffer) => {
      console.info(`Buffer read is ${buffer.byteLength}`);
    }).catch((err: BusinessError) => {
      console.error(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`);
    });
  }
});Copy to clipboardErrorCopied

getBufferSize8+

getBufferSize(): Promise<number>

获取采集器合理的最小缓冲区大小。使用Promise方式异步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

返回值:

类型说明
Promise<number>Promise对象,返回缓冲区大小。

示例:

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}`);
});Copy to clipboardErrorCopied

getBufferSizeSync10+

getBufferSizeSync(): number

获取采集器合理的最小缓冲区大小,同步返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

返回值:

类型说明
number返回缓冲区大小。

示例:

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.error(`AudioFrameworkRecLog: getBufferSizeSync :ERROR : ${error}`);
}Copy to clipboardErrorCopied

on('audioInterrupt')10+

on(type: 'audioInterrupt', callback: Callback<InterruptEvent>): void

监听音频中断事件,使用callback方式返回结果。

on('interrupt')一致,均用于监听焦点变化。AudioCapturer对象在start事件发生时会主动获取焦点,在pause、stop等事件发生时会主动释放焦点,不需要开发者主动发起获取焦点或释放焦点的申请。

系统能力: SystemCapability.Multimedia.Audio.Interrupt

参数:

参数名类型必填说明
typestring事件回调类型,支持的事件为:'audioInterrupt'(中断事件被触发,音频采集被中断。)
callbackCallback<InterruptEvent>回调函数,返回播放中断时,应用接收的中断事件信息。

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101if input parameter value error

示例:

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

let isCapturing: boolean; // 标识符,表示是否正在采集
onAudioInterrupt();

async function onAudioInterrupt(){
  audioCapturer.on('audioInterrupt', (interruptEvent: audio.InterruptEvent) => {
    if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) {
      // 由系统进行操作,强制打断音频采集,应用需更新自身状态及显示内容等
      switch (interruptEvent.hintType) {
        case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
          // 音频流已被暂停,临时失去焦点,待可重获焦点时会收到resume对应的interruptEvent
          console.info('Force paused. Update capturing status and stop reading');
          isCapturing = false; // 简化处理,代表应用切换至暂停状态的若干操作
          break;
        case audio.InterruptHint.INTERRUPT_HINT_STOP:
          // 音频流已被停止,永久失去焦点,若想恢复采集,需用户主动触发
          console.info('Force stopped. Update capturing status and stop reading');
          isCapturing = false; // 简化处理,代表应用切换至暂停状态的若干操作
          break;
        default:
          console.info('Invalid interruptEvent');
          break;
      }
    } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) {
      // 由应用进行操作,应用可以自主选择打断或忽略
      switch (interruptEvent.hintType) {
        case audio.InterruptHint.INTERRUPT_HINT_RESUME:
          // 建议应用继续采集(说明音频流此前被强制暂停,临时失去焦点,现在可以恢复采集)
          console.info('Resume force paused renderer or ignore');
          // 若选择继续采集,需在此处主动执行开始采集的若干操作
          break;
        case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
          // 建议应用暂停采集
          console.info('Choose to pause or ignore');
          // 若选择暂停采集,需在此处主动执行暂停采集的若干操作
          break;
        case audio.InterruptHint.INTERRUPT_HINT_STOP:
          // 建议应用停止采集
          console.info('Choose to stop or ignore');
          // 若选择停止采集,需在此处主动执行停止采集的若干操作
          break;
        default:
          break;
      }
    }
  });
}Copy to clipboardErrorCopied

off('audioInterrupt')10+

off(type: 'audioInterrupt'): void

取消订阅音频中断事件。

系统能力: SystemCapability.Multimedia.Audio.Interrupt

参数:

参数名类型必填说明
typestring事件回调类型,支持的事件为:'audioInterrupt'

错误码:

以下错误码的详细介绍请参见音频错误码

错误码ID错误信息
6800101if input parameter value error

示例:

audioCapturer.off('audioInterrupt');Copy to clipboardErrorCopied

on('markReach')8+

on(type: 'markReach', frame: number, callback: Callback<number>): void

订阅标记到达的事件。 当采集的帧数达到 frame 参数的值时,回调被触发,使用callback方式返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

参数:

参数名类型必填说明
typestring事件回调类型,支持的事件为:'markReach'。
framenumber触发事件的帧数。 该值必须大于0。
callbackCallback<number>回调函数,返回frame 参数的值

示例:

audioCapturer.on('markReach', 1000, (position: number) => {
  if (position == 1000) {
    console.info('ON Triggered successfully');
  }
});Copy to clipboardErrorCopied

off('markReach')8+

off(type: 'markReach'): void

取消订阅标记到达的事件。

系统能力: SystemCapability.Multimedia.Audio.Capturer

参数:

参数名类型必填说明
typestring取消事件回调类型,支持的事件为:'markReach'。

示例:

audioCapturer.off('markReach');Copy to clipboardErrorCopied

on('periodReach')8+

on(type: 'periodReach', frame: number, callback: Callback<number>): void

订阅到达标记的事件。 当采集的帧数达到 frame 参数的值时,触发回调并返回设定的值,使用callback方式返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

参数:

参数名类型必填说明
typestring事件回调类型,支持的事件为:'periodReach'。
framenumber触发事件的帧数。 该值必须大于0。
callbackCallback<number>回调函数,返回frame 参数的值。

示例:

audioCapturer.on('periodReach', 1000, (position: number) => {
  if (position == 1000) {
    console.info('ON Triggered successfully');
  }
});Copy to clipboardErrorCopied

off('periodReach')8+

off(type: 'periodReach'): void

取消订阅标记到达的事件。

系统能力: SystemCapability.Multimedia.Audio.Capturer

参数:

参数名类型必填说明
typestring取消事件回调类型,支持的事件为:'periodReach'。

示例:

audioCapturer.off('periodReach');Copy to clipboardErrorCopied

on('stateChange') 8+

on(type: 'stateChange', callback: Callback<AudioState>): void

订阅监听状态变化,使用callback方式返回结果。

系统能力: SystemCapability.Multimedia.Audio.Capturer

参数:

参数名类型必填说明
typestring事件回调类型,支持的事件为:'stateChange'。
callbackCallback<AudioState>回调函数,返回当前音频的状态。

示例:

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');
  }
});Copy to clipboardErrorCopied

ToneType9+

枚举,播放器的音调类型。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Tone

名称说明
TONE_TYPE_DIAL_00键0的DTMF音。
TONE_TYPE_DIAL_11键1的DTMF音。
TONE_TYPE_DIAL_22键2的DTMF音。
TONE_TYPE_DIAL_33键3的DTMF音。
TONE_TYPE_DIAL_44键4的DTMF音。
TONE_TYPE_DIAL_55键5的DTMF音。
TONE_TYPE_DIAL_66键6的DTMF音。
TONE_TYPE_DIAL_77键7的DTMF音。
TONE_TYPE_DIAL_88键8的DTMF音。
TONE_TYPE_DIAL_99键9的DTMF音。
TONE_TYPE_DIAL_S10键*的DTMF音。
TONE_TYPE_DIAL_P11键#的DTMF音。
TONE_TYPE_DIAL_A12键A的DTMF音。
TONE_TYPE_DIAL_B13键B的DTMF音。
TONE_TYPE_DIAL_C14键C的DTMF音。
TONE_TYPE_DIAL_D15键D的DTMF音。
TONE_TYPE_COMMON_SUPERVISORY_DIAL100呼叫监管音调,拨号音。
TONE_TYPE_COMMON_SUPERVISORY_BUSY101呼叫监管音调,忙。
TONE_TYPE_COMMON_SUPERVISORY_CONGESTION102呼叫监管音调,拥塞。
TONE_TYPE_COMMON_SUPERVISORY_RADIO_ACK103呼叫监管音调,无线电 ACK。
TONE_TYPE_COMMON_SUPERVISORY_RADIO_NOT_AVAILABLE104呼叫监管音调,无线电不可用。
TONE_TYPE_COMMON_SUPERVISORY_CALL_WAITING106呼叫监管音调,呼叫等待。
TONE_TYPE_COMMON_SUPERVISORY_RINGTONE107呼叫监管音调,铃声。
TONE_TYPE_COMMON_PROPRIETARY_BEEP200专有声调,一般蜂鸣声。
TONE_TYPE_COMMON_PROPRIETARY_ACK201专有声调,ACK。
TONE_TYPE_COMMON_PROPRIETARY_PROMPT203专有声调,PROMPT。
TONE_TYPE_COMMON_PROPRIETARY_DOUBLE_BEEP204专有声调,双重蜂鸣声。

TonePlayer9+

提供播放和管理DTMF(Dual Tone Multi Frequency,双音多频)音调的方法,包括各种系统监听音调、专有音调,如拨号音、通话回铃音等。 在调用TonePlayer的接口前,需要先通过createTonePlayer创建实例。

系统接口: 该接口为系统接口

load9+

load(type: ToneType, callback: AsyncCallback<void>): void

加载DTMF音调配置。使用callback方式异步返回结果。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Tone

参数:

参数名类型必填说明
typeToneType配置的音调类型。
callbackAsyncCallback<void>回调函数。当加载DTMF音调配置成功,err为undefined,否则为错误对象。

示例:

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');
  }
});Copy to clipboardErrorCopied

load9+

load(type: ToneType): Promise<void>

加载DTMF音调配置。使用Promise方式异步返回结果。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Tone

参数:

参数名类型必填说明
typeToneType配置的音调类型。

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

示例:

tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_1).then(() => {
  console.info('promise call load ');
}).catch(() => {
  console.error('promise call load fail');
});Copy to clipboardErrorCopied

start9+

start(callback: AsyncCallback<void>): void

启动DTMF音调播放。使用callback方式异步返回结果。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Tone

参数:

参数名类型必填说明
callbackAsyncCallback<void>回调函数。当启动DTMF音调播放成功,err为undefined,否则为错误对象。

示例:

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');
  }
});Copy to clipboardErrorCopied

start9+

start(): Promise<void>

启动DTMF音调播放。使用Promise方式异步返回结果。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Tone

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

示例:

tonePlayer.start().then(() => {
  console.info('promise call start');
}).catch(() => {
  console.error('promise call start fail');
});Copy to clipboardErrorCopied

stop9+

stop(callback: AsyncCallback<void>): void

停止当前正在播放的音调。使用callback方式异步返回结果。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Tone

参数:

参数名类型必填说明
callbackAsyncCallback<void>回调函数。当停止当前正在播放的音调成功,err为undefined,否则为错误对象。

示例:

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 ');
  }
});Copy to clipboardErrorCopied

stop9+

stop(): Promise<void>

停止当前正在播放的音调。使用Promise方式异步返回结果。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Tone

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

示例:

tonePlayer.stop().then(() => {
  console.info('promise call stop finish');
}).catch(() => {
  console.error('promise call stop fail');
});Copy to clipboardErrorCopied

release9+

release(callback: AsyncCallback<void>): void

释放与此TonePlayer对象关联的资源。使用callback方式异步返回结果。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Tone

参数:

参数名类型必填说明
callbackAsyncCallback<void>回调函数。当释放与此TonePlayer对象关联的资源成功,err为undefined,否则为错误对象。

示例:

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 ');
  }
});Copy to clipboardErrorCopied

release9+

release(): Promise<void>

释放与此TonePlayer对象关联的资源。使用Promise方式异步返回结果。

系统接口: 该接口为系统接口

系统能力: SystemCapability.Multimedia.Audio.Tone

返回值:

类型说明
Promise<void>Promise对象,无返回结果。

示例:

tonePlayer.release().then(() => {
  console.info('promise call release');
}).catch(() => {
  console.error('promise call release fail');
});Copy to clipboardErrorCopied

ActiveDeviceType(deprecated)

枚举,活跃设备类型。

说明:

从 API version 9 开始废弃,建议使用CommunicationDeviceType替代。

系统能力: SystemCapability.Multimedia.Audio.Device

名称说明
SPEAKER2扬声器。
BLUETOOTH_SCO7蓝牙设备SCO(Synchronous Connection Oriented)连接。

InterruptActionType(deprecated)

枚举,中断事件返回类型。

说明:

从 API version 7 开始支持,从 API version 9 开始废弃。无替代接口,与中断事件配套使用。

系统能力: SystemCapability.Multimedia.Audio.Renderer

名称说明
TYPE_ACTIVATED0表示触发焦点事件。
TYPE_INTERRUPT1表示音频打断事件。

AudioInterrupt(deprecated)

音频监听事件传入的参数。

说明:

从 API version 7 开始支持,从 API version 9 开始废弃。无替代接口,与中断事件配套使用。

系统能力: SystemCapability.Multimedia.Audio.Renderer

名称类型必填说明
streamUsageStreamUsage音频流使用类型。
contentTypeContentType音频打断媒体类型。
pauseWhenDucked布尔音频打断时是否可以暂停音频播放(true表示音频播放可以在音频打断期间暂停,false表示相反)。

InterruptAction(deprecated)

音频打断/获取焦点事件的回调方法。

说明:

从 API version 7 开始支持,从 API version 9 开始废弃。建议使用InterruptEvent替代。

系统能力: SystemCapability.Multimedia.Audio.Renderer

名称类型必填说明
actionTypeInterruptActionType事件返回类型。TYPE_ACTIVATED为焦点触发事件,TYPE_INTERRUPT为音频打断事件。
类型InterruptType打断事件类型。
hintInterruptHint打断事件提示。
activated布尔获得/释放焦点。true表示焦点获取/释放成功,false表示焦点获得/释放失败。

最后

有很多小伙伴不知道学习哪些鸿蒙开发技术?不知道需要重点掌握哪些鸿蒙应用开发知识点?而且学习时频繁踩坑,最终浪费大量时间。所以有一份实用的鸿蒙(HarmonyOS NEXT)资料用来跟着学习是非常有必要的。 

这份鸿蒙(HarmonyOS NEXT)资料包含了鸿蒙开发必掌握的核心知识要点,内容包含了ArkTS、ArkUI开发组件、Stage模型、多端部署、分布式应用开发、音频、视频、WebGL、OpenHarmony多媒体技术、Napi组件、OpenHarmony内核、Harmony南向开发、鸿蒙项目实战等等)鸿蒙(HarmonyOS NEXT)技术知识点。

希望这一份鸿蒙学习资料能够给大家带来帮助,有需要的小伙伴自行领取,限时开源,先到先得~无套路领取!!

获取这份完整版高清学习路线,请点击→纯血版全套鸿蒙HarmonyOS学习资料

鸿蒙(HarmonyOS NEXT)最新学习路线

  •  HarmonOS基础技能

  • HarmonOS就业必备技能 
  •  HarmonOS多媒体技术

  • 鸿蒙NaPi组件进阶

  • HarmonOS高级技能

  • 初识HarmonOS内核 
  • 实战就业级设备开发

有了路线图,怎么能没有学习资料呢,小编也准备了一份联合鸿蒙官方发布笔记整理收纳的一套系统性的鸿蒙(OpenHarmony )学习手册(共计1236页)鸿蒙(OpenHarmony )开发入门教学视频,内容包含:ArkTS、ArkUI、Web开发、应用模型、资源分类…等知识点。

获取以上完整版高清学习路线,请点击→纯血版全套鸿蒙HarmonyOS学习资料

《鸿蒙 (OpenHarmony)开发入门教学视频》

《鸿蒙生态应用开发V2.0白皮书》

图片

《鸿蒙 (OpenHarmony)开发基础到实战手册》

OpenHarmony北向、南向开发环境搭建

图片

 《鸿蒙开发基础》

  • ArkTS语言
  • 安装DevEco Studio
  • 运用你的第一个ArkTS应用
  • ArkUI声明式UI开发
  • .……

图片

 《鸿蒙开发进阶》

  • Stage模型入门
  • 网络管理
  • 数据管理
  • 电话服务
  • 分布式应用开发
  • 通知与窗口管理
  • 多媒体技术
  • 安全技能
  • 任务管理
  • WebGL
  • 国际化开发
  • 应用测试
  • DFX面向未来设计
  • 鸿蒙系统移植和裁剪定制
  • ……

图片

《鸿蒙进阶实战》

  • ArkTS实践
  • UIAbility应用
  • 网络案例
  • ……

图片

 获取以上完整鸿蒙HarmonyOS学习资料,请点击→纯血版全套鸿蒙HarmonyOS学习资料

总结

总的来说,华为鸿蒙不再兼容安卓,对中年程序员来说是一个挑战,也是一个机会。只有积极应对变化,不断学习和提升自己,他们才能在这个变革的时代中立于不败之地。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值