The SoundPool class provides APIs to implement low-latency playback of short sounds.
Short sound effects (such as the camera shutter sound effect and system notification sound effect) are often required during application development. You can call the APIs provided by SoundPool to implement one-time loading of short sounds and multiple times of low-latency playback.
SoundPool currently supports playing of audio files that are under 1 MB in size after decoding. For audio files that exceed this limit after decoding, only the first 1 MB of data is played. This is equivalent to approximately 5.6 seconds of audio duration at a 44.1 kHz sampling rate with 16-bit depth for stereo sound. (At lower sampling rates or in mono mode, the duration may be slightly longer.)
This topic walks you through on how to use the SoundPool APIs to implement low-latency playback. For details about the API declaration, see SoundPool.
The full process includes creating a SoundPool instance, loading a sound (including decapsulation and decoding), setting playback parameters (loop mode, and playback priority), playing the sound, stopping the playback, and releasing the instance. (For details about the decoding formats, see Audio Decoding.)
During application development, you must subscribe to playback state changes and call the APIs in the defined sequence. Otherwise, an exception or undefined behavior may occur.
For details about the audio focus strategy when SoundPool is used to play short sounds, see Introduction to Audio Focus and Audio Session.
Call createSoundPool to create a SoundPool instance.
// The value of the usage parameter in audioRendererInfo can be STREAM_USAGE_UNKNOWN, STREAM_USAGE_MUSIC, or STREAM_USAGE_MOVIE.
// or STREAM_USAGE_AUDIOBOOK, SoundPool plays a short sound in audio mixing mode, without interrupting the playback of other audio streams.
let audioRendererInfo: audio.AudioRendererInfo = {
usage: audio.StreamUsage.STREAM_USAGE_MUSIC, // Audio stream usage type: music. Set this parameter based on the service scenario.
rendererFlags: 1 // AudioRenderer flag.
}
// Create a SoundPool instance.
this.soundPool = await media.createSoundPool(14, audioRendererInfo); Call on('loadComplete') to listen for the completion of sound loading.
// Callback invoked when the sound finishes loading.
this.soundPool!.on('loadComplete', (soundId_: number) => {
this.soundId = soundId_;
console.info('loadComplete soundId: ' + soundId_);
}) Call on('playFinished') or on('playFinishedWithStreamId') to listen for the completion of audio playback.
When only the 'playFinished' or 'playFinishedWithStreamId' event callback is registered, the registered callback is triggered when audio playback finishes.
When both the 'playFinished' and 'playFinishedWithStreamId' event callbacks are registered, only the 'playFinishedWithStreamId' event callback is triggered when audio playback finishes. The 'playFinished' event callback is not triggered.
this.soundPool!.on('playFinished', () => {
console.info('receive play finished message');
// Ready for the next playback.
}) Call on('error') to listen for errors that may occur.
this.soundPool!.on('error', (error: BusinessError) => {
console.error('error happened,message is :' + error.code);
console.error('error happened,message is :' + error.message);
}) Call load() to load a sound.
You can load a sound by passing a URI or an fd. This example uses the fd method. For more methods, see load.
When the system finishes loading the sound, the loadComplete callback is invoked to notify the user that the loading is complete. Perform the subsequent play operation after the callback is received.
let context = this.getUIContext().getHostContext();;
let fileDescriptor = await context!.resourceManager.getRawFd('test.ogg');
this.soundId = await this.soundPool!.load(fileDescriptor.fd, fileDescriptor.offset, fileDescriptor.length);
console.info(`load soundPool soundId: ${this.soundId}`) Set PlayParameters, and call play after the loadComplete callback is received. If play() with the same sound ID passed in is called for multiple times, the sound is played only once.
let playParameters: media.PlayParameters = {
loop: 1, // Loop once, that is, play twice.
rate: 1, // Play at 1x speed.
leftVolume: 0.5, // Value range: [0.0, 1.0].
rightVolume: 0.5, // Value range: [0.0, 1.0].
priority: 0, // Lowest priority.
};
// Start playback. Here, play can also carry the playback parameter PlayParameters. Call play only after the audio resource is loaded, that is, after the loadComplete callback is received.
this.soundPool!.play(this.soundId, playParameters, (error, streamID: number) => {
if (error) {
console.error(`play sound Error: errCode is ${error.code}, errMessage is ${error.message}`)
} else {
this.streamId = streamID;
console.info('play success soundid:' + this.streamId);
}
}); Call setLoop() to set the number of loops.
// Set the number of loop plays. await this.soundPool!.setLoop(this.streamId, 2); // Play 3 times.
Call setPriority() to set the playback priority.
// Set the priority of the corresponding stream. await this.soundPool!.setPriority(this.streamId, 1);
Call setVolume() to set the playback volume.
// Set the volume. await this.soundPool!.setVolume(this.streamId, 0.5, 0.5);
Call stop() to stop the playback.
// Stop the playback of the stream. await this.soundPool!.stop(this.streamId);
Call unload() to unload a sound.
// Unload the sound. await this.soundPool!.unload(this.soundId);
Call off('loadComplete') to stop listening for the completion of sound loading.
this.soundPool!.off('loadComplete'); Call off('playFinished') to stop listening for the completion of audio playback.
this.soundPool!.off('playFinished'); Call off('error') to stop listening for errors.
this.soundPool!.off('error'); Call release() to release the SoundPool instance.
// Release the SoundPool instance. await this.soundPool!.release();
Refer to the sample project to use SoundPool to play audio at a low latency.
Create a project, download the sample project, and copy its resources to the corresponding directories.
SoundPoolArkTS
entry/src/main/ets/
└── pages
└── Index.ets (Playback UI)
entry/src/main/resources/
├── base
│ ├── element
│ │ ├── color.json
│ │ ├── float.json
│ │ └── string.json
│ └── media
│
└── rawfile
└── test.ogg (Audio resource) Compile and run the project.