0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
会员中心
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

鸿蒙开发接口媒体:【@ohos.multimedia.audio (音频管理)】

jf_46214456 来源:jf_46214456 作者:jf_46214456 2024-05-31 09:53 次阅读

音频管理

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

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

  • [AudioManager]:音频管理。
  • [AudioRenderer]:音频渲染,用于播放PCM(Pulse Code Modulation)音频数据。
  • [AudioCapturer]:音频采集,用于录制PCM音频数据。

说明: 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 开发前请熟悉鸿蒙开发指导文档 :[gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md]

导入模块

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

audio.getAudioManager

getAudioManager(): AudioManager

获取音频管理器。

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

返回值:

类型说明
[AudioManager]音频管理类。

示例:

var audioManager = audio.getAudioManager();

audio.createAudioRenderer8+

createAudioRenderer(options: AudioRendererOptions, callback: AsyncCallback): void

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

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

参数

参数名类型必填说明
options[AudioRendererOptions]配置渲染器。
callbackAsyncCallback<[AudioRenderer]>音频渲染器对象。

示例:

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

var audioRendererInfo = {
    content: audio.ContentType.CONTENT_TYPE_SPEECH,
    usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION,
    rendererFlags: 1
}

var audioRendererOptions = {
    streamInfo: audioStreamInfo,
    rendererInfo: audioRendererInfo
}

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

audio.createAudioRenderer8+

createAudioRenderer(options: AudioRendererOptions): Promise

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

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

参数:

参数名类型必填说明
options[AudioRendererOptions]配置渲染器。

返回值:

类型说明
Promise<[AudioRenderer]>音频渲染器对象。

示例:

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

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

var audioRendererInfo = {
    content: audio.ContentType.CONTENT_TYPE_SPEECH,
    usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION,
    rendererFlags: 1
}

var audioRendererOptions = {
    streamInfo: audioStreamInfo,
    rendererInfo: audioRendererInfo
}

var audioRenderer;
audio.createAudioRenderer(audioRendererOptions).then((data) = > {
    audioRenderer = data;
    console.info('AudioFrameworkRenderLog: AudioRenderer Created : Success : Stream Type: SUCCESS');
}).catch((err) = > {
    console.info('AudioFrameworkRenderLog: AudioRenderer Created : ERROR : '+err.message);
});

audio.createAudioCapturer8+

createAudioCapturer(options: AudioCapturerOptions, callback: AsyncCallback): void

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

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

参数:

参数名类型必填说明
options[AudioCapturerOptions]配置音频采集器。
callbackAsyncCallback<[AudioCapturer]>音频采集器对象。

示例:

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

var audioCapturerInfo = {
    source: audio.SourceType.SOURCE_TYPE_MIC,
    capturerFlags: 1
}

var audioCapturerOptions = {
    streamInfo: audioStreamInfo,
    capturerInfo: audioCapturerInfo
}

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

audio.createAudioCapturer8+

createAudioCapturer(options: AudioCapturerOptions): Promise

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

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

参数:

参数名类型必填说明
options[AudioCapturerOptions]配置音频采集器。

返回值:

类型说明
Promise<[AudioCapturer]>音频采集器对象

示例:

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

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

var audioCapturerInfo = {
    source: audio.SourceType.SOURCE_TYPE_MIC,
    capturerFlags: 1
}

var audioCapturerOptions = {
    streamInfo: audioStreamInfo,
    capturerInfo: audioCapturerInfo
}

var audioCapturer;
audio.createAudioRenderer(audioCapturerOptions).then((data) = > {
    audioCapturer = data;
    console.info('AudioCapturer Created : Success : Stream Type: SUCCESS');
}).catch((err) = > {
    console.info('AudioCapturer Created : ERROR : '+err.message);
});

AudioVolumeType

枚举,音频流类型。

系统能力: 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Volume

名称默认值描述
VOICE_CALL8+0语音电话。
RINGTONE2铃声。
MEDIA3媒体。
VOICE_ASSISTANT8+9语音助手。

DeviceFlag

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

系统能力: 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Device

名称默认值描述
OUTPUT_DEVICES_FLAG1输出设备。
INPUT_DEVICES_FLAG2输入设备。
ALL_DEVICES_FLAG3所有设备。

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耳机,带麦克风。

ActiveDeviceType

枚举,活跃设备类型。

系统能力: 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Device

名称默认值描述
SPEAKER2扬声器。
BLUETOOTH_SCO7蓝牙设备SCO(Synchronous Connection Oriented)连接。

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位整数,小尾数。

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

枚举,音频内容类型。

系统能力: 以下各项对应的系统能力均为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_MEDIA1音频。
STREAM_USAGE_VOICE_COMMUNICATION2语音通信
STREAM_USAGE_NOTIFICATION_RINGTONE6通知铃声。

AudioState8+

枚举,音频状态。

系统能力: 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Core

名称默认值描述
STATE_INVALID-1无效状态。
STATE_NEW0创建新实例状态。
STATE_PREPARED1准备状态。
STATE_RUNNING2可运行状态。
STATE_STOPPED3停止状态。
STATE_RELEASED4释放状态。
STATE_PAUSED5暂停状态。

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提示音量恢复。

InterruptActionType

枚举,中断事件返回类型。

系统能力: 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Renderer

名称默认值描述
TYPE_ACTIVATED0表示触发焦点事件。
TYPE_INTERRUPT1表示音频打断事件。

AudioStreamInfo8+

音频流信息

系统能力: 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Core

名称类型必填说明
samplingRate[AudioSamplingRate]音频文件的采样率。
channels[AudioChannel]音频文件的通道数。
sampleFormat[AudioSampleFormat]音频采样格式。
encodingType[AudioEncodingType]音频编码格式。

AudioRendererInfo8+

音频渲染器信息。

系统能力: 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Core

名称类型必填说明
content[ContentType]媒体类型。
usage[StreamUsage]音频流使用类型。
rendererFlagsnumber音频渲染器标志。

AudioRendererOptions8+

音频渲染器选项信息。

系统能力: 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Renderer

名称类型必填说明
streamInfo[AudioStreamInfo]表示音频流信息。
rendererInfo[AudioRendererInfo]表示渲染器信息。

InterruptEvent9+

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

系统能力: 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Renderer

名称类型必填说明
eventType[InterruptType]中断事件类型,开始或是结束。
forceType[InterruptForceType]操作是由系统执行或是由应用程序执行。
hintType[InterruptHint]中断提示。

AudioInterrupt

音频监听事件传入的参数。

系统能力: 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Renderer

名称类型必填说明
streamUsage[StreamUsage]音频流使用类型。
contentType[ContentType]音频打断媒体类型。
pauseWhenDuckedboolean音频打断时是否可以暂停音频播放(true表示音频播放可以在音频打断期间暂停,false表示相反)。

InterruptAction

音频打断/获取焦点事件的回调方法。

系统能力: 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Renderer

名称类型必填说明
actionType[InterruptActionType]事件返回类型。TYPE_ACTIVATED为焦点触发事件,TYPE_INTERRUPT为音频打断事件。
type[InterruptType]打断事件类型。
hint[InterruptHint]打断事件提示。
activatedboolean获得/释放焦点。true表示焦点获取/释放成功,false表示焦点获得/释放失败。

VolumeEvent8+

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

此接口为系统接口,三方应用不支持调用。

系统能力: 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Volume

名称类型必填说明
volumeType[AudioVolumeType]音量流类型。
volumenumber音量等级,可设置范围通过getMinVolume和getMaxVolume获取。
updateUiboolean在UI中显示音量变化。

DeviceChangeAction

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

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

名称类型必填说明
type[DeviceChangeType]设备连接状态变化。
deviceDescriptors[AudioDeviceDescriptors]设备信息。

DeviceChangeType

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

系统能力: 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Device

名称默认值描述
CONNECT0设备连接。
DISCONNECT1断开设备连接。

AudioCapturerOptions8+

音频采集器选项信息。

系统能力: 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Capturer

名称类型必填说明
streamInfo[AudioStreamInfo]表示音频流信息。
capturerInfo[AudioCapturerInfo]表示采集器信息。

AudioCapturerInfo8+[]()

描述音频采集器信息。

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

名称类型必填说明
source[SourceType]音源类型。
capturerFlagsnumber音频采集器标志。

SourceType8+[]()

枚举,音源类型。

系统能力: 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Core

名称默认值描述
SOURCE_TYPE_INVALID-1无效的音频源。
SOURCE_TYPE_MIC0Mic音频源。
SOURCE_TYPE_VOICE_COMMUNICATION7语音通话场景的音频源。

AudioScene8+[]()

枚举,音频场景。

系统能力: 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Communication

名称默认值描述
AUDIO_SCENE_DEFAULT0默认音频场景。
AUDIO_SCENE_RINGING1响铃模式。 此接口为系统接口,三方应用不支持调用。
AUDIO_SCENE_PHONE_CALL2电话模式。 此接口为系统接口,三方应用不支持调用。
AUDIO_SCENE_VOICE_CHAT3语音聊天模式。

AudioManager

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

setVolume

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

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

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

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

参数:

参数名类型必填说明
volumeType[AudioVolumeType]音量流类型。
volumenumber音量等级,可设置范围通过getMinVolume和getMaxVolume获取。
callbackAsyncCallback回调表示成功还是失败。

示例:

audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) = > {
    if (err) {
        console.error('Failed to set the volume. ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate a successful volume setting.');
});

setVolume

setVolume(volumeType: AudioVolumeType, volume: number): Promise

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

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

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

参数:

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

返回值:

类型说明
PromisePromise回调表示成功还是失败。

示例:

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

getVolume

getVolume(volumeType: AudioVolumeType, callback: AsyncCallback): void

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

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

参数:

参数名类型必填说明
volumeType[AudioVolumeType]音量流类型。
callbackAsyncCallback回调返回音量大小。

示例:

audioManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) = > {
   if (err) {
       console.error('Failed to obtain the volume. ${err.message}');
       return;
   }
   console.log('Callback invoked to indicate that the volume is obtained.');
});

getVolume

getVolume(volumeType: AudioVolumeType): Promise

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

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

参数:

参数名类型必填说明
volumeType[AudioVolumeType]音量流类型。

返回值:

类型说明
PromisePromise回调返回音量大小。

示例:

audioManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) = > {
    console.log('Promise returned to indicate that the volume is obtained.' + value);
});

getMinVolume

getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback): void

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

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

参数:

参数名类型必填说明
volumeType[AudioVolumeType]音量流类型。
callbackAsyncCallback回调返回最小音量。

示例:

audioManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) = > {
    if (err) {
        console.error('Failed to obtain the minimum volume. ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate that the minimum volume is obtained.' + value);
});

getMinVolume

getMinVolume(volumeType: AudioVolumeType): Promise

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

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

参数:

参数名类型必填说明
volumeType[AudioVolumeType]音量流类型。

返回值:

类型说明
PromisePromise回调返回最小音量。

示例:

audioManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) = > {
    console.log('Promised returned to indicate that the minimum volume is obtained.' + value);
});

getMaxVolume

getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback): void

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

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

参数:

参数名类型必填说明
volumeType[AudioVolumeType]音量流类型。
callbackAsyncCallback回调返回最大音量大小。

示例:

audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) = > {
    if (err) {
        console.error('Failed to obtain the maximum volume. ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate that the maximum volume is obtained.' + value);
});

getMaxVolume

getMaxVolume(volumeType: AudioVolumeType): Promise

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

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

参数:

参数名类型必填说明
volumeType[AudioVolumeType]音量流类型。

返回值:

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

示例:

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

mute

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

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

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

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

参数:

参数名类型必填说明
volumeType[AudioVolumeType]音量流类型。
muteboolean静音状态,true为静音,false为非静音。
callbackAsyncCallback回调表示成功还是失败。

示例:

audioManager.mute(audio.AudioVolumeType.MEDIA, true, (err) = > {
    if (err) {
        console.error('Failed to mute the stream. ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate that the stream is muted.');
});

mute

mute(volumeType: AudioVolumeType, mute: boolean): Promise

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

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

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

参数:

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

返回值:

类型说明
PromisePromise回调表示成功还是失败。

示例:

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

isMute

isMute(volumeType: AudioVolumeType, callback: AsyncCallback): void

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

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

参数:

参数名类型必填说明
volumeType[AudioVolumeType]音量流类型。
callbackAsyncCallback回调返回流静音状态,true为静音,false为非静音。

示例:

audioManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) = > {
   if (err) {
       console.error('Failed to obtain the mute status. ${err.message}');
       return;
   }
   console.log('Callback invoked to indicate that the mute status of the stream is obtained.' + value);
});

isMute

isMute(volumeType: AudioVolumeType): Promise

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

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

参数:

参数名类型必填说明
volumeType[AudioVolumeType]音量流类型。

返回值:

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

示例:

audioManager.isMute(audio.AudioVolumeType.MEDIA).then((value) = > {
    console.log('Promise returned to indicate that the mute status of the stream is obtained.' + value);
});

isActive

isActive(volumeType: AudioVolumeType, callback: AsyncCallback): void

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

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

参数:

参数名类型必填说明
volumeType[AudioVolumeType]音量流类型。
callbackAsyncCallback回调返回流的活跃状态,true为活跃,false为不活跃。

示例:

audioManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) = > {
    if (err) {
        console.error('Failed to obtain the active status of the stream. ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate that the active status of the stream is obtained.' + value);
});

isActive

isActive(volumeType: AudioVolumeType): Promise

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

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

参数:

参数名类型必填说明
volumeType[AudioVolumeType]音量流类型。

返回值:

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

示例:

audioManager.isActive(audio.AudioVolumeType.MEDIA).then((value) = > {
    console.log('Promise returned to indicate that the active status of the stream is obtained.' + value);
});

setRingerMode

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

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

需要权限: ohos.permission.ACCESS_NOTIFICATION_POLICY,仅在静音和非静音状态切换时需要该权限。

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

参数:

参数名类型必填说明
mode[AudioRingMode]音频铃声模式。
callbackAsyncCallback回调返回设置成功或失败。

示例:

audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) = > {
   if (err) {
       console.error('Failed to set the ringer mode.​ ${err.message}');
       return;
    }
    console.log('Callback invoked to indicate a successful setting of the ringer mode.');
});

setRingerMode

setRingerMode(mode: AudioRingMode): Promise

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

需要权限: ohos.permission.ACCESS_NOTIFICATION_POLICY,仅在静音和非静音状态切换时需要该权限。

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

参数:

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

返回值:

类型说明
PromisePromise回调返回设置成功或失败。

示例:

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

getRingerMode

getRingerMode(callback: AsyncCallback): void

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

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

参数:

参数名类型必填说明
callbackAsyncCallback<[AudioRingMode]>回调返回系统的铃声模式。

示例:

audioManager.getRingerMode((err, value) = > {
   if (err) {
       console.error('Failed to obtain the ringer mode.​ ${err.message}');
       return;
   }
   console.log('Callback invoked to indicate that the ringer mode is obtained.' + value);
});

getRingerMode

getRingerMode(): Promise

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

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

返回值:

类型说明
Promise<[AudioRingMode]>Promise回调返回系统的铃声模式。

示例:

audioManager.getRingerMode().then((value) = > {
    console.log('Promise returned to indicate that the ringer mode is obtained.' + value);
});

setAudioParameter

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

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

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

需要权限: ohos.permission.MODIFY_AUDIO_SETTINGS

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

参数:

参数名类型必填说明
keystring被设置的音频参数的键。
valuestring被设置的音频参数的值。
callbackAsyncCallback回调返回设置成功或失败。

示例:

audioManager.setAudioParameter('key_example', 'value_example', (err) = > {
    if (err) {
        console.error('Failed to set the audio parameter. ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate a successful setting of the audio parameter.');
});

setAudioParameter

setAudioParameter(key: string, value: string): Promise

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

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

需要权限: ohos.permission.MODIFY_AUDIO_SETTINGS

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

参数:

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

返回值:

类型说明
PromisePromise回调返回设置成功或失败。

示例:

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

getAudioParameter

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

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

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

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

参数:

参数名类型必填说明
keystring待获取的音频参数的键。
callbackAsyncCallback回调返回获取的音频参数的值。

示例:

audioManager.getAudioParameter('key_example', (err, value) = > {
    if (err) {
        console.error('Failed to obtain the value of the audio parameter. ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate that the value of the audio parameter is obtained.' + value);
});

getAudioParameter

getAudioParameter(key: string): Promise

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

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

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

参数:

参数名类型必填说明
keystring待获取的音频参数的键。

返回值:

类型说明
PromisePromise回调返回获取的音频参数的值。

示例:

audioManager.getAudioParameter('key_example').then((value) = > {
    console.log('Promise returned to indicate that the value of the audio parameter is obtained.' + value);
});

getDevices

getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback): void

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

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

参数:

参数名类型必填说明
deviceFlag[DeviceFlag]设备类型的flag。
callbackAsyncCallback<[AudioDeviceDescriptors]>回调,返回设备列表。

示例:

audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) = > {
   if (err) {
       console.error('Failed to obtain the device list. ${err.message}');
       return;
   }
   console.log('Callback invoked to indicate that the device list is obtained.');
});

getDevices

getDevices(deviceFlag: DeviceFlag): Promise

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

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

参数:

参数名类型必填说明
deviceFlag[DeviceFlag]设备类型的flag。

返回值:

类型说明
Promise<[AudioDeviceDescriptors]>Promise回调返回设备列表。

示例:

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

setDeviceActive

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

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

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

参数:

参数名类型必填说明
deviceType[ActiveDeviceType]活跃音频设备类型。
activeboolean设备激活状态。
callbackAsyncCallback回调返回设置成功或失败。

示例:

audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true, (err) = > {
    if (err) {
        console.error('Failed to set the active status of the device. ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate that the device is set to the active status.');
});

setDeviceActive

setDeviceActive(deviceType: ActiveDeviceType, active: boolean): Promise

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

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

参数:

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

返回值:

类型说明
PromisePromise回调返回设置成功或失败。

示例:

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

isDeviceActive

isDeviceActive(deviceType: ActiveDeviceType, callback: AsyncCallback): void

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

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

参数:

参数名类型必填说明
deviceType[ActiveDeviceType]活跃音频设备类型。
callbackAsyncCallback回调返回设备的激活状态。

示例:

audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER, (err, value) = > {
    if (err) {
        console.error('Failed to obtain the active status of the device. ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate that the active status of the device is obtained.');
});

isDeviceActive

isDeviceActive(deviceType: ActiveDeviceType): Promise

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

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

参数:

参数名类型必填说明
deviceType[ActiveDeviceType]活跃音频设备类型。

返回值:

TypeDescription
PromisePromise回调返回设备的激活状态。

示例:

audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER).then((value) = > {
    console.log('Promise returned to indicate that the active status of the device is obtained.' + value);
});

setMicrophoneMute

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

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

需要权限: ohos.permission.MICROPHONE

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

参数:

参数名类型必填说明
muteboolean待设置的静音状态,true为静音,false为非静音。
callbackAsyncCallback回调返回设置成功或失败。

示例:

audioManager.setMicrophoneMute(true, (err) = > {
    if (err) {
        console.error('Failed to mute the microphone. ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate that the microphone is muted.');
});

setMicrophoneMute

setMicrophoneMute(mute: boolean): Promise

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

需要权限: ohos.permission.MICROPHONE

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

参数:

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

返回值:

类型说明
PromisePromise回调返回设置成功或失败。

示例:

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

isMicrophoneMute

isMicrophoneMute(callback: AsyncCallback): void

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

需要权限: ohos.permission.MICROPHONE

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

参数:

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

示例:

audioManager.isMicrophoneMute((err, value) = > {
    if (err) {
        console.error('Failed to obtain the mute status of the microphone. ${err.message}');
        return;
    }
    console.log('Callback invoked to indicate that the mute status of the microphone is obtained.' + value);
});

isMicrophoneMute

isMicrophoneMute(): Promise

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

需要权限: ohos.permission.MICROPHONE

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

返回值:

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

示例:

audioManager.isMicrophoneMute().then((value) = > {
    console.log('Promise returned to indicate that the mute status of the microphone is obtained.', + value);
});

on('volumeChange')8+

on(type: 'volumeChange', callback: Callback): void

监听系统音量变化事件。

此接口为系统接口,三方应用不支持调用。

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

参数:

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

示例:

audioManager.on('volumeChange', (volumeEvent) = > {
    console.log('VolumeType of stream: ' + volumeEvent.volumeType);
    console.log('Volume level: ' + volumeEvent.volume);
    console.log('Whether to updateUI: ' + volumeEvent.updateUi);
});

on('ringerModeChange')8+

on(type: 'ringerModeChange', callback: Callback): void

监听铃声模式变化事件。

此接口为系统接口,三方应用不支持调用。

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

参数:

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

示例:

audioManager.on('ringerModeChange', (ringerMode) = > {
    console.log('Updated ringermode: ' + ringerMode);
});

on('deviceChange')

on(type: 'deviceChange', callback: Callback): void

设备更改。音频设备连接状态变化。

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

参数:

参数名类型必填说明
typestring订阅的事件的类型。支持事件:'deviceChange'
callbackCallback<[DeviceChangeAction]>获取设备更新详情。

示例:

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

off('deviceChange')

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

取消订阅音频设备连接变化事件。

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

参数:

参数名类型必填说明
typestring订阅的事件的类型。支持事件:'deviceChange'
callbackCallback<[DeviceChangeAction]>获取设备更新详情。

示例:

audioManager.off('deviceChange', (deviceChanged) = > {
    console.log("Should be no callback.");
});

on('interrupt')

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

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

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

参数:

参数名类型必填说明
typestring音频打断事件回调类型,支持的事件为:'interrupt'(多应用之间第二个应用会打断第一个应用,触发该事件)。
interruptAudioInterrupt音频打断事件类型的参数。
callbackCallback<[InterruptAction]>音频打断事件回调方法。

示例:

var interAudioInterrupt = {
    streamUsage:2,
    contentType:0,
    pauseWhenDucked:true
};
audioManager.on('interrupt', interAudioInterrupt, (InterruptAction) = > {
    if (InterruptAction.actionType === 0) {
        console.log("An event to gain the audio focus starts.");
        console.log("Focus gain event:" + JSON.stringify(InterruptAction));
    }
    if (InterruptAction.actionType === 1) {
        console.log("An audio interruption event starts.");
        console.log("Audio interruption event:" + JSON.stringify(InterruptAction));
    }
});

off('interrupt')

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

取消监听音频打断事件(删除监听事件,取消打断)

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

参数:

参数名类型必填说明
typestring音频打断事件回调类型,支持的事件为:'interrupt'(多应用之间第二个应用会打断第一个应用,触发该事件)。
interruptAudioInterrupt音频打断事件类型的参数。
callbackCallback<[InterruptAction]>音频打断事件回调方法。

示例:

var interAudioInterrupt = {
    streamUsage:2,
    contentType:0,
    pauseWhenDucked:true
};
audioManager.off('interrupt', interAudioInterrupt, (InterruptAction) = > {
    if (InterruptAction.actionType === 0) {
        console.log("An event to release the audio focus starts.");
        console.log("Focus release event:" + JSON.stringify(InterruptAction));
    }
});

setAudioScene8+

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

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

此接口为系统接口,三方应用不支持调用。

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

参数:

参数名类型必填说明
scene[AudioScene]音频场景模式。
callbackAsyncCallback用于返回结果的回调。

示例:

audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL, (err) = > {
   if (err) {
       console.error('Failed to set the audio scene mode.​ ${err.message}');
       return;
    }
    console.log('Callback invoked to indicate a successful setting of the audio scene mode.');
});

setAudioScene8+

setAudioScene(scene: AudioScene): Promise

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

此接口为系统接口,三方应用不支持调用。

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

参数:

参数名类型必填说明
scene[AudioScene]音频场景模式。

返回值:

类型说明
Promise用于返回结果的回调。

示例:

audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL).then(() = > {
    console.log('Promise returned to indicate a successful setting of the audio scene mode.');
}).catch ((err) = > {
    console.log('Failed to set the audio scene mode');
});

getAudioScene8+

getAudioScene(callback: AsyncCallback): void

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

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

参数:

参数名类型必填说明
callbackAsyncCallback<[AudioScene]>用于返回音频场景模式的回调。

示例:

audioManager.getAudioScene((err, value) = > {
   if (err) {
       console.error('Failed to obtain the audio scene mode.​ ${err.message}');
       return;
   }
   console.log('Callback invoked to indicate that the audio scene mode is obtained.' + value);
});

getAudioScene8+

getAudioScene(): Promise

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

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

返回值:

类型说明
Promise<[AudioScene]>用于返回音频场景模式的回调。

示例:

audioManager.getAudioScene().then((value) = > {
    console.log('Promise returned to indicate that the audio scene mode is obtained.' + value);
}).catch ((err) = > {
    console.log('Failed to obtain the audio scene mode');
});

AudioDeviceDescriptor

描述音频设备。

系统能力: 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Device

名称类型可读可写说明
deviceRole[DeviceRole]设备角色。
deviceType[DeviceType]设备类型。

AudioDeviceDescriptors

设备属性数组类型,为[AudioDeviceDescriptor]的数组,只读。

示例:

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

function displayDeviceProp(value) {
    deviceRoleValue = value.deviceRole;
    deviceTypeValue = value.deviceType;

}

var deviceRoleValue = null;
var deviceTypeValue = null;
const promise = audio.getAudioManager().getDevices(1);
promise.then(function (value) {
    console.info('AudioFrameworkTest: Promise: getDevices OUTPUT_DEVICES_FLAG');
    value.forEach(displayDeviceProp);
    if (deviceTypeValue != null && deviceRoleValue != null){
        console.info('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG :  PASS');
    }
    else{
        console.info('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG :  FAIL');
    }
});

AudioRenderer8+

提供音频渲染的相关接口。在调用AudioRenderer的接口前,需要先通过[createAudioRenderer]创建实例。

属性

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

名称类型可读可写说明
state8+[AudioState]音频渲染器的状态。

示例:

var state = audioRenderer.state;

getRendererInfo8+

getRendererInfo(callback: AsyncCallback): void

获取当前被创建的音频渲染器的信息,使用callback方式异步返回结果。

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

参数:

参数名类型必填说明
callbackAsyncCallback<[AudioRendererInfo]>返回音频渲染器的信息。

示例:

audioRenderer.getRendererInfo((err, rendererInfo) = > {
    console.log('Renderer GetRendererInfo:');
    console.log('Renderer content:' + rendererInfo.content);
    console.log('Renderer usage:' + rendererInfo.usage);
    console.log('Renderer flags:' + rendererInfo.rendererFlags);
});

getRendererInfo8+

getRendererInfo(): Promise

获取当前被创建的音频渲染器的信息,使用Promise方式异步返回结果。

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

返回值:

类型说明
Promise<[AudioRendererInfo]>Promise用于返回音频渲染器信息。

示例:

var resultFlag = true;
audioRenderer.getRendererInfo().then((rendererInfo) = > {
    console.log('Renderer GetRendererInfo:');
    console.log('Renderer content:' + rendererInfo.content);
    console.log('Renderer usage:' + rendererInfo.usage);
    console.log('Renderer flags:' + rendererInfo.rendererFlags);
}).catch((err) = > {
    console.log('AudioFrameworkRenderLog: RendererInfo :ERROR: '+err.message);
    resultFlag = false;
});

getStreamInfo8+

getStreamInfo(callback: AsyncCallback): void

获取音频流信息,使用callback方式异步返回结果。

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

参数:

参数名类型必填说明
callbackAsyncCallback<[AudioStreamInfo]>回调返回音频流信息。

示例:

audioRenderer.getStreamInfo((err, streamInfo) = > {
    console.log('Renderer GetStreamInfo:');
    console.log('Renderer sampling rate:' + streamInfo.samplingRate);
    console.log('Renderer channel:' + streamInfo.channels);
    console.log('Renderer format:' + streamInfo.sampleFormat);
    console.log('Renderer encoding type:' + streamInfo.encodingType);
});

getStreamInfo8+

getStreamInfo(): Promise

获取音频流信息,使用Promise方式异步返回结果。

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

返回值:

类型说明
Promise<[AudioStreamInfo]>Promise返回音频流信息.

示例:

audioRenderer.getStreamInfo().then((streamInfo) = > {
    console.log('Renderer GetStreamInfo:');
    console.log('Renderer sampling rate:' + streamInfo.samplingRate);
    console.log('Renderer channel:' + streamInfo.channels);
    console.log('Renderer format:' + streamInfo.sampleFormat);
    console.log('Renderer encoding type:' + streamInfo.encodingType);
}).catch((err) = > {
    console.log('ERROR: '+err.message);
});

start8+

start(callback: AsyncCallback): void

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

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

参数:

参数名类型必填说明
callbackAsyncCallback回调函数。

示例:

audioRenderer.start((err) = > {
    if (err) {
        console.error('Renderer start failed.');
    } else {
        console.info('Renderer start success.');
    }
});

start8+

start(): Promise

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

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

返回值:

类型说明
PromisePromise方式异步返回结果。

示例:

audioRenderer.start().then(() = > {
    console.log('Renderer started');
}).catch((err) = > {
    console.log('ERROR: '+err.message);
});

pause8+

pause(callback: AsyncCallback): void

暂停渲染。使用callback方式异步返回结果。

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

参数:

参数名类型必填说明
callbackAsyncCallback返回回调的结果。

示例:

audioRenderer.pause((err) = > {
    if (err) {
        console.error('Renderer pause failed');
    } else {
        console.log('Renderer paused.');
    }
});

pause8+

pause(): Promise

暂停渲染。使用Promise方式异步返回结果。

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

返回值:

类型说明
PromisePromise方式异步返回结果。

示例:

audioRenderer.pause().then(() = > {
    console.log('Renderer paused');
}).catch((err) = > {
    console.log('ERROR: '+err.message);
});

drain8+

drain(callback: AsyncCallback): void

检查缓冲区是否已被耗尽。使用callback方式异步返回结果。

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

参数:

参数名类型必填说明
callbackAsyncCallback返回回调的结果。

示例:

audioRenderer.drain((err) = > {
    if (err) {
        console.error('Renderer drain failed');
    } else {
        console.log('Renderer drained.');
    }
});

drain8+

drain(): Promise

检查缓冲区是否已被耗尽。使用Promise方式异步返回结果。

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

返回值:

类型说明
PromisePromise方式异步返回结果。

示例:

audioRenderer.drain().then(() = > {
    console.log('Renderer drained successfully');
}).catch((err) = > {
    console.log('ERROR: '+err.message);
});

stop8+

stop(callback: AsyncCallback): void

停止渲染。使用callback方式异步返回结果。

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

参数:

参数名类型必填说明
callbackAsyncCallback返回回调的结果。

示例:

audioRenderer.stop((err) = > {
    if (err) {
        console.error('Renderer stop failed');
    } else {
        console.log('Renderer stopped.');
    }
});

stop8+

stop(): Promise

停止渲染。使用Promise方式异步返回结果。

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

返回值:

类型说明
PromisePromise方式异步返回结果。

示例:

audioRenderer.stop().then(() = > {
    console.log('Renderer stopped successfully');
}).catch((err) = > {
    console.log('ERROR: '+err.message);
});

release8+

release(callback: AsyncCallback): void

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

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

参数:

参数名类型必填说明
callbackAsyncCallback返回回调的结果。

示例:

audioRenderer.release((err) = > {
    if (err) {
        console.error('Renderer release failed');
    } else {
        console.log('Renderer released.');
    }
});

release8+

release(): Promise

释放渲染器。使用Promise方式异步返回结果。

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

返回值:

类型说明
PromisePromise方式异步返回结果。

示例:

audioRenderer.release().then(() = > {
    console.log('Renderer released successfully');
}).catch((err) = > {
    console.log('ERROR: '+err.message);
});

write8+

write(buffer: ArrayBuffer, callback: AsyncCallback): void

写入缓冲区。使用callback方式异步返回结果。

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

参数:

参数名类型必填说明
bufferArrayBuffer要写入缓冲区的数据。
callbackAsyncCallback回调如果成功,返回写入的字节数,否则返回errorcode。

示例:

import audio from '@ohos.multimedia.audio';
import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility'

var audioStreamInfo = {
    samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000,
    channels: audio.AudioChannel.CHANNEL_2,
    sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE,
    encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
}

var audioRendererInfo = {
    content: audio.ContentType.CONTENT_TYPE_SPEECH,
    usage: audio.streamUsage.STREAM_USAGE_VOICE_COMMUNICATION
    rendererFlags: 1
}

var audioRendererOptions = {
    streamInfo: audioStreamInfo,
    rendererInfo: audioRendererInfo
}
var audioRenderer;
audio.createAudioRenderer(audioRendererOptions).then((data)= > {
    audioRenderer = data;
    console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS');
    }).catch((err) = > {
    console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: '+err.message);
    });
var bufferSize;
audioRenderer.getBufferSize().then((data)= > {
    console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS '+data);
    bufferSize = data;
    }).catch((err) = > {
    console.info.('AudioFrameworkRenderLog: getBufferSize: ERROR: '+err.message);
    });
console.info('Buffer size:'+bufferSize);
var context = featureAbility.getContext();
var path = await context.getCacheDir();
var filePath = path+"/StarWars10s-2C-48000-4SW.wav"
let ss = fileio.createStreamSync(filePath, 'r');
let buf = new ArrayBuffer(bufferSize);
ss.readSync(buf);
audioRenderer.write(buf, (err, writtenbytes) = > {
    if (writtenbytes < 0) {
        console.error('write failed.');
    } else {
       console.log('Actual written bytes: ' + writtenbytes);
    }
});

write8+

write(buffer: ArrayBuffer): Promise

写入缓冲区。使用Promise方式异步返回结果。

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

返回值:

类型说明
PromisePromise返回结果,如果成功,返回写入的字节数,否则返回errorcode。

示例:

import audio from '@ohos.multimedia.audio';
import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility'

var audioStreamInfo = {
    samplingRate:audio.AudioSamplingRate.SAMPLE_RATE_48000,
    channels:audio.AudioChannel.CHANNEL_2,
    sampleFormat.audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE,
    encodingType.audio.AudioEncodingType.ENCODING_TYPE_RAW
}

var audioRendererInfo = {
    content: audio.ContentType.CONTENT_TYPE_SPEECH,
    usage: audio.streamUsage.STREAM_USAGE_VOICE_COMMUNICATION,
    rendererFlags: 1
}

var audioRendererOptions = {
    streamInfo: audioStreamInfo,
    rendererInfo: audioRendererInfo
}
var audioRenderer;
audio.createAudioRenderer(audioRendererOptions).then((data) = > {
    audioRenderer = data;
    console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS');
    }).catch((err) = > {
    console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: '+err.message);
    });
var bufferSize;
audioRenderer.getBufferSize().then((data) = > {
    console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS '+data);
    bufferSize = data;
    }).catch((err) = > {
    console.info('AudioFrameworkRenderLog: getBufferSize: ERROR: '+err.message);
    });
console.info('BufferSize: ' + bufferSize);
var context = featureAbility.getContext();
var path = await context.getCacheDir();
var filePath = 'data/StarWars10s-2C-48000-4SW.wav';
let ss = fileio.createStreamSync(filePath, 'r');
let buf = new ArrayBuffer(bufferSize);
ss.readSync(buf);
audioRenderer.write(buf).then((writtenbytes) = > {
    if (writtenbytes < 0) {
        console.error('write failed.');
    } else {
        console.log('Actual written bytes: ' + writtenbytes);
    }
}).catch((err) = > {
    console.log('ERROR: '+err.message);
});

getAudioTime8+

getAudioTime(callback: AsyncCallback): void

获取时间戳(从 1970 年 1 月 1 日开始)。使用callback方式异步返回结果。

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

参数:

参数名类型必填说明
callbackAsyncCallback回调返回时间戳。

示例:

audioRenderer.getAudioTime((err, timestamp) = > {
    console.log('Current timestamp: ' + timestamp);
});

getAudioTime8+

getAudioTime(): Promise

获取时间戳(从 1970 年 1 月 1 日开始)。使用Promise方式异步返回结果。

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

返回值:

类型描述
PromisePromise回调返回时间戳。

示例:

audioRenderer.getAudioTime().then((timestamp) = > {
    console.log('Current timestamp: ' + timestamp);
}).catch((err) = > {
    console.log('ERROR: '+err.message);
});

getBufferSize8+

getBufferSize(callback: AsyncCallback): void

获取音频渲染器的最小缓冲区大小。使用callback方式异步返回结果。

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

参数:

参数名类型必填说明
callbackAsyncCallback回调返回缓冲区大小。

示例:

var bufferSize = audioRenderer.getBufferSize(async(err, bufferSize) = > {
    if (err) {
        console.error('getBufferSize error');
    }
});

getBufferSize8+

getBufferSize(): Promise

获取音频渲染器的最小缓冲区大小。使用Promise方式异步返回结果。

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

返回值:

类型说明
Promisepromise回调返回缓冲区大小。

示例:

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

var audioStreamInfo = {
    samplingRate:audio.AudioSamplingRate.SAMPLE_RATE_48000,
    channels:audio.AudioChannel.CHANNEL_2,
    sampleFormat.audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE,
    encodingType.audio.AudioEncodingType.ENCODING_TYPE_RAW
}

var audioRendererInfo = {
    content: audio.ContentType.CONTENT_TYPE_SPEECH,
    usage: audio.streamUsage.STREAM_USAGE_VOICE_COMMUNICATION,
    rendererFlags: 1
}

var audioRendererOptions = {
    streamInfo: audioStreamInfo,
    rendererInfo: audioRendererInfo
}
var audioRenderer;
audio.createAudioRenderer(audioRendererOptions).then((data) = > {
    audioRenderer = data;
    console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS');
    }).catch((err) = > {
    console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: '+err.message);
    });
var bufferSize;
audioRenderer.getBufferSize().then((data) = > {
    console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS '+data);
    bufferSize=data;
}).catch((err) = > {
    console.info('AudioFrameworkRenderLog: getBufferSize: ERROR: '+err.message);
});

setRenderRate8+

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

设置音频渲染速率。使用callback方式异步返回结果。

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

参数:

参数名类型必填说明
rate[AudioRendererRate]渲染的速率。
callbackAsyncCallback用于返回执行结果的回调。

示例:

audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL, (err) = > {
    if (err) {
        console.error('Failed to set params');
    } else {
        console.log('Callback invoked to indicate a successful render rate setting.');
    }
});

setRenderRate8+

setRenderRate(rate: AudioRendererRate): Promise

设置音频渲染速率。使用Promise方式异步返回结果。

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

参数:

参数名类型必填说明
rate[AudioRendererRate]渲染的速率。

返回值:

类型说明
PromisePromise用于返回执行结果。

示例:

audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL).then(() = > {
    console.log('setRenderRate SUCCESS');
}).catch((err) = > {
    console.log('ERROR: '+err.message);
});

getRenderRate8+

getRenderRate(callback: AsyncCallback): void

获取当前渲染速率。使用callback方式异步返回结果。

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

参数:

参数名类型必填说明
callbackAsyncCallback<[AudioRendererRate]>回调返回渲染速率。

示例:

audioRenderer.getRenderRate((err, renderrate) = > {
    console.log('getRenderRate: ' + renderrate);
});

getRenderRate8+

getRenderRate(): Promise

获取当前渲染速率。使用Promise方式异步返回结果。

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

返回值:

类型说明
Promise<[AudioRendererRate]>Promise回调返回渲染速率。

示例:

audioRenderer.getRenderRate().then((renderRate) = > {
    console.log('getRenderRate: ' + renderRate);
}).catch((err) = > {
    console.log('ERROR: '+err.message);
});

on('interrupt')9+

on(type: 'interrupt', callback: Callback): void

监听音频中断事件。使用callback获取中断事件。

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

参数:

参数名类型必填说明
typestring事件回调类型,支持的事件为:'interrupt'(中断事件被触发,音频播放被中断。)
callbackCallback<[InterruptEvent]>被监听的中断事件的回调。

示例:

var isPlay;
var started;
audioRenderer.on('interrupt', async(interruptEvent) = > {
    if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) {
        switch (interruptEvent.hintType) {
            case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
                console.log('Force paused. Stop writing');
                isPlay = false;
                break;
            case audio.InterruptHint.INTERRUPT_HINT_STOP:
                console.log('Force stopped. Stop writing');
                isPlay = false;
                break;
        }
    } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) {
        switch (interruptEvent.hintType) {
            case audio.InterruptHint.INTERRUPT_HINT_RESUME:
                console.log('Resume force paused renderer or ignore');
                await audioRenderer.start().then(async function () {
                    console.info('AudioInterruptMusic: renderInstant started :SUCCESS ');
                    started = true;
                }).catch((err) = > {
                    console.info('AudioInterruptMusic: renderInstant start :ERROR : '+err.message);
                    started = false;
                });
                if (started) {
                    isPlay = true;
                    console.info('AudioInterruptMusic Renderer started : isPlay : '+isPlay);
                } else {
                    console.error('AudioInterruptMusic Renderer start failed');
                }
                break;
            case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
                console.log('Choose to pause or ignore');
                if (isPlay == true) {
                    isPlay == false;
                    console.info('AudioInterruptMusic: Media PAUSE : TRUE');
                }
                else {
                    isPlay = true;
                    console.info('AudioInterruptMusic: Media PLAY : TRUE');
                }
                break;
        }
    }
});

on('markReach')8+

on(type: 'markReach', frame: number, callback: (position: number) => {}): void

订阅到达标记的事件。 当渲染的帧数达到 frame 参数的值时,回调被调用。

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

参数:

参数名类型必填说明
typestring事件回调类型,支持的事件为:'markReach'。
framenumber触发事件的帧数。 该值必须大于 0。
callback(position: number) => {}触发事件时调用的回调。

示例:

audioRenderer.on('markReach', 1000, (position) = > {
    if (position == 1000) {
        console.log('ON Triggered successfully');
    }
});

off('markReach') 8+

off(type: 'markReach'): void

取消订阅标记事件。

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

参数:

参数名类型必填说明
typestring要取消订阅事件的类型。支持的事件为:'markReach'。

示例:

audioRenderer.off('markReach');

on('periodReach') 8+

on(type: "periodReach", frame: number, callback: (position: number) => {}): void

订阅到达标记的事件。 当渲染的帧数达到 frame 参数的值时,回调被循环调用。

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

参数:

参数名类型必填说明
typestring事件回调类型,支持的事件为:'periodReach'。
framenumber触发事件的帧数。 该值必须大于 0。
callback(position: number) => {}触发事件时调用的回调。

示例:

audioRenderer.on('periodReach', 1000, (position) = > {
    if (position == 1000) {
        console.log('ON Triggered successfully');
    }
});

off('periodReach') 8+

off(type: 'periodReach'): void

取消订阅标记事件。

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

参数:

参数名类型必填说明
typestring要取消订阅事件的类型。支持的事件为:'periodReach'。

示例:

audioRenderer.off('periodReach')

on('stateChange') 8+

on(type: 'stateChange', callback: Callback): void

订阅监听状态变化。

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

参数:

参数名类型必填说明
typestring事件回调类型,支持的事件为:'stateChange'。
callback[AudioState]返回监听的状态。

示例:

audioRenderer.on('stateChange', (state) = > {
    if (state == 1) {
        console.log("audio renderer state is: STATE_PREPARED");
    }
    if (state == 2) {
        console.log("audio renderer state is: STATE_RUNNING");
    }
});

AudioCapturer8+

提供音频采集的相关接口。在调用AudioCapturer的接口前,需要先通过[createAudioCapturer]创建实例。

属性

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

名称类型可读可写说明
state8+[AudioState]音频采集器状态。

示例:

var state = audioCapturer.state;

getCapturerInfo8+

getCapturerInfo(callback: AsyncCallback): void

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

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

参数:

参数名类型必填说明
callbackAsyncCallback使用callback方式异步返回采集器信息。

示例:

audioCapturer.getCapturerInfo((err, capturerInfo) = > {
    if (err) {
        console.error('Failed to get capture info');
    } else {
        console.log('Capturer getCapturerInfo:');
        console.log('Capturer source:' + capturerInfo.source);
        console.log('Capturer flags:' + capturerInfo.capturerFlags);
    }
});

getCapturerInfo8+

getCapturerInfo(): Promise

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

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

返回值:

类型说明
Promise<[AudioCapturerInfo]>使用Promise方式异步返回采集器信息。

示例:

audioCapturer.getCapturerInfo().then((audioParamsGet) = > {
    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) = > {
    console.log('AudioFrameworkRecLog: CapturerInfo :ERROR: '+err.message);
});

getStreamInfo8+

getStreamInfo(callback: AsyncCallback): void

获取采集器流信息。使用callback方式异步返回结果。

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

参数:

参数名类型必填说明
callbackAsyncCallback<[AudioStreamInfo]>使用callback方式异步返回流信息。

示例:

audioCapturer.getStreamInfo((err, streamInfo) = > {
    if (err) {
        console.error('Failed to get stream info');
    } else {
        console.log('Capturer GetStreamInfo:');
        console.log('Capturer sampling rate:' + streamInfo.samplingRate);
        console.log('Capturer channel:' + streamInfo.channels);
        console.log('Capturer format:' + streamInfo.sampleFormat);
        console.log('Capturer encoding type:' + streamInfo.encodingType);
    }
});

getStreamInfo8+

getStreamInfo(): Promise

获取采集器流信息。使用Promise方式异步返回结果。

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

返回值:

类型说明
Promise<[AudioStreamInfo]>使用Promise方式异步返回流信息。

示例:

audioCapturer.getStreamInfo().then((audioParamsGet) = > {
    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) = > {
    console.log('getStreamInfo :ERROR: ' + err.message);
});

start8+

start(callback: AsyncCallback): void

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

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

参数

参数名类型必填说明
callbackAsyncCallback使用callback方式异步返回结果。

示例:

audioCapturer.start((err) = > {
    if (err) {
        console.error('Capturer start failed.');
    } else {
        console.info('Capturer start success.');
    }
});

start8+

start(): Promise

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

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

返回值:

类型说明
Promise使用Promise方式异步返回结果。

示例:

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

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

var audioCapturerInfo = {
    source: audio.SourceType.SOURCE_TYPE_MIC,
    capturerFlags = 1
}

var audioCapturer;
audio.createAudioCapturer(audioCapturerOptions).then((data) = > {
    audioCapturer = data;
    console.info('AudioFrameworkRecLog: AudioCapturer Created: SUCCESS');
    }).catch((err) = > {
    console.info('AudioFrameworkRecLog: AudioCapturer Created: ERROR: '+err.message);
    });
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) = > {
    console.info('AudioFrameworkRecLog: Capturer start :ERROR : '+err.message);
    stateFlag=false;
});

stop8+

stop(callback: AsyncCallback): void

停止采集。使用callback方式异步返回结果。

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

参数:

参数名类型必填说明
callbackAsyncCallback使用callback方式异步返回结果。

示例:

audioCapturer.stop((err) = > {
    if (err) {
        console.error('Capturer stop failed');
    } else {
        console.log('Capturer stopped.');
    }
});

stop8+

stop(): Promise

停止采集。使用Promise方式异步返回结果。

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

返回值:

类型说明
Promise使用Promise方式异步返回结果。

示例:

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) = > {
    console.info('AudioFrameworkRecLog: Capturer stop: ERROR: '+err.message);
});

release8+

release(callback: AsyncCallback): void

释放采集器。使用callback方式异步返回结果。

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

参数:

参数名类型必填说明
callbackAsyncCallbackCallback used to return the result.

示例:

audioCapturer.release((err) = > {
    if (err) {
        console.error('capturer release failed');
    } else {
        console.log('capturer released.');
    }
});

release8+

release(): Promise

释放采集器。使用Promise方式异步返回结果。

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

返回值:

类型说明
Promise使用Promise方式异步返回结果。

示例:

audioCapturer.release().then(() = > {
    console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------');
    console.info('AudioFrameworkRecLog: Capturer release : SUCCESS');
    console.info('AudioFrameworkRecLog: AudioCapturer : STATE : '+audioCapturer.state);
    console.info('AudioFrameworkRecLog: stateFlag : '+stateFlag);
}).catch((err) = > {
    console.info('AudioFrameworkRecLog: Capturer stop: ERROR: '+err.message);
});

read8+

read(size: number, isBlockingRead: boolean, callback: AsyncCallback): void

读入缓冲区。使用callback方式异步返回结果。

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

参数

参数名类型必填说明
sizenumber读入的字节数。
isBlockingReadboolean是否阻塞读操作。
callbackAsyncCallback使用callback方式异步返回缓冲区。

示例:

var bufferSize;
audioCapturer.getBufferSize().then((data) = > {
    console.info('AudioFrameworkRecLog: getBufferSize: SUCCESS '+data);
    bufferSize = data;
    }).catch((err) = > {
    console.info('AudioFrameworkRecLog: getBufferSize: EROOR: '+err.message);
    });
audioCapturer.read(bufferSize, true, async(err, buffer) = > {
    if (!err) {
        console.log("Success in reading the buffer data");
    }
});

read8+

read(size: number, isBlockingRead: boolean): Promise

读入缓冲区。使用Promise方式异步返回结果。

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

参数:

参数名类型必填说明
sizenumber读入的字节数。
isBlockingReadboolean是否阻塞读操作。

返回值:

类型说明
Promise如果操作成功,返回读取的缓冲区数据;否则返回错误代码。

示例:

var bufferSize;
audioCapturer.getBufferSize().then((data) = > {
    console.info('AudioFrameworkRecLog: getBufferSize: SUCCESS '+data);
    bufferSize = data;
    }).catch((err) = > {
    console.info('AudioFrameworkRecLog: getBufferSize: ERROR '+err.message);
    });
console.info('Buffer size: ' + bufferSize);
audioCapturer.read(bufferSize, true).then((buffer) = > {
    console.info('buffer read successfully');
}).catch((err) = > {
    console.info('ERROR : '+err.message);
});

getAudioTime8+

getAudioTime(callback: AsyncCallback): void

获取时间戳(从1970年1月1日开始),单位为纳秒。使用callback方式异步返回结果。

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

参数:

参数名类型必填说明
callbackAsyncCallback使用callback方式异步返回结果。

示例:

audioCapturer.getAudioTime((err, timestamp) = > {
    console.log('Current timestamp: ' + timestamp);
});

getAudioTime8+

getAudioTime(): Promise

获取时间戳(从1970年1月1日开始),单位为纳秒。使用Promise方式异步返回结果。

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

返回值:

类型说明
Promise使用Promise方式异步返回结果。

示例:

audioCapturer.getAudioTime().then((audioTime) = > {
    console.info('AudioFrameworkRecLog: AudioCapturer getAudioTime : Success' + audioTime );
}).catch((err) = > {
    console.info('AudioFrameworkRecLog: AudioCapturer Created : ERROR : '+err.message);
});

getBufferSize8+

getBufferSize(callback: AsyncCallback): void

获取采集器合理的最小缓冲区大小。使用callback方式异步返回结果。

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

参数:

参数名类型必填说明
callbackAsyncCallback使用callback方式异步返回缓冲区大小。

示例:

audioCapturer.getBufferSize((err, bufferSize) = > {
    if (!err) {
        console.log('BufferSize : ' + bufferSize);
        audioCapturer.read(bufferSize, true).then((buffer) = > {
            console.info('Buffer read is ' + buffer );
        }).catch((err) = > {
            console.info('AudioFrameworkRecLog: AudioCapturer Created : ERROR : '+err.message);
        });
    }
});

getBufferSize8+

getBufferSize(): Promise

获取采集器合理的最小缓冲区大小。使用Promise方式异步返回结果。

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

返回值:

类型说明
Promise使用Promise方式异步返回缓冲区大小。

示例:

var bufferSize;
audioCapturer.getBufferSize().then((data) = > {
    console.info('AudioFrameworkRecLog: getBufferSize :SUCCESS '+ data);
    bufferSize = data;
}).catch((err) = > {
    console.info('AudioFrameworkRecLog: getBufferSize :ERROR : '+ err.message);
});

on('markReach')8+

on(type: 'markReach', frame: number, callback: (position: number) => {}): void

订阅标记到达的事件。 当采集的帧数达到 frame 参数的值时,回调被触发。

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

参数:

参数名类型必填说明
typestring事件回调类型,支持的事件为:'markReach'。
framenumber触发事件的帧数。 该值必须大于0。
callbackposition: number) => {}使用callback方式异步返回被触发事件的回调。

示例:

audioCapturer.on('markReach', 1000, (position) = > {
    if (position == 1000) {
        console.log('ON Triggered successfully');
    }
});

off('markReach')8+

off(type: 'markReach'): void

取消订阅标记到达的事件。

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

参数:

参数名类型必填说明
typestring取消事件回调类型,支持的事件为:'markReach'。

示例:

audioCapturer.off('markReach');

on('periodReach')8+

on(type: "periodReach", frame: number, callback: (position: number) => {}): void

订阅到达标记的事件。 当采集的帧数达到 frame 参数的值时,回调被循环调用。

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

参数:

参数名类型必填说明
typestring事件回调类型,支持的事件为:'periodReach'。
framenumber触发事件的帧数。 该值必须大于0。
callback(position: number) => {}使用callback方式异步返回被触发事件的回调

示例:

audioCapturer.on('periodReach', 1000, (position) = > {
    if (position == 1000) {
        console.log('ON Triggered successfully');
    }
});

off('periodReach')8+

off(type: 'periodReach'): void

取消订阅标记到达的事件。

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

参数:

参数名类型必填说明
typestringYes取消事件回调类型,支持的事件为:'periodReach'。

示例:

audioCapturer.off('periodReach')

on('stateChange') 8+

on(type: 'stateChange', callback: Callback): void

订阅监听状态变化。

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

参数:

参数名类型必填说明HarmonyOSOpenHarmony鸿蒙文档籽料:mau123789是v直接拿
typestring事件回调类型,支持的事件为:'stateChange'。
callback[AudioState]返回监听的状态。

搜狗高速浏览器截图20240326151344.png
示例:

audioCapturer.on('stateChange', (state) = > {
    if (state == 1) {
        console.log("audio capturer state is: STATE_PREPARED");
    }
    if (state == 2) {
        console.log("audio capturer state is: STATE_RUNNING");
    }
});

审核编辑 黄宇

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • 接口
    +关注

    关注

    33

    文章

    7972

    浏览量

    149245
  • 开发
    +关注

    关注

    0

    文章

    352

    浏览量

    40670
  • 鸿蒙
    +关注

    关注

    55

    文章

    2123

    浏览量

    42274
收藏 人收藏

    评论

    相关推荐

    鸿蒙开发接口媒体:【@ohos.multimedia.camera (相机管理)】

    本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
    的头像 发表于 05-31 09:42 797次阅读
    <b class='flag-5'>鸿蒙</b><b class='flag-5'>开发</b><b class='flag-5'>接口</b><b class='flag-5'>媒体</b>:【@<b class='flag-5'>ohos.multimedia</b>.camera (相机<b class='flag-5'>管理</b>)】

    鸿蒙原生应用/元服务开发-延迟任务说明(一)

    ) @ohos.backgroundTaskManager (后台任务管理) @ohos.multimedia.audio (音频管理) @
    发表于 01-16 14:57

    鸿蒙媒体开发【简述】

    录制)、图片等。 如下图所示,媒体系统面向应用开发提供音视频应用、图库应用的编程框架接口;面向设备开发提供对接不同硬件芯片适配加速功能;中间以服务形态提供
    发表于 02-28 17:53

    HarmonyOS API Version 7版本特性说明

    ,主要包含音视频、媒体库、图片编解码等媒体能力,支撑了X1图库的商用诉求,同步助力HarmonyOS北向生态拓展。图5 多媒体子系统新增接口@oho
    发表于 11-30 15:19

    HarmonyOS API Version 7版本特性说明

    ,主要包含音视频、媒体库、图片编解码等媒体能力,支撑了X1图库的商用诉求,同步助力HarmonyOS北向生态拓展。图5 多媒体子系统新增接口@oho
    发表于 12-01 10:35

    OpenHarmony 3.2 Beta Audio——音频渲染

    一、简介Audio是多媒体子系统中的一个重要模块,其涉及的内容比较多,有音频的渲染、音频的采集、音频的策略
    发表于 03-02 14:28

    HarmonyOS/OpenHarmony应用开发-ArkTSAPI系统能力SystemCapability列表

    SystemCapability.Multimedia.Audio.Capturer:音频输入能力 SystemCapability.Multimedia.Audio.Device:音频设备
    发表于 08-11 10:08

    HarmonyOS音频开发指导:使用AudioRenderer开发音频播放功能

    音频文件的示例代码。 import audio from \'@ohos.multimedia.audio\'; import fs from \'@ohos.file.fs\';
    发表于 10-23 14:21

    HarmonyOS多音频播放并发政策及音频管理解析

    实例 在使用AudioRoutingManager管理音频设备前,需要先导入模块并创建实例。 import audio from \'@ohos.multimedia.audio\';
    发表于 10-25 16:35

    基于开源项目Piasy/RxAndroid音频进行的ohos移植和开发

    本项目是基于开源项目Piasy/RxAndroidAudio进行ohos移植和开发的。 所属系列:鸿蒙的第三方组件适配移植 功能:(Functions:) 实现音频文件录制和播放 (1
    发表于 04-02 15:52 10次下载

    OpenHarmony 3.2 Beta Audio音频渲染

    一、简介 Audio是多媒体子系统中的一个重要模块,其涉及的内容比较多,有音频的渲染、音频的采集、音频的策略
    的头像 发表于 03-11 14:15 460次阅读

    OpenHarmony 3.2 Beta Audio——音频渲染

    点击蓝字 ╳ 关注我们 开源项目 OpenHarmony 是每个人的 OpenHarmony 巴延兴 深圳开鸿数字产业发展有限公司 资深OS框架开发工程师 一、简介 Audio是多媒体子系统
    的头像 发表于 03-11 16:40 490次阅读

    鸿蒙开发实战:【文件管理

    文件管理相关的功能,使用[@ohos.multimedia.medialibrary]、[@ohos.filemanagement.userFileManager] 、[@ohos
    的头像 发表于 03-20 21:57 339次阅读
    <b class='flag-5'>鸿蒙</b><b class='flag-5'>开发</b>实战:【文件<b class='flag-5'>管理</b>】

    鸿蒙开发接口媒体:【@ohos.multimedia.media (媒体服务)】

    媒体子系统为开发者提供一套简单且易于理解的接口,使得开发者能够方便接入系统并使用系统的媒体资源。
    的头像 发表于 06-06 11:03 327次阅读
    <b class='flag-5'>鸿蒙</b><b class='flag-5'>开发</b><b class='flag-5'>接口</b><b class='flag-5'>媒体</b>:【@<b class='flag-5'>ohos.multimedia</b>.media (<b class='flag-5'>媒体</b>服务)】

    鸿蒙开发接口媒体:【@ohos.multimedia.medialibrary (媒体管理)】

    获取媒体库的实例,用于访问和修改用户等个人媒体数据信息(如音频、视频、图片、文档等)。
    的头像 发表于 06-03 11:52 692次阅读
    <b class='flag-5'>鸿蒙</b><b class='flag-5'>开发</b><b class='flag-5'>接口</b><b class='flag-5'>媒体</b>:【@<b class='flag-5'>ohos.multimedia</b>.medialibrary (<b class='flag-5'>媒体</b>库<b class='flag-5'>管理</b>)】