diff --git a/en/application-dev/media/audio-capturer.md b/en/application-dev/media/audio-capturer.md index 00ff76707d2e8d6a2d0ee7dee92fbe8ff92adc84..ab1664eb718591f8abdcd691f1b9ff37b2f97a14 100644 --- a/en/application-dev/media/audio-capturer.md +++ b/en/application-dev/media/audio-capturer.md @@ -1,152 +1,152 @@ # Audio Capture Development ---- -## ***Note***: - 1. This document applies to JavaScript. ---- -## **Summary** -This guide will show how a JS application can use AudioCapturer to record the audio. -Applications can use the APIs provided in this document to record raw audio files. - -## **AudioCapturer Framework** -The AudioCapturer interface is one of the most important components of the audio framework. -### **Audio Capturing:** -The AudioCapturer framework provides APIs for capturing raw audio files. - -## **Usage** -Here's an example of how to use AudioCapturer to capture a raw audio file. -1. Use **createAudioCapturer()** to create an AudioCapturer instance. Capturer parameters can be set in **audioCapturerOptions**.\ - This instance can be used to record, control, and obtain the recording status, as well as to register a callback for notifications. - ``` - 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 audioCapturerInfo = { - source: audio.SourceType.SOURCE_TYPE_MIC, - capturerFlags: 1 - } - - var audioCapturerOptions = { - streamInfo: audioStreamInfo, - capturerInfo: audioCapturerInfo - } - - let audioCapturer = await audio.createAudioCapturer(audioCapturerOptions); - var state = audioRenderer.state; - ``` +## When to Use + +You can use the APIs provided by **AudioCapturer** to record raw audio files. + +### State Check + +During application development, you are advised to use **on('stateChange')** to subscribe to state changes of the **AudioCapturer** instance. This is because some operations can be performed only when the audio capturer is in a given state. If the application performs an operation when the audio capturer is not in the given state, the system may throw an exception or generate other undefined behavior. + +For details about the APIs, see [AudioCapturer in Audio Management](../reference/apis/js-apis-audio.md). + +**Figure 1** Audio capturer state + +![](figures/audio-capturer-state.png) + +## How to Develop + +1. Use **createAudioCapturer()** to create an **AudioCapturer** instance. + + Set parameters of the **AudioCapturer** instance in **audioCapturerOptions**. This instance is used to capture audio, control and obtain the recording status, and register a callback for notification. -2. (Optional) Subscribe to audio capturer state change events using the **on('stateChange')** API. - If an application wants to take some action based on the state updates in capturer, the application can subscribe to the state change event. - There are more events that applications can subscribe to, such as 'markReach' and 'periodReach'. Refer to [Audio](../reference/apis/js-apis-audio.md) for more details. + ```js + 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 audioCapturerInfo = { + source: audio.SourceType.SOURCE_TYPE_MIC, + capturerFlags: 1 + } + + var audioCapturerOptions = { + streamInfo: audioStreamInfo, + capturerInfo: audioCapturerInfo + } + + let audioCapturer = await audio.createAudioCapturer(audioCapturerOptions); + var state = audioRenderer.state; ``` + +2. (Optional) Use **on('stateChange')** to subscribe to audio renderer state changes. +If an application needs to perform some operations when the audio renderer state is updated, the application can subscribe to the state changes. For more events that can be subscribed to, see [Audio Management](../reference/apis/js-apis-audio.md). + + ```js audioCapturer.on('stateChange',(state) => { console.info('AudioCapturerLog: Changed State to : ' + state) switch (state) { - case audio.AudioState.STATE_PREPARED: - console.info('--------CHANGE IN AUDIO STATE----------PREPARED--------------'); - console.info('Audio State is : Prepared'); - break; - case audio.AudioState.STATE_RUNNING: - console.info('--------CHANGE IN AUDIO STATE----------RUNNING--------------'); - console.info('Audio State is : Running'); - break; - case audio.AudioState.STATE_STOPPED: - console.info('--------CHANGE IN AUDIO STATE----------STOPPED--------------'); - console.info('Audio State is : stopped'); - break; - case audio.AudioState.STATE_RELEASED: - console.info('--------CHANGE IN AUDIO STATE----------RELEASED--------------'); - console.info('Audio State is : released'); - break; - default: - console.info('--------CHANGE IN AUDIO STATE----------INVALID--------------'); - console.info('Audio State is : invalid'); - break; - } + case audio.AudioState.STATE_PREPARED: + console.info('--------CHANGE IN AUDIO STATE----------PREPARED--------------'); + console.info('Audio State is : Prepared'); + break; + case audio.AudioState.STATE_RUNNING: + console.info('--------CHANGE IN AUDIO STATE----------RUNNING--------------'); + console.info('Audio State is : Running'); + break; + case audio.AudioState.STATE_STOPPED: + console.info('--------CHANGE IN AUDIO STATE----------STOPPED--------------'); + console.info('Audio State is : stopped'); + break; + case audio.AudioState.STATE_RELEASED: + console.info('--------CHANGE IN AUDIO STATE----------RELEASED--------------'); + console.info('Audio State is : released'); + break; + default: + console.info('--------CHANGE IN AUDIO STATE----------INVALID--------------'); + console.info('Audio State is : invalid'); + break; + } }); - ``` -3. Call the **start()** function on the AudioCapturer instance to start/resume the recording task.\ - The capturer state will be STATE_RUNNING once the start is complete. The application can then begin reading buffers. - ``` - await audioCapturer.start(); - if (audioCapturer.state == audio.AudioState.STATE_RUNNING) { - console.info('AudioRecLog: Capturer started'); - } else { - console.info('AudioRecLog: Capturer start failed'); - } +3. Use **start()** to start audio recording. - ``` + The capturer state will be **STATE_RUNNING** once the audio capturer is started. The application can then begin reading buffers. -4. Obtain the minimum buffer size to read using the **getBufferSize()** API. + ```js + await audioCapturer.start(); + if (audioCapturer.state == audio.AudioState.STATE_RUNNING) { + console.info('AudioRecLog: Capturer started'); + } else { + console.info('AudioRecLog: Capturer start failed'); + } ``` - var bufferSize = await audioCapturer.getBufferSize(); - console.info('AudioRecLog: buffer size: ' + bufferSize); - ``` +4. Use **getBufferSize()** to obtain the minimum buffer size to read. -5. Read the captured audio data and convert it to a byte stream. Call the **read()** API repeatedly to read the data - until the application wants to stop the recording. The following example shows how to write recorded data into a file. + ```js + var bufferSize = await audioCapturer.getBufferSize(); + console.info('AudioRecLog: buffer size: ' + bufferSize); ``` - import fileio from '@ohos.fileio'; - - const path = '/data/data/.pulse_dir/capture_js.wav'; - let fd = fileio.openSync(path, 0o102, 0o777); - if (fd !== null) { - console.info('AudioRecLog: file fd created'); - } - else{ - console.info('AudioRecLog: file fd create : FAILED'); - return; - } - - fd = fileio.openSync(path, 0o2002, 0o666); - if (fd !== null) { - console.info('AudioRecLog: file fd opened in append mode'); - } - - var numBuffersToCapture = 150; - while (numBuffersToCapture) { - var buffer = await audioCapturer.read(bufferSize, true); - if (typeof(buffer) == undefined) { - console.info('read buffer failed'); - } else { - var number = fileio.writeSync(fd, buffer); - console.info('AudioRecLog: data written: ' + number); - } - - numBuffersToCapture--; - } - ``` -6. Once the recording is complete, call the **stop()** API on the AudioCapturer instance to stop the recording. - ``` - await audioCapturer.stop(); - if (audioCapturer.state == audio.AudioState.STATE_STOPPED) { - console.info('AudioRecLog: Capturer stopped'); - } else { - console.info('AudioRecLog: Capturer stop failed'); - } + +5. Read the captured audio data and convert it to a byte stream. Call **read()** repeatedly to read the data until the application wants to stop the recording. + + The following example shows how to write recorded data into a file. + + ```js + import fileio from '@ohos.fileio'; + + const path = '/data/data/.pulse_dir/capture_js.wav'; + let fd = fileio.openSync(path, 0o102, 0o777); + if (fd !== null) { + console.info('AudioRecLog: file fd created'); + } + else{ + console.info('AudioRecLog: file fd create : FAILED'); + return; + } + + fd = fileio.openSync(path, 0o2002, 0o666); + if (fd !== null) { + console.info('AudioRecLog: file fd opened in append mode'); + } + + var numBuffersToCapture = 150; + while (numBuffersToCapture) { + var buffer = await audioCapturer.read(bufferSize, true); + if (typeof(buffer) == undefined) { + console.info('read buffer failed'); + } else { + var number = fileio.writeSync(fd, buffer); + console.info('AudioRecLog: data written: ' + number); + } + + numBuffersToCapture--; + } ``` -7. After the recording task is complete, call the **release()** API on the AudioCapturer instance to release the stream resources. +6. Once the recording is complete, call **stop()** to stop the recording. + ``` - await audioCapturer.release(); - if (audioCapturer.state == audio.AudioState.STATE_RELEASED) { - console.info('AudioRecLog: Capturer released'); - } else { - console.info('AudioRecLog: Capturer release failed'); - } + await audioCapturer.stop(); + if (audioCapturer.state == audio.AudioState.STATE_STOPPED) { + console.info('AudioRecLog: Capturer stopped'); + } else { + console.info('AudioRecLog: Capturer stop failed'); + } ``` -## **Importance of State Check** -Application developers should keep in mind that an AudioCapturer is state-based. -That is, the AudioCapturer has an internal state that the application must always check when calling recorder control APIs, because some operations are only acceptable while the capturer is in a given state.\ -The system may throw an error/exception or generate other undefined behaviour if the application performs an operation while capturer is in an improper state. +7. After the task is complete, call **release()** to release related resources. -## **Other APIs** -See [AudioCapturer in the Audio API](../reference/apis/js-apis-audio.md) for more useful APIs like **getAudioTime**, **getCapturerInfo** and **getStreamInfo**. + ```js + await audioCapturer.release(); + if (audioCapturer.state == audio.AudioState.STATE_RELEASED) { + console.info('AudioRecLog: Capturer released'); + } else { + console.info('AudioRecLog: Capturer release failed'); + } + ``` diff --git a/en/application-dev/media/audio-renderer.md b/en/application-dev/media/audio-renderer.md index f9dfb75c2a08d6c8d641bbe0c8e7960efc6bc6ee..8e2be849396373aaa68ee7c4eb5e36a4cad28c1c 100644 --- a/en/application-dev/media/audio-renderer.md +++ b/en/application-dev/media/audio-renderer.md @@ -1,152 +1,124 @@ # Audio Rendering Development ---- -## ***Note***: - 1. This document applies to JavaScript. ---- -## **Summary** -This guide will show you how to use AudioRenderer to create an audio player app. -You can use the APIs provided in this document to play audio files in output devices and manage playback tasks. +## When to Use -## **AudioRenderer Framework** -The AudioRenderer interface is one of the most important components of the audio framework. -### **Audio Rendering:** -The AudioRenderer framework provides APIs for playing audio files and controlling the playback. -### **Audio Interruption:** -When a higher priority stream wants to play, the AudioRenderer framework interrupts the lower priority stream.\ -For example, if a call is arrived when you listen to music, the music playback, which is the lower priority stream, is paused.\ -With the sample code below, we'll look at how AudioInterrupt works in detail.\ -
-Please see [AudioRenderer in the Audio API](../reference/apis/js-apis-audio.md#audiorenderer8) for a list of supported audio stream types and formats, such as AudioSampleFormat, AudioChannel, AudioSampleFormat, and AudioEncodingType. +**AudioRenderer** provides APIs for rendering audio files and controlling playback. It also supports audio interruption. You can use the APIs provided by **AudioRenderer** to play audio files in output devices and manage playback tasks. +### Audio Interruption -## **Usage** -Here's an example of how to use AudioRenderer to play a raw audio file. -1. Use **createAudioRenderer** to create an AudioRenderer instance. Renderer parameters can be set in **audioRendererOptions**.\ - This object can be used to play, control, and obtain the status of the playback, as well as receive callback notifications. - ``` +When an audio stream with a higher priority needs to be played, the audio renderer interrupts the stream with a lower priority. For example, if a call comes in when the user is listening to music, the music playback, which is the lower priority stream, is paused. For details, see [How to Develop](#how-to-develop). + +### State Check + +During application development, you are advised to use **on('stateChange')** to subscribe to state changes of the **AudioRenderer** instance. This is because some operations can be performed only when the audio renderer is in a given state. If the application performs an operation when the audio renderer is not in the given state, the system may throw an exception or generate other undefined behavior. + +**Figure 1** Audio renderer state + +![](figures/audio-renderer-state.png) + +### Asynchronous Operations + +To ensure that the UI thread is not blocked, most **AudioRenderer** calls are asynchronous. Each API provides the callback and promise functions. The following examples use the promise functions. For more information, see [AudioRenderer in Audio Management](../reference/apis/js-apis-audio.md#audiorenderer8). + + + +## How to Develop + +1. Use **createAudioRenderer()** to create an **AudioRenderer** instance. + Set parameters of the audio renderer in **audioCapturerOptions**. This instance is used to render audio, control and obtain the rendering status, and register a callback for notification. + + ```js var audioStreamInfo = { samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, + 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 } - + let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); ``` -2. Subscribe to audio interruption events using the **on** API.\ - Stream-A is interrupted when Stream-B with a higher or equal priority requests to become active and use the output device.\ - In some cases, the framework takes forced actions like pausing and ducking, and notifies the app using **InterruptEvent**. In other cases, the app can take action. In this situation, the app can choose to act on the **InterruptEvent** or ignore it. When the app is interrupted by forced action, it should handle the state, update the user interface, and so on. - - In case of audio interrupts, the app may encounter write failures. Interrupt unaware apps can check the renderer state using the **audioRenderer.state** API before writing audio data, whereas interrupt aware apps will have more details accessible via this listener.\ -
- The following information will be provided by the Interrupt Event Notification: - - 1) **eventType:** Whether the interruption has begun or ended. - - | Value | Description | - | :------------------- | :-------------------------------------------- | - | INTERRUPT_TYPE_BEGIN | Indicates that the interruption has started. | - | INTERRUPT_TYPE_END | Indicates that the interruption has finished. | - - 2) **forceType:** Whether the framework has already taken action or if the app is being suggested to take action. - - | Value | Description | - | :-------------- | :------------------------------------------------------------------ | - | INTERRUPT_FORCE | The audio state has been changed by the framework. | - | INTERRUPT_SHARE | The app can decide whether or not to respond to the InterruptEvent. | - - 3) **hintType:** The kind of action taken or to be taken. - - | Value | Description | - | :-------------------- | :--------------------------- | - | INTERRUPT_HINT_PAUSE | Pausing the playback. | - | INTERRUPT_HINT_RESUME | Resuming the playback. | - | INTERRUPT_HINT_STOP | Stopping the playback. | - | INTERRUPT_HINT_DUCK | Ducking the stream volume. | - | INTERRUPT_HINT_UNDUCK | Unducking the stream volume. | - - 4) **Some actions are exclusively forced or shared**, which means that they are performed by either the framework or the app.\ - For instance, when a call is received while a music stream is ongoing, the framework forces the music stream to pause. When the call is finished, the framework will not forcibly resume the music stream. Instead, it will alert the app to resume the playback. - - | Action | Description | - | :-------------------- | :-------------------------------------------------------------------------------- | - | INTERRUPT_HINT_RESUME | INTERRUPT_SHARE is always the forceType. It can only be done by the app. | - | INTERRUPT_HINT_DUCK | INTERRUPT_FORCE is always the forceType. It will always be done by the framework. | - | INTERRUPT_HINT_UNDUCK | INTERRUPT_FORCE is always the forceType. It will always be done by the framework. | - +2. Use **on('interrupt')** to subscribe to audio interruption events. + + Stream-A is interrupted when Stream-B with a higher or equal priority requests to become active and use the output device. + + In some cases, the audio renderer performs forcible operations such as pausing and ducking, and notifies the application through **InterruptEvent**. In other cases, the application can choose to act on the **InterruptEvent** or ignore it. + + In the case of audio interruption, the application may encounter write failures. To avoid such failures, interruption unaware applications can use **audioRenderer.state** to check the renderer state before writing audio data. The applications can obtain more details by subscribing to the audio interruption events. For details, see [InterruptEvent](../reference/apis/js-apis-audio.md#interruptevent9). + + ```js + audioRenderer.on('interrupt', (interruptEvent) => { + console.info('InterruptEvent Received'); + console.info('InterruptType: ' + interruptEvent.eventType); + console.info('InterruptForceType: ' + interruptEvent.forceType); + console.info('AInterruptHint: ' + interruptEvent.hintType); + + if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { + switch (interruptEvent.hintType) { + // Force Pause: Action was taken by framework. + // Halt the write calls to avoid data loss. + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + isPlay = false; + break; + // Force Stop: Action was taken by framework. + // Halt the write calls to avoid data loss. + case audio.InterruptHint.INTERRUPT_HINT_STOP: + isPlay = false; + break; + // Force Duck: Action was taken by framework, + // just notifying the app that volume has been reduced. + case audio.InterruptHint.INTERRUPT_HINT_DUCK: + break; + // Force Unduck: Action was taken by framework, + // just notifying the app that volume has been restored. + case audio.InterruptHint.INTERRUPT_HINT_UNDUCK: + break; + } + } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { + switch (interruptEvent.hintType) { + // Share Resume: Action is to be taken by App. + // Resume the force paused stream if required. + case audio.InterruptHint.INTERRUPT_HINT_RESUME: + startRenderer(); + break; + // Share Pause: Stream has been interrupted, + // It can choose to pause or play concurrently. + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + isPlay = false; + pauseRenderer(); + break; + } + } + }); ``` - audioRenderer.on('interrupt', (interruptEvent) => { - console.info('InterruptEvent Received'); - console.info('InterruptType: ' + interruptEvent.eventType); - console.info('InterruptForceType: ' + interruptEvent.forceType); - console.info('AInterruptHint: ' + interruptEvent.hintType); - if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { - switch (interruptEvent.hintType) { - // Force Pause: Action was taken by framework. - // Halt the write calls to avoid data loss. - case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - isPlay = false; - break; - // Force Stop: Action was taken by framework. - // Halt the write calls to avoid data loss. - case audio.InterruptHint.INTERRUPT_HINT_STOP: - isPlay = false; - break; - // Force Duck: Action was taken by framework, - // just notifying the app that volume has been reduced. - case audio.InterruptHint.INTERRUPT_HINT_DUCK: - break; - // Force Unduck: Action was taken by framework, - // just notifying the app that volume has been restored. - case audio.InterruptHint.INTERRUPT_HINT_UNDUCK: - break; - } - } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { - switch (interruptEvent.hintType) { - // Share Resume: Action is to be taken by App. - // Resume the force paused stream if required. - case audio.InterruptHint.INTERRUPT_HINT_RESUME: - startRenderer(); - break; - // Share Pause: Stream has been interrupted, - // It can choose to pause or play concurrently. - case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - isPlay = false; - pauseRenderer(); - break; - } - } - }); - ``` +3. Use **start()** to start audio rendering. + + The renderer state will be **STATE_RUNNING** once the audio renderer is started. The application can then begin reading buffers. -4. Call the **start()** function on the AudioRenderer instance to start/resume the playback task.\ - The renderer state will be STATE_RUNNING once the start is complete. You can then begin writing buffers. - ``` + ```js async function startRenderer() { var state = audioRenderer.state; - // state should be prepared, paused or stopped. + // The state should be prepared, paused, or stopped. if (state != audio.AudioState.STATE_PREPARED || state != audio.AudioState.STATE_PAUSED || state != audio.AudioState.STATE_STOPPED) { console.info('Renderer is not in a correct state to start'); return; } - + await audioRenderer.start(); - + state = audioRenderer.state; if (state == audio.AudioState.STATE_RUNNING) { console.info('Renderer started'); @@ -154,11 +126,13 @@ Here's an example of how to use AudioRenderer to play a raw audio file. console.error('Renderer start failed'); } } - - ``` -5. Make **write** calls to start rendering the buffers. - Read the audio data to be played into a buffer. Call the write function repeatedly to write data. ``` + +4. Call **write()** to write data to the buffer. + + Read the audio data to be played to the buffer. Call **write()** repeatedly to write the data to the buffer. + + ```js async function writeBuffer(buf) { var state = audioRenderer.state; if (state != audio.AudioState.STATE_RUNNING) { @@ -167,13 +141,13 @@ Here's an example of how to use AudioRenderer to play a raw audio file. return; } let writtenbytes = await audioRenderer.write(buf); - + console.info('Actual written bytes: ' + writtenbytes); if (writtenbytes < 0) { console.error('Write buffer failed. check the state of renderer'); } } - + // Reasonable minimum buffer size for renderer. However, the renderer can accept other read sizes as well. const bufferSize = await audioRenderer.getBufferSize(); const path = '/data/file_example_WAV_2MG.wav'; @@ -183,7 +157,7 @@ Here's an example of how to use AudioRenderer to play a raw audio file. let discardHeader = new ArrayBuffer(44); ss.readSync(discardHeader); rlen += 44; - + var id = setInterval(() => { if (isPlay || isRelease) { if (rlen >= totalSize || isRelease) { @@ -201,74 +175,65 @@ Here's an example of how to use AudioRenderer to play a raw audio file. } , 30); // interval to be set based on audio file format ``` -6. (Optional) Call the **pause()** or **stop()** function on the AudioRenderer instance. -``` - async function pauseRenderer() { - var state = audioRenderer.state; - if (state != audio.AudioState.STATE_RUNNING) { - console.info('Renderer is not running'); - return; - } - - await audioRenderer.pause(); - - state = audioRenderer.state; - if (state == audio.AudioState.STATE_PAUSED) { - console.info('Renderer paused'); - } else { - console.error('Renderer pause failed'); - } - } - - async function stopRenderer() { - var state = audioRenderer.state; - if (state != audio.AudioState.STATE_RUNNING || state != audio.AudioState.STATE_PAUSED) { - console.info('Renderer is not running or paused'); - return; - } - - await audioRenderer.stop(); - - state = audioRenderer.state; - if (state == audio.AudioState.STATE_STOPPED) { - console.info('Renderer stopped'); - } else { - console.error('Renderer stop failed'); - } -} -``` - -7. After the playback task is complete, call the **release()** function on the AudioRenderer instance to release resources.\ - AudioRenderer can use a lot of system resources. As a result, whenever the resources are no longer required, they must be released. To ensure that any system resources allocated to it are appropriately released, you should always call **release()**. -``` - async function releaseRenderer() { - if (state_ == RELEASED || state_ == NEW) { - console.info('Resourced already released'); - return; - } - - await audioRenderer.release(); - - state = audioRenderer.state; - if (state == STATE_RELEASED) { - console.info('Renderer released'); - } else { - console.info('Renderer release failed'); - } - - } -``` - -## **Importance of State Check:** -You should also keep in mind that an AudioRenderer is state-based. -That is, the AudioRenderer has an internal state that you must always check when calling playback control APIs, because some operations are only acceptable while the renderer is in a given state.\ -The system may throw an error/exception or generate other undefined behaviour if you perform an operation while in the improper state.\ +5. (Optional) Call **pause()** or **stop()** to pause or stop rendering. + + ```js + async function pauseRenderer() { + var state = audioRenderer.state; + if (state != audio.AudioState.STATE_RUNNING) { + console.info('Renderer is not running'); + return; + } + + await audioRenderer.pause(); + + state = audioRenderer.state; + if (state == audio.AudioState.STATE_PAUSED) { + console.info('Renderer paused'); + } else { + console.error('Renderer pause failed'); + } + } + + async function stopRenderer() { + var state = audioRenderer.state; + if (state != audio.AudioState.STATE_RUNNING || state != audio.AudioState.STATE_PAUSED) { + console.info('Renderer is not running or paused'); + return; + } + + await audioRenderer.stop(); + + state = audioRenderer.state; + if (state == audio.AudioState.STATE_STOPPED) { + console.info('Renderer stopped'); + } else { + console.error('Renderer stop failed'); + } + } + ``` -## **Asynchronous Operations:** -Most of the AudioRenderer calls are asynchronous. As a result, the UI thread will not be blocked.\ -For each API, the framework provides both callback and promises functions.\ -In the example, promise functions are used for simplicity. [AudioRender in the Audio API](../reference/apis/js-apis-audio.md#audiorenderer8) -provides reference for both callback and promise. +6. After the task is complete, call **release()** to release related resources. + + **AudioRenderer** uses a large number of system resources. Therefore, ensure that the resources are released after the task is complete. + + ```js + async function releaseRenderer() { + if (state_ == RELEASED || state_ == NEW) { + console.info('Resourced already released'); + return; + } + + await audioRenderer.release(); + + state = audioRenderer.state; + if (state == STATE_RELEASED) { + console.info('Renderer released'); + } else { + console.info('Renderer release failed'); + } + + } + ``` -## **Other APIs:** -See [Audio](../reference/apis/js-apis-audio.md) for more useful APIs like getAudioTime, drain, and getBufferSize. + diff --git a/en/application-dev/media/figures/audio-capturer-state.png b/en/application-dev/media/figures/audio-capturer-state.png new file mode 100644 index 0000000000000000000000000000000000000000..52b5556260dbf78c5e816b37013248a07e8dbbc6 Binary files /dev/null and b/en/application-dev/media/figures/audio-capturer-state.png differ diff --git a/en/application-dev/media/figures/audio-renderer-state.png b/en/application-dev/media/figures/audio-renderer-state.png new file mode 100644 index 0000000000000000000000000000000000000000..9ae30c2a9306dc85662405c36da9e11d07ed9a2a Binary files /dev/null and b/en/application-dev/media/figures/audio-renderer-state.png differ