Obtaining Real-time Audio Volume During Capture in HarmonyOS for Fluctuating Effects
Context
When recording with audio.AudioCapturer, how to get the real-time volume of the audio data? Need to create a fluctuating effect based on the volume.
Description
API 12 now supports capturing changes in recording volume. Use the getMaxAmplitudeForInputDevice event to get the maximum amplitude of the input device's audio stream.
Solution
Example usage:
private async getMaxAmplitudeVolume() {
// Initialize audioDeviceDescriptor
audio.getAudioManager().getRoutingManager().getPreferredInputDeviceForCapturerInfo({
source: audio.SourceType.SOURCE_TYPE_MIC,
capturerFlags: 0
}).then(async (data) => {
this.audioDeviceDescriptor = data[0]
}).catch((err) => {
console.error("get outputDeviceId error" + JSON.stringify(err));
})
this.audioVolumeGroupManager = await audio.getAudioManager().getVolumeManager()
.getVolumeGroupManager(audio.DEFAULT_VOLUME_GROUP_ID)
this.volumeInterval = setInterval(() => {
this.audioVolumeGroupManager?.getMaxAmplitudeForInputDevice(this.audioDeviceDescriptor).then((volume) => {
this.volume = volume
console.log("get volume:" + this.volume);
})
}, 300)
}
However, this may return 0 frequently. Instead, place getMaxAmplitudeForInputDevice inside the read callback:
let readDataCallback = (buffer: ArrayBuffer) => {
let audioManager = audio.getAudioManager();
let capturerInfo = { source: audio.SourceType.SOURCE_TYPE_MIC, capturerFlags: 0 };
let desc = audioManager.getRoutingManager().getPreferredInputDeviceForCapturerInfoSync(capturerInfo);
let audioVolumeManager = audioManager.getVolumeManager();
let audioVolumeGroupManager = audioVolumeManager.getVolumeGroupManagerSync(audio.DEFAULT_VOLUME_GROUP_ID);
audioVolumeGroupManager.getMaxAmplitudeForInputDevice(desc[0]).then((value) => {
console.info(`mic volatileume amplitude is: ${value}`);
})
};
For optimization, initialize manager objects once outside the callback and reuse them inside.
Key Takeaways
• Use getMaxAmplitudeForInputDevice (API 12) to get audio input volume.
• Avoid using setInterval, as it may return 0 frequently.
• Place the API call inside the audio read callback for real-time capture.
• To reduce overhead, initialize singleton audio manager objects once outside the callback.
Top comments (0)