• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# SoundPool (Sound Pool)
2
3The SoundPool module provides APIs for loading, unloading, playing, and stopping playing sounds, setting the volume, and setting the number of loops.
4
5Before using these APIs, you must call [media.createSoundPool](js-apis-media.md#mediacreatesoundpool10) to create a **SoundPool** instance.
6
7> **NOTE**
8>
9> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
10
11## Modules to Import
12
13```js
14import { media } from '@kit.MediaKit';
15import { audio } from '@kit.AudioKit';
16```
17
18## PlayParameters
19
20Describes the playback parameters of the sound pool.
21
22These parameters are used to control the playback volume, number of loops, and priority.
23
24**System capability**: SystemCapability.Multimedia.Media.SoundPool
25
26| Name           | Type                                    | Mandatory| Description                                                        |
27| --------------- | ---------------------------------------- | ---- | ------------------------------------------------------------ |
28| loop | number   | No | Number of loops.<br>If this parameter is set to a value greater than or equal to 0, the number of times the content is actually played is the value of **loop** plus 1.<br> If this parameter is set to a value less than 0, the content is played repeatedly.<br>The default value is **0**, indicating that the content is played only once.                  |
29| rate | number    | No | Playback rate. For details, see [AudioRendererRate](../apis-audio-kit/js-apis-audio.md#audiorendererrate8). Default value: **0**|
30| leftVolume  | number | No | Volume of the left channel. The value ranges from 0.0 to 1.0. Default value: **1.0**                                   |
31| rightVolume | number  | No | Volume of the right channel. The value ranges from 0.0 to 1.0. (Currently, the volume cannot be set separately for the left and right channels. The volume set for the left channel is used.) Default value: **1.0**|
32| priority  | number  | No | Playback priority. The value **0** means the lowest priority. A larger value indicates a higher priority. The value is an integer greater than or equal to 0. Default value: **0**     |
33
34## SoundPool
35
36Implements a sound pool that provides APIs for loading, unloading, playing, and stopping playing system sounds, setting the volume, and setting the number of loops. Before using these APIs, you must call [createSoundPool](js-apis-media.md#mediacreatesoundpool10) to create a **SoundPool** instance.
37
38> **NOTE**
39>
40> When using the **SoundPool** instance, you are advised to register the following callbacks to proactively obtain status changes:
41> - [on('loadComplete')](#onloadcomplete): listens for the event indicating that the resource loading is finished.
42> - [on('playFinishedWithStreamId')](#onplayfinishedwithstreamid18): listens for the event indicating that the playback is finished and returns the stream ID of the audio that finishes playing.
43> - [on('playFinished')](#onplayfinished): listens for the event indicating that the playback is finished.
44> - [on('error')](#onerror): listens for error events.
45
46### load
47
48load(uri: string, callback: AsyncCallback\<number>): void
49
50Loads a sound. This API uses an asynchronous callback to obtain the sound ID. The input parameter **uri** is a string starting with fd://, which is generated based on the file descriptor (FD) obtained.
51This API cannot be used to load resources in the **rawfile** directory. Instead, use [load(fd: number, offset: number, length: number, callback: AsyncCallback\<number>): void](#load-2) or [load(fd: number, offset: number, length: number): Promise\<number>](#load-3).
52
53>**NOTE**
54>
55>After the resource handle (in the form of an FD) or path description (in the form of a URI) is transferred to the AVPlayer, do not use the resource handle or path description in read or write operations, including but not limited to transferring it to multiple AVPlayers.
56>Competition occurs when multiple AVPlayers use the same resource handle or path description to read and write files at the same time, resulting in playback errors.
57
58**System capability**: SystemCapability.Multimedia.Media.SoundPool
59
60**Parameters**
61
62| Name  | Type                                  | Mandatory| Description                                 |
63| -------- | -------------------------------------- | ---- | ------------------------------------- |
64| uri   | string | Yes  | URI of the audio file to load. Generally, the URI starts with fd://.|
65| callback | AsyncCallback\<number>                   | Yes  | Callback used to return the sound ID. A valid value must be greater than 0.|
66
67**Error codes**
68
69For details about the error codes, see [Media Error Codes](errorcode-media.md).
70
71| ID| Error Message                               |
72| -------- | --------------------------------------- |
73| 5400102  | Operation not allowed. Return by callback.|
74| 5400103  | I/O error. Return by callback. |
75| 5400105  | Service died. Return by callback. |
76
77**Example**
78
79```ts
80import { fileIo } from '@kit.CoreFileKit';
81import { BusinessError } from '@kit.BasicServicesKit';
82
83// Create a SoundPool instance.
84let soundPool: media.SoundPool;
85let audioRendererInfo: audio.AudioRendererInfo = {
86  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
87  rendererFlags: 1
88}
89media.createSoundPool(5, audioRendererInfo, (error: BusinessError, soundPool_: media.SoundPool) => {
90  if (error) {
91    console.error(`Failed to createSoundPool`)
92    return;
93  } else {
94    soundPool = soundPool_;
95    console.info(`Succeeded in createSoundPool`)
96    let uri:string = "";
97    let file: fileIo.File;
98    // Obtain the URI starting with fd://.
99    fileIo.open('/test_01.mp3', fileIo.OpenMode.READ_ONLY).then((file_: fileIo.File) => {
100      file = file_;
101      console.info("file fd: " + file.fd);
102      uri = 'fd://' + (file.fd).toString()
103      soundPool.load(uri, (error: BusinessError, soundId_: number) => {
104        if (error) {
105          console.error(`Failed to load soundPool: errCode is ${error.code}, errMessage is ${error.message}`)
106        } else {
107          console.info(`Succeeded in loading soundPool` + JSON.stringify(soundId_))
108        }
109      });
110    }); // '/test_01.mp3' here is only an example. You need to pass in the actual URI.
111  }
112});
113```
114
115### load
116
117load(uri: string): Promise\<number>
118
119Loads a sound. This API uses a promise to obtain the sound ID. The input parameter **uri** is a starting with fd://, which is generated based on the FD obtained.
120This API cannot be used to load resources in the **rawfile** directory. Instead, use [load(fd: number, offset: number, length: number, callback: AsyncCallback\<number>): void](#load-2) or [load(fd: number, offset: number, length: number): Promise\<number>](#load-3).
121
122>**NOTE**
123>
124>After the resource handle (in the form of an FD) or path description (in the form of a URI) is transferred to the AVPlayer, do not use the resource handle or path description in read or write operations, including but not limited to transferring it to multiple AVPlayers.
125>Competition occurs when multiple AVPlayers use the same resource handle or path description to read and write files at the same time, resulting in playback errors.
126
127**System capability**: SystemCapability.Multimedia.Media.SoundPool
128
129**Parameters**
130
131| Name| Type                                  | Mandatory| Description                      |
132| ------ | -------------------------------------- | ---- | -------------------------- |
133| uri | string | Yes  | URI of the audio file to load. Generally, the URI starts with fd://.|
134
135**Return value**
136
137| Type          | Description                                      |
138| -------------- | ------------------------------------------ |
139| Promise\<number> | Promise used to return the sound ID. A valid value must be greater than 0.|
140
141**Error codes**
142
143For details about the error codes, see [Media Error Codes](errorcode-media.md).
144
145| ID| Error Message                               |
146| -------- | --------------------------------------- |
147| 5400102  | Operation not allowed. Return by promise.|
148| 5400103  | I/O error. Return by promise. |
149| 5400105  | Service died. Return by promise. |
150
151**Example**
152
153```ts
154import { fileIo } from '@kit.CoreFileKit';
155import { BusinessError } from '@kit.BasicServicesKit';
156
157// Create a SoundPool instance.
158let soundPool: media.SoundPool;
159let audioRendererInfo: audio.AudioRendererInfo = {
160  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
161  rendererFlags: 1
162}
163media.createSoundPool(5, audioRendererInfo, (error: BusinessError, soundPool_: media.SoundPool) => {
164  if (error) {
165    console.error(`Failed to createSoundPool`)
166    return;
167  } else {
168    soundPool = soundPool_;
169    console.info(`Succeeded in createSoundPool`)
170    let uri:string = "";
171    let soundID: number = 0;
172    let file: fileIo.File;
173    // Obtain the URI starting with fd://.
174    fileIo.open('/test_01.mp3', fileIo.OpenMode.READ_ONLY).then((file_: fileIo.File) => {
175      file = file_;
176      console.info("file fd: " + file.fd);
177      uri = 'fd://' + (file.fd).toString()
178      soundPool.load(uri).then((soundId: number) => {
179        console.info('Succeeded in loading uri');
180        soundID = soundId;
181      }, (err: BusinessError) => {
182        console.error('Failed to load soundPool and catch error is ' + err.message);
183      });
184    }); // '/test_01.mp3' here is only an example. You need to pass in the actual URI.
185  }
186});
187
188```
189
190### load
191
192load(fd: number, offset: number, length: number, callback: AsyncCallback\<number>): void
193
194Loads a sound. This API uses an asynchronous callback to obtain the sound ID. The input parameter **fd** can be manually input or automatically obtained by reading the embedded resource of the application.
195
196>**NOTE**
197>
198>After the resource handle (in the form of an FD) or path description (in the form of a URI) is transferred to the AVPlayer, do not use the resource handle or path description in read or write operations, including but not limited to transferring it to multiple AVPlayers.
199>Competition occurs when multiple AVPlayers use the same resource handle or path description to read and write files at the same time, resulting in playback errors.
200
201**System capability**: SystemCapability.Multimedia.Media.SoundPool
202
203**Parameters**
204
205| Name  | Type                  | Mandatory| Description                       |
206| -------- | ---------------------- | ---- | --------------------------- |
207| fd     | number | Yes  | Resource handle, which is obtained by calling [resourceManager.getRawFd](../apis-localization-kit/js-apis-resource-manager.md#getrawfd9).    |
208| offset | number | Yes  | Resource offset, which needs to be entered based on the preset resource information. An invalid value causes a failure to parse audio and video resources.|
209| length | number | Yes  | Resource length, which needs to be entered based on the preset resource information. An invalid value causes a failure to parse audio and video resources.|
210| callback | AsyncCallback\<number> | Yes  | Callback used to return the sound ID. A valid value must be greater than 0.|
211
212**Error codes**
213
214For details about the error codes, see [Media Error Codes](errorcode-media.md).
215
216| ID| Error Message                               |
217| -------- | --------------------------------------- |
218| 5400102  | Operation not allowed. Return by callback. |
219| 5400103  | I/O error. Return by callback. |
220| 5400105  | Service died. Return by callback.       |
221
222**Example 1:**
223
224```ts
225import { fileIo } from '@kit.CoreFileKit';
226import { BusinessError } from '@kit.BasicServicesKit';
227
228// Create a SoundPool instance.
229let soundPool: media.SoundPool;
230let audioRendererInfo: audio.AudioRendererInfo = {
231  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
232  rendererFlags: 1
233}
234media.createSoundPool(5, audioRendererInfo, (error: BusinessError, soundPool_: media.SoundPool) => {
235  if (error) {
236    console.error(`Failed to createSoundPool`)
237    return;
238  } else {
239    soundPool = soundPool_;
240    console.info(`Succeeded in createSoundPool`)
241    let file: fileIo.File;
242    let soundID: number = 0;
243    let fileSize: number = 1; // Obtain the size through fileIo.stat().
244    let uri: string = "";
245    // Obtain the FD. The test_01.mp3 file is not an audio file in the rawfile directory.
246    fileIo.open('/test_01.mp3', fileIo.OpenMode.READ_ONLY).then((file_: fileIo.File) => {
247      file = file_;
248      console.info("file fd: " + file.fd);
249      uri = 'fd://' + (file.fd).toString()
250      soundPool.load(file.fd, 0, fileSize, (error: BusinessError, soundId_: number) => {
251        if (error) {
252          console.error(`Failed to load soundPool: errCode is ${error.code}, errMessage is ${error.message}`)
253        } else {
254          soundID = soundId_;
255          console.info('Succeeded in loading soundId:' + soundId_);
256        }
257      });
258    }); // '/test_01.mp3' here is only an example. You need to pass in the actual URI.
259  }
260});
261
262```
263
264**Example 2**
265
266```ts
267import { media } from '@kit.MediaKit';
268import { audio } from '@kit.AudioKit';
269import { BusinessError } from '@kit.BasicServicesKit';
270
271// Create a SoundPool instance.
272let soundPool: media.SoundPool;
273let audioRendererInfo: audio.AudioRendererInfo = {
274  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
275  rendererFlags: 1
276}
277let soundID: number = 0;
278media.createSoundPool(5, audioRendererInfo, async (error: BusinessError, soundPool_: media.SoundPool) => {
279  if (error) {
280    console.error(`Failed to createSoundPool`)
281    return;
282  } else {
283    soundPool = soundPool_;
284    console.info(`Succeeded in createSoundPool`)
285    // The test_01.mp3 file is an audio file in the rawfile directory.
286    let fileDescriptor = await getContext().resourceManager.getRawFd('test_01.mp3');
287    soundPool.load(fileDescriptor.fd, fileDescriptor.offset, fileDescriptor.length, (error: BusinessError, soundId_: number) => {
288      if (error) {
289        console.error(`Failed to load soundPool: errCode is ${error.code}, errMessage is ${error.message}`)
290      } else {
291        soundID = soundId_;
292        console.info('Succeeded in loading soundId:' + soundId_);
293      }
294    });
295  }
296});
297
298```
299
300### load
301
302load(fd: number, offset: number, length: number): Promise\<number>
303
304Loads a sound. This API uses a promise to obtain the sound ID. The input parameter **fd** can be manually input or automatically obtained by reading the embedded resource of the application.
305
306>**NOTE**
307>
308>After the resource handle (in the form of an FD) or path description (in the form of a URI) is transferred to the AVPlayer, do not use the resource handle or path description in read or write operations, including but not limited to transferring it to multiple AVPlayers.
309>Competition occurs when multiple AVPlayers use the same resource handle or path description to read and write files at the same time, resulting in playback errors.
310
311**System capability**: SystemCapability.Multimedia.Media.SoundPool
312
313**Parameters**
314
315| Name  | Type                  | Mandatory| Description                       |
316| -------- | ---------------------- | ---- | --------------------------- |
317| fd     | number | Yes  | Resource handle, which is obtained by calling [resourceManager.getRawFd](../apis-localization-kit/js-apis-resource-manager.md#getrawfd9).    |
318| offset | number | Yes  | Resource offset, which needs to be entered based on the preset resource information. An invalid value causes a failure to parse audio and video resources.|
319| length | number | Yes  | Resource length, which needs to be entered based on the preset resource information. An invalid value causes a failure to parse audio and video resources.|
320
321**Return value**
322
323| Type            | Description                            |
324| ---------------- | -------------------------------- |
325| Promise\<number> | Promise used to return the sound ID. A valid value must be greater than 0.|
326
327**Error codes**
328
329For details about the error codes, see [Media Error Codes](errorcode-media.md).
330
331| ID| Error Message                               |
332| -------- | --------------------------------------- |
333| 5400102  | Operation not allowed. Return by promise.|
334| 5400103  | I/O error. Return by promise. |
335| 5400105  | Service died. Return by promise. |
336
337**Example 1:**
338
339```ts
340import { fileIo } from '@kit.CoreFileKit';
341import { BusinessError } from '@kit.BasicServicesKit';
342
343// Create a SoundPool instance.
344let soundPool: media.SoundPool;
345let audioRendererInfo: audio.AudioRendererInfo = {
346  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
347  rendererFlags: 1
348}
349media.createSoundPool(5, audioRendererInfo, (error: BusinessError, soundPool_: media.SoundPool) => {
350  if (error) {
351    console.error(`Failed to createSoundPool`)
352    return;
353  } else {
354    soundPool = soundPool_;
355    console.info(`Succeeded in createSoundPool`)
356    let file: fileIo.File;
357    let soundID: number = 0;
358    let fileSize: number = 1; // Obtain the size through fileIo.stat().
359    let uri: string = "";
360    // Obtain the FD. The test_01.mp3 file is not an audio file in the rawfile directory.
361    fileIo.open('/test_01.mp3', fileIo.OpenMode.READ_ONLY).then((file_: fileIo.File) => {
362      file = file_;
363      console.info("file fd: " + file.fd);
364      uri = 'fd://' + (file.fd).toString()
365      soundPool.load(file.fd, 0, fileSize).then((soundId: number) => {
366        console.info('Succeeded in loading soundpool');
367        soundID = soundId;
368      }, (err: BusinessError) => {
369        console.error('Failed to load soundpool and catch error is ' + err.message);
370      });
371    });
372  }
373});
374
375```
376
377**Example 2**
378
379```ts
380import { media } from '@kit.MediaKit';
381import { audio } from '@kit.AudioKit';
382import { BusinessError } from '@kit.BasicServicesKit';
383
384// Create a SoundPool instance.
385let soundPool: media.SoundPool;
386let audioRendererInfo: audio.AudioRendererInfo = {
387  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
388  rendererFlags: 1
389}
390let soundID: number = 0;
391media.createSoundPool(5, audioRendererInfo, async (error: BusinessError, soundPool_: media.SoundPool) => {
392  if (error) {
393    console.error(`Failed to createSoundPool`)
394    return;
395  } else {
396    soundPool = soundPool_;
397    console.info(`Succeeded in createSoundPool`)
398    // The test_01.mp3 file is an audio file in the rawfile directory.
399    let fileDescriptor = await getContext().resourceManager.getRawFd('test_01.mp3');
400    soundPool.load(fileDescriptor.fd, fileDescriptor.offset, fileDescriptor.length).then((soundId: number) => {
401      console.info('Succeeded in loading soundpool');
402      soundID = soundId;
403    }, (err: BusinessError) => {
404      console.error('Failed to load soundpool and catch error is ' + err.message);
405    });
406  }
407});
408
409```
410
411### play
412
413play(soundID: number, params: PlayParameters, callback: AsyncCallback\<number>): void
414
415Plays a sound. This API uses an asynchronous callback to obtain the audio stream ID.
416
417**System capability**: SystemCapability.Multimedia.Media.SoundPool
418
419**Parameters**
420
421| Name  | Type                  | Mandatory| Description                       |
422| -------- | ---------------------- | ---- | --------------------------- |
423| soundID | number | Yes  | Sound ID, which is obtained by calling **load()**.|
424| params | [PlayParameters](#playparameters) | Yes | Playback parameters.|
425| callback | AsyncCallback\<number> | Yes  | Callback used to return the audio stream ID. A valid value must be greater than 0.|
426
427**Error codes**
428
429For details about the error codes, see [Media Error Codes](errorcode-media.md).
430
431| ID| Error Message                               |
432| -------- | --------------------------------------- |
433| 401  | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed.  Return by callback. |
434| 5400102  | Operation not allowed. Return by callback. |
435| 5400105  | Service died. Return by callback.       |
436
437**Example**
438
439```js
440import { BusinessError } from '@kit.BasicServicesKit';
441
442// Create a SoundPool instance.
443let soundPool: media.SoundPool;
444let audioRendererInfo: audio.AudioRendererInfo = {
445  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
446  rendererFlags: 1
447}
448media.createSoundPool(5, audioRendererInfo, (error: BusinessError, soundPool_: media.SoundPool) => {
449  if (error) {
450    console.error(`Failed to createSoundPool`)
451    return;
452  } else {
453    soundPool = soundPool_;
454    console.info(`Succeeded in createSoundPool`)
455    let soundID: number = 0;
456    let streamID: number = 0;
457    let playParameters: media.PlayParameters = {
458      loop: 3, // The sound is played four times (three loops).
459      rate: audio.AudioRendererRate.RENDER_RATE_NORMAL, // The sound is played at the original frequency.
460      leftVolume: 0.5, // range = 0.0-1.0
461      rightVolume: 0.5, // range = 0.0-1.0
462      priority: 0, // The sound playback has the lowest priority.
463    }
464    soundPool.play(soundID, playParameters, (error: BusinessError, streamId: number) => {
465      if (error) {
466        console.error(`Failed to play soundpool: errCode is ${error.code}, errMessage is ${error.message}`)
467      } else {
468        streamID = streamId;
469        console.info('Succeeded in playing soundpool, streamId:' + streamId);
470      }
471    });
472  }
473});
474
475```
476
477### play
478
479play(soundID: number, callback: AsyncCallback\<number>): void
480
481Plays a sound. This API uses an asynchronous callback to obtain the audio stream ID.
482
483**System capability**: SystemCapability.Multimedia.Media.SoundPool
484
485**Parameters**
486
487| Name  | Type                  | Mandatory| Description                       |
488| -------- | ---------------------- | ---- | --------------------------- |
489| soundID | number | Yes  | Sound ID, which is obtained by calling **load()**.|
490| callback | AsyncCallback\<number> | Yes  | Callback used to return the audio stream ID. A valid value must be greater than 0.|
491
492**Error codes**
493
494For details about the error codes, see [Media Error Codes](errorcode-media.md).
495
496| ID| Error Message                               |
497| -------- | --------------------------------------- |
498| 401  | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed.  Return by callback. |
499| 5400102  | Operation not allowed. Return by callback. |
500| 5400105  | Service died. Return by callback.       |
501
502**Example**
503
504```js
505import { BusinessError } from '@kit.BasicServicesKit';
506
507// Create a SoundPool instance.
508let soundPool: media.SoundPool;
509let audioRendererInfo: audio.AudioRendererInfo = {
510  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
511  rendererFlags: 1
512}
513media.createSoundPool(5, audioRendererInfo, (error: BusinessError, soundPool_: media.SoundPool) => {
514  if (error) {
515    console.error(`Failed to createSoundPool`)
516    return;
517  } else {
518    soundPool = soundPool_;
519    console.info(`Succeeded in createSoundPool`)
520    let soundID: number = 0;
521    let streamID: number = 0;
522    soundPool.play(soundID,  (error: BusinessError, streamId: number) => {
523      if (error) {
524        console.error(`Failed to play soundpool: errCode is ${error.code}, errMessage is ${error.message}`)
525      } else {
526        streamID = streamId;
527        console.info('Succeeded in playing soundpool, streamId:' + streamId);
528      }
529    });
530  }
531});
532
533```
534
535### play
536
537play(soundID: number, params?: PlayParameters): Promise\<number>
538
539Plays a sound. This API uses a promise to obtain the audio stream ID.
540
541**System capability**: SystemCapability.Multimedia.Media.SoundPool
542
543**Parameters**
544
545| Name  | Type                  | Mandatory| Description                       |
546| -------- | ---------------------- | ---- | --------------------------- |
547| soundID | number | Yes  | Sound ID, which is obtained by calling **load()**.|
548| params | [PlayParameters](#playparameters) | No | Playback parameters.|
549
550**Return value**
551
552| Type            | Description                            |
553| ---------------- | -------------------------------- |
554| Promise\<number> | Promise used to return the audio stream ID. A valid value must be greater than 0.|
555
556**Error codes**
557
558For details about the error codes, see [Media Error Codes](errorcode-media.md).
559
560| ID| Error Message                               |
561| -------- | --------------------------------------- |
562| 401  | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed.  Return by promise. |
563| 5400102  | Operation not allowed. Return by promise. |
564| 5400105  | Service died. Return by promise.       |
565
566**Example**
567
568```js
569import { BusinessError } from '@kit.BasicServicesKit';
570
571// Create a SoundPool instance.
572let soundPool: media.SoundPool;
573let audioRendererInfo: audio.AudioRendererInfo = {
574  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
575  rendererFlags: 1
576}
577media.createSoundPool(5, audioRendererInfo, (error: BusinessError, soundPool_: media.SoundPool) => {
578  if (error) {
579    console.error(`Failed to createSoundPool`)
580    return;
581  } else {
582    soundPool = soundPool_;
583    console.info(`Succeeded in createSoundPool`)
584    let soundID: number = 0;
585    let streamID: number = 0;
586    let playParameters: media.PlayParameters = {
587      loop: 3, // The sound is played four times (three loops).
588      rate: audio.AudioRendererRate.RENDER_RATE_NORMAL, // The sound is played at the original frequency.
589      leftVolume: 0.5, // range = 0.0-1.0.
590      rightVolume: 0.5, // range = 0.0-1.0.
591      priority: 0, // The sound playback has the lowest priority.
592    }
593
594    soundPool.play(soundID, playParameters).then((streamId: number) => {
595      console.info('Succeeded in playing soundpool');
596      streamID = streamId;
597    },(err: BusinessError) => {
598      console.error('Failed to play soundpool and catch error is ' + err.message);
599    });
600  }
601});
602
603```
604
605### stop
606
607stop(streamID: number, callback: AsyncCallback\<void>): void
608
609Stops playing a sound. This API uses an asynchronous callback to return the result.
610
611**System capability**: SystemCapability.Multimedia.Media.SoundPool
612
613**Parameters**
614
615| Name  | Type                  | Mandatory| Description                       |
616| -------- | ---------------------- | ---- | --------------------------- |
617| streamID | number | Yes  | Audio stream ID, which is obtained by calling **play()**.|
618| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
619
620**Error codes**
621
622For details about the error codes, see [Media Error Codes](errorcode-media.md).
623
624| ID| Error Message                               |
625| -------- | --------------------------------------- |
626| 401  | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed.  Return by callback. |
627| 5400102  | Operation not allowed. Return by callback. |
628| 5400105  | Service died. Return by callback.       |
629
630**Example**
631
632```js
633import { BusinessError } from '@kit.BasicServicesKit';
634
635// Create a SoundPool instance.
636let soundPool: media.SoundPool;
637let audioRendererInfo: audio.AudioRendererInfo = {
638  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
639  rendererFlags: 1
640}
641media.createSoundPool(5, audioRendererInfo, (error: BusinessError, soundPool_: media.SoundPool) => {
642  if (error) {
643    console.error(`Failed to createSoundPool`)
644    return;
645  } else {
646    soundPool = soundPool_;
647    console.info(`Succeeded in createSoundPool`)
648    let streamID: number = 0;
649    // Call play() to obtain the stream ID.
650    soundPool.stop(streamID, (error: BusinessError) => {
651      if (error) {
652        console.error(`Failed to stop soundpool: errCode is ${error.code}, errMessage is ${error.message}`)
653      } else {
654        console.info('Succeeded in stopping soundpool');
655      }
656    })
657  }
658});
659
660```
661
662### stop
663
664stop(streamID: number): Promise\<void>
665
666Stops playing a sound. This API uses a promise to return the result.
667
668**System capability**: SystemCapability.Multimedia.Media.SoundPool
669
670**Parameters**
671
672| Name  | Type                  | Mandatory| Description                       |
673| -------- | ---------------------- | ---- | --------------------------- |
674| streamID | number | Yes  | Audio stream ID, which is obtained by calling **play()**.|
675
676**Return value**
677
678| Type            | Description                            |
679| ---------------- | -------------------------------- |
680| Promise\<void> | Promise that returns no value.|
681
682**Error codes**
683
684For details about the error codes, see [Media Error Codes](errorcode-media.md).
685
686| ID| Error Message                               |
687| -------- | --------------------------------------- |
688| 401  | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed.  Return by promise. |
689| 5400102  | Operation not allowed. Return by promise. |
690| 5400105  | Service died. Return by promise.       |
691
692**Example**
693
694```js
695import { BusinessError } from '@kit.BasicServicesKit';
696
697// Create a SoundPool instance.
698let soundPool: media.SoundPool;
699let audioRendererInfo: audio.AudioRendererInfo = {
700  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
701  rendererFlags: 1
702}
703media.createSoundPool(5, audioRendererInfo, (error: BusinessError, soundPool_: media.SoundPool) => {
704  if (error) {
705    console.error(`Failed to createSoundPool`)
706    return;
707  } else {
708    soundPool = soundPool_;
709    console.info(`Succeeded in createSoundPool`)
710    let streamID: number = 0;
711    // Call play() to obtain the stream ID.
712    soundPool.stop(streamID).then(() => {
713      console.info('Succeeded in stopping soundpool');
714    }, (err: BusinessError) => {
715      console.error('Failed to stop soundpool and catch error is ' + err.message);
716    });
717  }
718});
719```
720
721### setLoop
722
723setLoop(streamID: number, loop: number, callback: AsyncCallback\<void>): void;
724
725Sets the loop mode for an audio stream. This API uses an asynchronous callback to return the result.
726
727**System capability**: SystemCapability.Multimedia.Media.SoundPool
728
729**Parameters**
730
731| Name  | Type                  | Mandatory| Description                       |
732| -------- | ---------------------- | ---- | --------------------------- |
733| streamID | number | Yes  | Audio stream ID, which is obtained by calling **play()**.|
734| loop | number | Yes  | Number of loops.<br>If this parameter is set to a value greater than or equal to 0, the number of times the content is actually played is the value of **loop** plus 1.<br> If this parameter is set to a value less than 0, the content is played repeatedly.|
735| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
736
737**Error codes**
738
739For details about the error codes, see [Media Error Codes](errorcode-media.md).
740
741| ID| Error Message                               |
742| -------- | --------------------------------------- |
743| 401  | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed.  Return by callback. |
744| 5400102  | Operation not allowed. Return by callback. |
745| 5400105  | Service died. Return by callback.       |
746
747**Example**
748
749```js
750import { BusinessError } from '@kit.BasicServicesKit';
751
752// Create a SoundPool instance.
753let soundPool: media.SoundPool;
754let audioRendererInfo: audio.AudioRendererInfo = {
755  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
756  rendererFlags: 1
757}
758media.createSoundPool(5, audioRendererInfo, (error: BusinessError, soundPool_: media.SoundPool) => {
759  if (error) {
760    console.error(`Failed to createSoundPool`)
761    return;
762  } else {
763    soundPool = soundPool_;
764    console.info(`Succeeded in createSoundPool`)
765    let streamID: number = 0;
766    // Call play() to obtain the stream ID.
767    // Set the number of loops to 2.
768    soundPool.setLoop(streamID, 2, (error: BusinessError) => {
769      if (error) {
770        console.error(`Failed to setLoop soundPool: errCode is ${error.code}, errMessage is ${error.message}`)
771      } else {
772        console.info('Succeeded in setLoopping soundpool, streamID:' + streamID);
773      }
774    });
775  }
776});
777
778```
779
780### setLoop
781
782setLoop(streamID: number, loop: number): Promise\<void>
783
784Sets the loop mode for an audio stream. This API uses a promise to return the result.
785
786**System capability**: SystemCapability.Multimedia.Media.SoundPool
787
788**Parameters**
789
790| Name  | Type                  | Mandatory| Description                       |
791| -------- | ---------------------- | ---- | --------------------------- |
792| streamID | number | Yes  | Audio stream ID, which is obtained by calling **play()**.|
793| loop | number | Yes  | Number of loops.<br>If this parameter is set to a value greater than or equal to 0, the number of times the content is actually played is the value of **loop** plus 1.<br> If this parameter is set to a value less than 0, the content is played repeatedly.|
794
795**Return value**
796
797| Type            | Description                            |
798| ---------------- | -------------------------------- |
799| Promise\<void> | Promise that returns no value.|
800
801**Error codes**
802
803For details about the error codes, see [Media Error Codes](errorcode-media.md).
804
805| ID| Error Message                               |
806| -------- | --------------------------------------- |
807| 401  | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed.  Return by promise. |
808| 5400102  | Operation not allowed. Return by promise. |
809| 5400105  | Service died. Return by promise.       |
810
811**Example**
812
813```js
814import { BusinessError } from '@kit.BasicServicesKit';
815
816// Create a SoundPool instance.
817let soundPool: media.SoundPool;
818let audioRendererInfo: audio.AudioRendererInfo = {
819  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
820  rendererFlags: 1
821}
822media.createSoundPool(5, audioRendererInfo, (error: BusinessError, soundPool_: media.SoundPool) => {
823  if (error) {
824    console.error(`Failed to createSoundPool`)
825    return;
826  } else {
827    soundPool = soundPool_;
828    console.info(`Succeeded in createSoundPool`)
829    let streamID: number = 0;
830    // Call play() to obtain the stream ID.
831    // Set the number of loops to 1.
832    soundPool.setLoop(streamID, 1).then(() => {
833      console.info('Succeeded in setLoopping soundpool, streamID:' + streamID);
834    }).catch((err: BusinessError) => {
835      console.error('Failed to setLoop soundPool and catch error is ' + err.message);
836    });
837  }
838});
839
840```
841
842### setPriority
843
844setPriority(streamID: number, priority: number, callback: AsyncCallback\<void>): void
845
846Sets the priority for an audio stream. This API uses an asynchronous callback to return the result.
847
848**System capability**: SystemCapability.Multimedia.Media.SoundPool
849
850**Parameters**
851
852| Name  | Type                  | Mandatory| Description                       |
853| -------- | ---------------------- | ---- | --------------------------- |
854| streamID | number | Yes  | Audio stream ID, which is obtained by calling **play()**.|
855| priority | number | Yes  | Priority. The value **0** means the lowest priority. The value is an integer greater than or equal to 0.|
856| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
857
858**Error codes**
859
860For details about the error codes, see [Media Error Codes](errorcode-media.md).
861
862| ID| Error Message                               |
863| -------- | --------------------------------------- |
864| 401  | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed.  Return by callback. |
865| 5400102  | Operation not allowed. Return by callback. |
866| 5400105  | Service died. Return by callback.       |
867
868**Example**
869
870```js
871import { BusinessError } from '@kit.BasicServicesKit';
872
873// Create a SoundPool instance.
874let soundPool: media.SoundPool;
875let audioRendererInfo: audio.AudioRendererInfo = {
876  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
877  rendererFlags: 1
878}
879media.createSoundPool(5, audioRendererInfo, (error: BusinessError, soundPool_: media.SoundPool) => {
880  if (error) {
881    console.error(`Failed to createSoundPool`)
882    return;
883  } else {
884    soundPool = soundPool_;
885    console.info(`Succeeded in createSoundPool`)
886    let streamID: number = 0;
887    // Call play() to obtain the stream ID.
888    // Set the priority to 1.
889    soundPool.setPriority(streamID, 1, (error: BusinessError) => {
890      if (error) {
891        console.error(`Failed to setPriority soundPool: errCode is ${error.code}, errMessage is ${error.message}`)
892      } else {
893        console.info('Succeeded in setPriority soundpool, streamID:' + streamID);
894      }
895    });
896  }
897});
898
899```
900
901### setPriority
902
903setPriority(streamID: number, priority: number): Promise\<void>
904
905Sets the priority for an audio stream. This API uses a promise to return the result.
906
907**System capability**: SystemCapability.Multimedia.Media.SoundPool
908
909**Parameters**
910
911| Name  | Type                  | Mandatory| Description                       |
912| -------- | ---------------------- | ---- | --------------------------- |
913| streamID | number | Yes  | Audio stream ID, which is obtained by calling **play()**.|
914| priority | number | Yes  | Priority. The value **0** means the lowest priority. The value is an integer greater than or equal to 0.|
915
916**Return value**
917
918| Type            | Description                            |
919| ---------------- | -------------------------------- |
920| Promise\<void> | Promise that returns no value.|
921
922**Error codes**
923
924For details about the error codes, see [Media Error Codes](errorcode-media.md).
925
926| ID| Error Message                               |
927| -------- | --------------------------------------- |
928| 401  | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed.  Return by promise. |
929| 5400102  | Operation not allowed. Return by promise. |
930| 5400105  | Service died. Return by promise.       |
931
932**Example**
933
934```js
935import { BusinessError } from '@kit.BasicServicesKit';
936
937// Create a SoundPool instance.
938let soundPool: media.SoundPool;
939let audioRendererInfo: audio.AudioRendererInfo = {
940  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
941  rendererFlags: 1
942}
943media.createSoundPool(5, audioRendererInfo, (error: BusinessError, soundPool_: media.SoundPool) => {
944  if (error) {
945    console.error(`Failed to createSoundPool`)
946    return;
947  } else {
948    soundPool = soundPool_;
949    console.info(`Succeeded in createSoundPool`)
950    let streamID: number = 0;
951    // Call play() to obtain the stream ID.
952    // Set the priority to 1.
953
954    soundPool.setPriority(streamID, 1).then(() => {
955      console.info('Succeeded in setPriority soundpool');
956    }, (err: BusinessError) => {
957      console.error('Failed to setPriority soundPool and catch error is ' + err.message);
958    });
959  }
960});
961
962```
963
964### setRate
965
966setRate(streamID: number, rate: audio.AudioRendererRate, callback: AsyncCallback\<void>): void
967
968Sets the playback rate for an audio stream. This API uses an asynchronous callback to return the result.
969
970**System capability**: SystemCapability.Multimedia.Media.SoundPool
971
972**Parameters**
973
974| Name  | Type                  | Mandatory| Description                       |
975| -------- | ---------------------- | ---- | --------------------------- |
976| streamID | number | Yes  | Audio stream ID, which is obtained by calling **play()**.|
977| rate | [audio.AudioRendererRate](../apis-audio-kit/js-apis-audio.md#audiorendererrate8) | Yes  | Playback rate.|
978| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
979
980**Error codes**
981
982For details about the error codes, see [Media Error Codes](errorcode-media.md).
983
984| ID| Error Message                               |
985| -------- | --------------------------------------- |
986| 401  | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed.  Return by callback. |
987| 5400102  | Operation not allowed. Return by callback. |
988| 5400105  | Service died. Return by callback.       |
989
990**Example**
991
992```js
993import { BusinessError } from '@kit.BasicServicesKit';
994
995// Create a SoundPool instance.
996let soundPool: media.SoundPool;
997let audioRendererInfo: audio.AudioRendererInfo = {
998  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
999  rendererFlags: 1
1000}
1001media.createSoundPool(5, audioRendererInfo, (error: BusinessError, soundPool_: media.SoundPool) => {
1002  if (error) {
1003    console.error(`Failed to createSoundPool`)
1004    return;
1005  } else {
1006    soundPool = soundPool_;
1007    console.info(`Succeeded in createSoundPool`)
1008    let streamID: number = 0;
1009    let selectedAudioRendererRate: audio.AudioRendererRate = audio.AudioRendererRate.RENDER_RATE_NORMAL; // The sound is played at the original frequency.
1010    // Call play() to obtain the stream ID.
1011    soundPool.setRate(streamID, selectedAudioRendererRate, (error: BusinessError) => {
1012      if (error) {
1013        console.error(`Failed to setRate soundPool: errCode is ${error.code}, errMessage is ${error.message}`)
1014      } else {
1015        console.info('Succeeded in setRate success, streamID:' + streamID);
1016      }
1017    })
1018  }
1019});
1020
1021```
1022
1023### setRate
1024
1025setRate(streamID: number, rate: audio.AudioRendererRate): Promise\<void>
1026
1027Sets the playback rate for an audio stream. This API uses a promise to return the result.
1028
1029**System capability**: SystemCapability.Multimedia.Media.SoundPool
1030
1031**Parameters**
1032
1033| Name  | Type                  | Mandatory| Description                       |
1034| -------- | ---------------------- | ---- | --------------------------- |
1035| streamID | number | Yes  | Audio stream ID, which is obtained by calling **play()**.|
1036| rate | [audio.AudioRendererRate](../apis-audio-kit/js-apis-audio.md#audiorendererrate8) | Yes  | Playback rate.|
1037
1038**Return value**
1039
1040| Type            | Description                            |
1041| ---------------- | -------------------------------- |
1042| Promise\<void> | Promise that returns no value.|
1043
1044**Error codes**
1045
1046For details about the error codes, see [Media Error Codes](errorcode-media.md).
1047
1048| ID| Error Message                               |
1049| -------- | --------------------------------------- |
1050| 401  | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed.  Return by promise. |
1051| 5400102  | Operation not allowed. Return by promise. |
1052| 5400105  | Service died. Return by promise.       |
1053
1054**Example**
1055
1056```js
1057import { BusinessError } from '@kit.BasicServicesKit';
1058
1059// Create a SoundPool instance.
1060let soundPool: media.SoundPool;
1061let audioRendererInfo: audio.AudioRendererInfo = {
1062  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
1063  rendererFlags: 1
1064}
1065media.createSoundPool(5, audioRendererInfo, (error: BusinessError, soundPool_: media.SoundPool) => {
1066  if (error) {
1067    console.error(`Failed to createSoundPool`)
1068    return;
1069  } else {
1070    soundPool = soundPool_;
1071    console.info(`Succeeded in createSoundPool`)
1072    let streamID: number = 0;
1073    let selectedAudioRendererRate: audio.AudioRendererRate = audio.AudioRendererRate.RENDER_RATE_NORMAL; // The sound is played at the original frequency.
1074    // Call play() to obtain the stream ID.
1075    soundPool.setRate(streamID, selectedAudioRendererRate).then(() => {
1076      console.info('Succeeded in setRate soundpool');
1077    }, (err: BusinessError) => {
1078      console.error('Failed to setRate soundpool and catch error is ' + err.message);
1079    });
1080  }
1081});
1082
1083```
1084
1085### setVolume
1086
1087setVolume(streamID: number, leftVolume: number, rightVolume: number, callback: AsyncCallback\<void>): void
1088
1089Sets the volume for an audio stream. This API uses an asynchronous callback to return the result.
1090
1091**System capability**: SystemCapability.Multimedia.Media.SoundPool
1092
1093**Parameters**
1094
1095| Name  | Type                  | Mandatory| Description                       |
1096| -------- | ---------------------- | ---- | --------------------------- |
1097| streamID | number | Yes  | Audio stream ID, which is obtained by calling **play()**.|
1098| leftVolume | number | Yes  | Volume of the left channel. The value ranges from 0.0 to 1.0.|
1099| rightVolume | number | Yes  | Volume of the right channel. The value ranges from 0.0 to 1.0. Currently, setting the volume for the right channel does not take effect. The volume set for the left channel is used.|
1100| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
1101
1102**Error codes**
1103
1104For details about the error codes, see [Media Error Codes](errorcode-media.md).
1105
1106| ID| Error Message                               |
1107| -------- | --------------------------------------- |
1108| 401  | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed.  Return by callback. |
1109| 5400102  | Operation not allowed. Return by callback. |
1110| 5400105  | Service died. Return by callback.       |
1111
1112**Example**
1113
1114```js
1115import { BusinessError } from '@kit.BasicServicesKit';
1116
1117// Create a SoundPool instance.
1118let soundPool: media.SoundPool;
1119let audioRendererInfo: audio.AudioRendererInfo = {
1120  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
1121  rendererFlags: 1
1122}
1123media.createSoundPool(5, audioRendererInfo, (error: BusinessError, soundPool_: media.SoundPool) => {
1124  if (error) {
1125    console.error(`Failed to createSoundPool`)
1126    return;
1127  } else {
1128    soundPool = soundPool_;
1129    console.info(`Succeeded in createSoundPool`)
1130    let streamID: number = 0;
1131    // Call play() to obtain the stream ID.
1132    // Set the volume to 0.5.
1133    soundPool.setVolume(streamID, 0.5, 0.5, (error: BusinessError) => {
1134      if (error) {
1135        console.error(`Failed to setVolume soundPool: errCode is ${error.code}, errMessage is ${error.message}`)
1136      } else {
1137        console.info('Succeeded in setVolume soundpool, streamID:' + streamID);
1138      }
1139    })
1140  }
1141});
1142
1143```
1144
1145### setVolume
1146
1147setVolume(streamID: number, leftVolume: number, rightVolume: number): Promise\<void>
1148
1149Sets the volume for an audio stream. This API uses a promise to return the result.
1150
1151**System capability**: SystemCapability.Multimedia.Media.SoundPool
1152
1153**Parameters**
1154
1155| Name  | Type                  | Mandatory| Description                       |
1156| -------- | ---------------------- | ---- | --------------------------- |
1157| streamID | number | Yes  | Audio stream ID, which is obtained by calling **play()**.|
1158| leftVolume | number | Yes  | Volume of the left channel. The value ranges from 0.0 to 1.0.|
1159| rightVolume | number | Yes  | Volume of the right channel. The value ranges from 0.0 to 1.0. Currently, setting the volume for the right channel does not take effect. The volume set for the left channel is used.|
1160
1161**Return value**
1162
1163| Type            | Description                            |
1164| ---------------- | -------------------------------- |
1165| Promise\<void> | Promise that returns no value.|
1166
1167**Error codes**
1168
1169For details about the error codes, see [Media Error Codes](errorcode-media.md).
1170
1171| ID| Error Message                               |
1172| -------- | --------------------------------------- |
1173| 401  | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed.  Return by promise. |
1174| 5400102  | Operation not allowed. Return by promise. |
1175| 5400105  | Service died. Return by promise.       |
1176
1177**Example**
1178
1179```js
1180import { BusinessError } from '@kit.BasicServicesKit';
1181
1182// Create a SoundPool instance.
1183let soundPool: media.SoundPool;
1184let audioRendererInfo: audio.AudioRendererInfo = {
1185  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
1186  rendererFlags: 1
1187}
1188media.createSoundPool(5, audioRendererInfo, (error: BusinessError, soundPool_: media.SoundPool) => {
1189  if (error) {
1190    console.error(`Failed to createSoundPool`)
1191    return;
1192  } else {
1193    soundPool = soundPool_;
1194    console.info(`Succeeded in createSoundPool`)
1195    let streamID: number = 0;
1196    // Call play() to obtain the stream ID.
1197
1198    soundPool.setVolume(streamID, 0.5, 0.5).then(() => {
1199      console.info('Succeeded in setVolume soundpool');
1200    }, (err: BusinessError) => {
1201      console.error('Failed to setVolume soundPool and catch error is ' + err.message);
1202    });
1203  }
1204});
1205
1206```
1207
1208### unload
1209
1210unload(soundID: number, callback: AsyncCallback\<void>): void
1211
1212Unloads a sound. This API uses an asynchronous callback to return the result.
1213
1214**System capability**: SystemCapability.Multimedia.Media.SoundPool
1215
1216**Parameters**
1217
1218| Name  | Type                  | Mandatory| Description                       |
1219| -------- | ---------------------- | ---- | --------------------------- |
1220| soundID | number | Yes  | Sound ID, which is obtained by calling **load()**.|
1221| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
1222
1223**Error codes**
1224
1225For details about the error codes, see [Media Error Codes](errorcode-media.md).
1226
1227| ID| Error Message                               |
1228| -------- | --------------------------------------- |
1229| 5400102  | Operation not allowed. Return by callback. |
1230| 5400103  | I/O error. Return by callback. |
1231| 5400105  | Service died. Return by callback.       |
1232
1233**Example**
1234
1235```js
1236import { BusinessError } from '@kit.BasicServicesKit';
1237
1238// Create a SoundPool instance.
1239let soundPool: media.SoundPool;
1240let audioRendererInfo: audio.AudioRendererInfo = {
1241  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
1242  rendererFlags: 1
1243}
1244media.createSoundPool(5, audioRendererInfo, (error: BusinessError, soundPool_: media.SoundPool) => {
1245  if (error) {
1246    console.error(`Failed to createSoundPool`)
1247    return;
1248  } else {
1249    soundPool = soundPool_;
1250    console.info(`Succeeded in createSoundPool`)
1251    let soundID: number = 0;
1252    // Call load() to obtain the sound ID.
1253    soundPool.unload(soundID, (error: BusinessError) => {
1254      if (error) {
1255        console.error(`Failed to unload soundPool: errCode is ${error.code}, errMessage is ${error.message}`)
1256      } else {
1257        console.info('Succceeded in unload soundPool');
1258      }
1259    })
1260  }
1261});
1262
1263```
1264
1265### unload
1266
1267unload(soundID: number): Promise\<void>
1268
1269Unloads a sound. This API uses a promise to return the result.
1270
1271**System capability**: SystemCapability.Multimedia.Media.SoundPool
1272
1273**Parameters**
1274
1275| Name  | Type                  | Mandatory| Description                       |
1276| -------- | ---------------------- | ---- | --------------------------- |
1277| soundID | number | Yes  | Sound ID, which is obtained by calling **load()**.|
1278
1279**Return value**
1280
1281| Type            | Description                            |
1282| ---------------- | -------------------------------- |
1283| Promise\<void> | Promise that returns no value.|
1284
1285**Error codes**
1286
1287For details about the error codes, see [Media Error Codes](errorcode-media.md).
1288
1289| ID| Error Message                               |
1290| -------- | --------------------------------------- |
1291| 5400102  | Operation not allowed. Return by promise. |
1292| 5400103  | I/O error. Return by promise. |
1293| 5400105  | Service died. Return by promise.       |
1294
1295**Example**
1296
1297```js
1298import { BusinessError } from '@kit.BasicServicesKit';
1299
1300// Create a SoundPool instance.
1301let soundPool: media.SoundPool;
1302let audioRendererInfo: audio.AudioRendererInfo = {
1303  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
1304  rendererFlags: 1
1305}
1306media.createSoundPool(5, audioRendererInfo, (error: BusinessError, soundPool_: media.SoundPool) => {
1307  if (error) {
1308    console.error(`Failed to createSoundPool`)
1309    return;
1310  } else {
1311    soundPool = soundPool_;
1312    console.info(`Succeeded in createSoundPool`)
1313    let soundID: number = 0;
1314    // Call load() to obtain the sound ID.
1315
1316    soundPool.unload(soundID).then(() => {
1317      console.info('Succceeded in unload soundPool');
1318    }, (err: BusinessError) => {
1319      console.error('Failed to unload soundPool and catch error is ' + err.message);
1320    });
1321  }
1322});
1323
1324```
1325
1326### release
1327
1328release(callback: AsyncCallback\<void>): void
1329
1330Releases this **SoundPool** instance. This API uses an asynchronous callback to return the result.
1331
1332**System capability**: SystemCapability.Multimedia.Media.SoundPool
1333
1334**Parameters**
1335
1336| Name  | Type                  | Mandatory| Description                       |
1337| -------- | ---------------------- | ---- | --------------------------- |
1338| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
1339
1340**Error codes**
1341
1342For details about the error codes, see [Media Error Codes](errorcode-media.md).
1343
1344| ID| Error Message                               |
1345| -------- | --------------------------------------- |
1346| 5400105  | Service died. Return by callback.       |
1347
1348**Example**
1349
1350```js
1351import { BusinessError } from '@kit.BasicServicesKit';
1352
1353// Create a SoundPool instance.
1354let soundPool: media.SoundPool;
1355let audioRendererInfo: audio.AudioRendererInfo = {
1356  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
1357  rendererFlags: 1
1358}
1359media.createSoundPool(5, audioRendererInfo, (error: BusinessError, soundPool_: media.SoundPool) => {
1360  if (error) {
1361    console.error(`Failed to createSoundPool`)
1362    return;
1363  } else {
1364    soundPool = soundPool_;
1365    console.info(`Succeeded in createSoundPool`)
1366    soundPool.release((error: BusinessError) => {
1367      if (error) {
1368        console.error(`Failed to release soundPool: errCode is ${error.code}, errMessage is ${error.message}`)
1369      } else {
1370        console.info('Succeeded in releasing soundPool');
1371      }
1372    })
1373  }
1374});
1375
1376
1377```
1378
1379### release
1380
1381release(): Promise\<void>
1382
1383Releases this **SoundPool** instance. This API uses a promise to return the result.
1384
1385**System capability**: SystemCapability.Multimedia.Media.SoundPool
1386
1387**Return value**
1388
1389| Type            | Description                            |
1390| ---------------- | -------------------------------- |
1391| Promise\<void> | Promise that returns no value.|
1392
1393**Error codes**
1394
1395For details about the error codes, see [Media Error Codes](errorcode-media.md).
1396
1397| ID| Error Message                               |
1398| -------- | --------------------------------------- |
1399| 5400105  | Service died. Return by promise.       |
1400
1401**Example**
1402
1403```js
1404import { BusinessError } from '@kit.BasicServicesKit';
1405
1406// Create a SoundPool instance.
1407let soundPool: media.SoundPool;
1408let audioRendererInfo: audio.AudioRendererInfo = {
1409  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
1410  rendererFlags: 1
1411}
1412media.createSoundPool(5, audioRendererInfo, (error: BusinessError, soundPool_: media.SoundPool) => {
1413  if (error) {
1414    console.error(`Failed to createSoundPool`)
1415    return;
1416  } else {
1417    soundPool = soundPool_;
1418    console.info(`Succeeded in createSoundPool`)
1419    soundPool.release().then(() => {
1420      console.info('Succeeded in releasing soundPool');
1421    }, (err: BusinessError) => {
1422      console.error('Failed to release soundPool and catch error is ' + err.message);
1423    });
1424  }
1425});
1426
1427```
1428
1429### on('loadComplete')
1430
1431on(type: 'loadComplete', callback: Callback\<number>): void
1432
1433Subscribes to events indicating that a sound finishes loading.
1434
1435**System capability**: SystemCapability.Multimedia.Media.SoundPool
1436
1437**Parameters**
1438
1439| Name  | Type    | Mandatory| Description                                                        |
1440| -------- | -------- | ---- | ------------------------------------------------------------ |
1441| type     | string   | Yes  | Event type, which is **'loadComplete'** in this case. This event is triggered when a sound is loaded.|
1442| callback | Callback\<number> | Yes  | ID of the sound that has been loaded.                              |
1443
1444**Example**
1445
1446```js
1447import { BusinessError } from '@kit.BasicServicesKit';
1448
1449// Create a SoundPool instance.
1450let soundPool: media.SoundPool;
1451let audioRendererInfo: audio.AudioRendererInfo = {
1452  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
1453  rendererFlags: 1
1454}
1455media.createSoundPool(5, audioRendererInfo, (error: BusinessError, soundPool_: media.SoundPool) => {
1456  if (error) {
1457    console.error(`Failed to createSoundPool`)
1458    return;
1459  } else {
1460    soundPool = soundPool_;
1461    console.info(`Succeeded in createSoundPool`)
1462    soundPool.on('loadComplete', (soundId: number) => {
1463      console.info('Succeeded in loadComplete, soundId: ' + soundId)
1464    })
1465  }
1466});
1467
1468```
1469
1470### off('loadComplete')
1471
1472off(type: 'loadComplete'): void
1473
1474Unsubscribes from events indicating that a sound finishes loading.
1475
1476**System capability**: SystemCapability.Multimedia.Media.SoundPool
1477
1478**Parameters**
1479
1480| Name| Type  | Mandatory| Description                                                        |
1481| ------ | ------ | ---- | ------------------------------------------------------------ |
1482| type   | string | Yes  | Event type. The value is fixed at **'loadComplete'**.|
1483
1484**Example**
1485
1486```js
1487import { BusinessError } from '@kit.BasicServicesKit';
1488
1489// Create a SoundPool instance.
1490let soundPool: media.SoundPool;
1491let audioRendererInfo: audio.AudioRendererInfo = {
1492  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
1493  rendererFlags: 1
1494}
1495media.createSoundPool(5, audioRendererInfo, (error: BusinessError, soundPool_: media.SoundPool) => {
1496  if (error) {
1497    console.error(`Failed to createSoundPool`)
1498    return;
1499  } else {
1500    soundPool = soundPool_;
1501    console.info(`Succeeded in createSoundPool`)
1502    soundPool.off('loadComplete')
1503  }
1504});
1505
1506```
1507
1508### on('playFinishedWithStreamId')<sup>18+</sup>
1509
1510on(type: 'playFinishedWithStreamId', callback: Callback\<number>): void
1511
1512Subscribes to events indicating the completion of audio playback and returns the stream ID of the audio that finishes playing.
1513
1514When only [on('playFinished')](#onplayfinished) or [on('playFinishedWithStreamId')](#onplayfinishedwithstreamid18) is subscribed to, the registered callback is triggered when the audio playback is complete.
1515
1516When both [on('playFinished')](#onplayfinished) and [on('playFinishedWithStreamId')](#onplayfinishedwithstreamid18) are subscribed to, the 'playFinishedWithStreamId' callback is triggered, but the 'playFinished' callback is not triggered, when the audio playback is complete.
1517
1518**System capability**: SystemCapability.Multimedia.Media.SoundPool
1519
1520**Parameters**
1521
1522| Name  | Type    | Mandatory| Description                                                        |
1523| -------- | -------- | ---- | ------------------------------------------------------------ |
1524| type     | string   | Yes  | Event type, which is **'playFinishedWithStreamId'** in this case. This event is triggered when an audio stream finishes playing, and the stream ID is returned.|
1525| callback | Callback\<number> | Yes  |  Callback used to return the result. Stream ID of the audio that finishes playing.  |
1526
1527**Example**
1528
1529```js
1530import { BusinessError } from '@kit.BasicServicesKit';
1531
1532// Create a SoundPool instance.
1533let soundPool_: media.SoundPool;
1534let audioRendererInfo: audio.AudioRendererInfo = {
1535  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
1536  rendererFlags: 1
1537}
1538media.createSoundPool(5, audioRendererInfo, (error: BusinessError, soundPool: media.SoundPool) => {
1539  if (error) {
1540    console.error(`Failed to createSoundPool`)
1541  } else {
1542    soundPool_ = soundPool;
1543    console.info(`Succeeded in createSoundPool`)
1544    soundPool_.on('playFinishedWithStreamId', (streamId) => {
1545      console.info('The stream with streamId: ' + streamId + ' has finished playing.')
1546    });
1547  }
1548});
1549
1550```
1551
1552### off('playFinishedWithStreamId')<sup>18+</sup>
1553
1554off(type: 'playFinishedWithStreamId'): void
1555
1556Unsubscribes from events indicating that a sound finishes playing.
1557
1558**System capability**: SystemCapability.Multimedia.Media.SoundPool
1559
1560**Parameters**
1561
1562| Name| Type  | Mandatory| Description                                                        |
1563| ------ | ------ | ---- | ------------------------------------------------------------ |
1564| type   | string | Yes  | Event type. The value is fixed at **'playFinishedWithStreamId'**.|
1565
1566**Example**
1567
1568```js
1569import { BusinessError } from '@kit.BasicServicesKit';
1570
1571// Create a SoundPool instance.
1572let soundPool_: media.SoundPool;
1573let audioRendererInfo: audio.AudioRendererInfo = {
1574  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
1575  rendererFlags: 1
1576}
1577media.createSoundPool(5, audioRendererInfo, (error: BusinessError, soundPool: media.SoundPool) => {
1578  if (error) {
1579    console.error(`Failed to createSoundPool`)
1580  } else {
1581    soundPool_ = soundPool;
1582    console.info(`Succeeded in createSoundPool`)
1583    soundPool_.off('playFinishedWithStreamId')
1584  }
1585});
1586
1587```
1588
1589### on('playFinished')
1590
1591on(type: 'playFinished', callback: Callback\<void>): void
1592
1593Subscribes to events indicating that a sound finishes playing.
1594
1595**System capability**: SystemCapability.Multimedia.Media.SoundPool
1596
1597**Parameters**
1598
1599| Name  | Type    | Mandatory| Description                                                        |
1600| -------- | -------- | ---- | ------------------------------------------------------------ |
1601| type     | string   | Yes  | Event type, which is **'playFinished'** in this case. This event is triggered when a sound finishes playing.|
1602| callback | Callback\<void> | Yes  |  Callback used to return the result.       |
1603
1604**Example**
1605
1606```js
1607import { BusinessError } from '@kit.BasicServicesKit';
1608
1609// Create a SoundPool instance.
1610let soundPool: media.SoundPool;
1611let audioRendererInfo: audio.AudioRendererInfo = {
1612  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
1613  rendererFlags: 1
1614}
1615media.createSoundPool(5, audioRendererInfo, (error: BusinessError, soundPool_: media.SoundPool) => {
1616  if (error) {
1617    console.error(`Failed to createSoundPool`)
1618    return;
1619  } else {
1620    soundPool = soundPool_;
1621    console.info(`Succeeded in createSoundPool`)
1622    soundPool.on('playFinished', () => {
1623      console.info('Succeeded in playFinished')
1624    });
1625  }
1626});
1627
1628```
1629
1630### off('playFinished')
1631
1632off(type: 'playFinished'): void
1633
1634Unsubscribes from events indicating that a sound finishes playing.
1635
1636**System capability**: SystemCapability.Multimedia.Media.SoundPool
1637
1638**Parameters**
1639
1640| Name| Type  | Mandatory| Description                                                        |
1641| ------ | ------ | ---- | ------------------------------------------------------------ |
1642| type   | string | Yes  | Event type. The value is fixed at **'playFinished'**.|
1643
1644**Example**
1645
1646```js
1647import { BusinessError } from '@kit.BasicServicesKit';
1648
1649// Create a SoundPool instance.
1650let soundPool: media.SoundPool;
1651let audioRendererInfo: audio.AudioRendererInfo = {
1652  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
1653  rendererFlags: 1
1654}
1655media.createSoundPool(5, audioRendererInfo, (error: BusinessError, soundPool_: media.SoundPool) => {
1656  if (error) {
1657    console.error(`Failed to createSoundPool`)
1658    return;
1659  } else {
1660    soundPool = soundPool_;
1661    console.info(`Succeeded in createSoundPool`)
1662    soundPool.off('playFinished')
1663  }
1664});
1665
1666```
1667
1668### on('error')
1669
1670on(type: 'error', callback: ErrorCallback): void
1671
1672Subscribes to error events of this **SoundPool** instance. This event is used only for error prompt.
1673
1674**System capability**: SystemCapability.Multimedia.Media.SoundPool
1675
1676**Parameters**
1677
1678| Name  | Type    | Mandatory| Description                                                        |
1679| -------- | -------- | ---- | ------------------------------------------------------------ |
1680| type     | string   | Yes  | Event type, which is **'error'** in this case. This event can be triggered by both user operations and the system.|
1681| callback | ErrorCallback | Yes  | Callback used to return the error code ID and error message.|
1682
1683The **SoundPool** class provides the following error types<a name = error_info></a>:
1684
1685| ID| Error Message             | Description                                                        |
1686| -------- | --------------------- | ------------------------------------------------------------ |
1687| 401      | Invalid Parameter.    | Incorrect input parameter, causing an invalid call.                                    |
1688| 801      | Unsupport Capability. | Unsupported API, causing an invalid call.                             |
1689| 5400101  | No Memory.            | Insufficient memory.|
1690| 5400102  | Operation Not Allowed.   | Unsupported operation in the current state, causing an invalid call.                      |
1691| 5400103  | IO Error.             | I/O exception.|
1692| 5400105  | Service Died.         | The playback process is dead, and the service on which the sound pool depends is abnormal.|
1693
1694**Example**
1695
1696```js
1697import { BusinessError } from '@kit.BasicServicesKit';
1698
1699// Create a SoundPool instance.
1700let soundPool: media.SoundPool;
1701let audioRendererInfo: audio.AudioRendererInfo = {
1702  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
1703  rendererFlags: 1
1704}
1705media.createSoundPool(5, audioRendererInfo, (error: BusinessError, soundPool_: media.SoundPool) => {
1706  if (error) {
1707    console.error(`Failed to createSoundPool`)
1708    return;
1709  } else {
1710    soundPool = soundPool_;
1711    console.info(`Succeeded in createSoundPool`)
1712    soundPool.on('error', (error: BusinessError) => {
1713      console.error('error happened,and error message is :' + error.message)
1714      console.error('error happened,and error code is :' + error.code)
1715    })
1716  }
1717});
1718
1719```
1720
1721### off('error')
1722
1723off(type: 'error'): void
1724
1725Unsubscribes from error events of this **SoundPool** instance.
1726
1727**System capability**: SystemCapability.Multimedia.Media.SoundPool
1728
1729**Parameters**
1730
1731| Name| Type  | Mandatory| Description                                     |
1732| ------ | ------ | ---- | ----------------------------------------- |
1733| type   | string | Yes  | Event type, which is **'error'** in this case.|
1734
1735**Example**
1736
1737```js
1738import { BusinessError } from '@kit.BasicServicesKit';
1739
1740// Create a SoundPool instance.
1741let soundPool: media.SoundPool;
1742let audioRendererInfo: audio.AudioRendererInfo = {
1743  usage: audio.StreamUsage.STREAM_USAGE_MUSIC,
1744  rendererFlags: 1
1745}
1746media.createSoundPool(5, audioRendererInfo, (error: BusinessError, soundPool_: media.SoundPool) => {
1747  if (error) {
1748    console.error(`Failed to createSoundPool`)
1749    return;
1750  } else {
1751    soundPool = soundPool_;
1752    console.info(`Succeeded in createSoundPool`)
1753    soundPool.off('error')
1754  }
1755});
1756```
1757