diff --git a/en/OpenHarmony-Overview.md b/en/OpenHarmony-Overview.md
index 1331ac52206cf1980ce59a7def62bfd32c27e406..75dc8b66607121be43c3bcfa13398ecee5b76401 100644
--- a/en/OpenHarmony-Overview.md
+++ b/en/OpenHarmony-Overview.md
@@ -150,7 +150,7 @@ Currently, the OpenHarmony community supports 17 types of development boards, wh
| System Type| Board Model| Chip Model|
Function Description and Use Case
| Application Scenario| Code Repository |
| -------- | -------- | -------- | -------- | -------- | -------- |
-| Standard system| Runhe HH-SCDAYU200| RK3568 | Function description:
Bolstered by the Rockchip RK3568, the HH-SCDAYU200 development board integrates the dual-core GPU and efficient NPU. Its quad-core 64-bit Cortex-A55 processor uses the advanced 22 nm fabrication process and is clocked at up to 2.0 GHz. The board is packed with Bluetooth, Wi-Fi, audio, video, and camera features, with a wide range of expansion ports to accommodate various video input and outputs. It comes with dual GE auto-sensing RJ45 ports, so it can be used in multi-connectivity products, such as network video recorders (NVRs) and industrial gateways.
Use case:
[DAYU200 Use Case](device-dev/porting/porting-dayu200-on_standard-demo.md)
| Entertainment, easy travel, and smart home, such as kitchen hoods, ovens, and treadmills.| [device_soc_rockchip](https://gitee.com/openharmony/device_soc_rockchip)
[device_board_hihope](https://gitee.com/openharmony/device_board_hihope)
[vendor_hihope](https://gitee.com/openharmony/vendor_hihope)
|
+| Standard system| Runhe HH-SCDAYU200| RK3568 | Function description:
Bolstered by the Rockchip RK3568, the HH-SCDAYU200 development board integrates the dual-core GPU and efficient NPU. Its quad-core 64-bit Cortex-A55 processor uses the advanced 22 nm fabrication process and is clocked at up to 2.0 GHz. The board is packed with Bluetooth, Wi-Fi, audio, video, and camera features, with a wide range of expansion ports to accommodate various video input and outputs. It comes with dual GE auto-sensing RJ45 ports, so it can be used in multi-connectivity products, such as network video recorders (NVRs) and industrial gateways.
| Entertainment, easy travel, and smart home, such as kitchen hoods, ovens, and treadmills.| [device_soc_rockchip](https://gitee.com/openharmony/device_soc_rockchip)
[device_board_hihope](https://gitee.com/openharmony/device_board_hihope)
[vendor_hihope](https://gitee.com/openharmony/vendor_hihope)
|
| Small system| Hispark_Taurus | Hi3516DV300 | Function Description:
Hi3516D V300 is the next-generation system on chip (SoC) for smart HD IP cameras. It integrates the next-generation image signal processor (ISP), H.265 video compression encoder, and high-performance NNIE engine, and delivers high performance in terms of low bit rate, high image quality, intelligent processing and analysis, and low power consumption.
| Smart device with screens, such as refrigerators with screens and head units.| [device_soc_hisilicon](https://gitee.com/openharmony/device_soc_hisilicon)
[device_board_hisilicon](https://gitee.com/openharmony/device_board_hisilicon)
[vendor_hisilicon](https://gitee.com/openharmony/vendor_hisilicon)
|
| Mini system| Multi-modal V200Z-R | BES2600 | Function description:
The multi-modal V200Z-R development board is a high-performance, multi-functional, and cost-effective AIoT SoC powered by the BES2600WM chip of Bestechnic. It integrates a quad-core ARM processor with a frequency of up to 1 GHz as well as dual-mode Wi-Fi and dual-mode Bluetooth. The board supports the 802.11 a/b/g/n/ and BT/BLE 5.2 standards. It is able to accommodate RAM of up to 42 MB and flash memory of up to 32 MB, and supports the MIPI display serial interface (DSI) and camera serial interface (CSI). It is applicable to various AIoT multi-modal VUI and GUI interaction scenarios.
Use case:
[Multi-modal V200Z-R Use Case](device-dev/porting/porting-bes2600w-on-minisystem-display-demo.md)
| Smart hardware, and smart devices with screens, such as speakers and watches.| [device_soc_bestechnic](https://gitee.com/openharmony/device_soc_bestechnic)
[device_board_fnlink](https://gitee.com/openharmony/device_board_fnlink)
[vendor_bestechnic](https://gitee.com/openharmony/vendor_bestechnic)
|
diff --git a/en/application-dev/IDL/idl-guidelines.md b/en/application-dev/IDL/idl-guidelines.md
index 661b2532c49d36c79855c3e0530326ef590c7cd2..5b3a5d7990d4dfe55ddef2ad77ef7dab84033a2e 100644
--- a/en/application-dev/IDL/idl-guidelines.md
+++ b/en/application-dev/IDL/idl-guidelines.md
@@ -7,7 +7,7 @@ To ensure successful communications between the client and server, interfaces re
![IDL-interface-description](./figures/IDL-interface-description.png)
-IDL provides the following functions:
+**IDL provides the following functions:**
- Declares interfaces provided by system services for external systems, and based on the interface declaration, generates C, C++, JS, or TS code for inter-process communication (IPC) or remote procedure call (RPC) proxies and stubs during compilation.
@@ -17,7 +17,7 @@ IDL provides the following functions:
![IPC-RPC-communication-model](./figures/IPC-RPC-communication-model.png)
-IDL has the following advantages:
+**IDL has the following advantages:**
- Services are defined in the form of interfaces in IDL. Therefore, you do not need to focus on implementation details.
@@ -433,7 +433,7 @@ export default {
console.log('ServiceAbility want:' + JSON.stringify(want));
console.log('ServiceAbility want name:' + want.bundleName)
} catch(err) {
- console.log("ServiceAbility error:" + err)
+ console.log('ServiceAbility error:' + err)
}
console.info('ServiceAbility onConnect end');
return new IdlTestImp('connect');
@@ -455,13 +455,13 @@ import featureAbility from '@ohos.ability.featureAbility';
function callbackTestIntTransaction(result: number, ret: number): void {
if (result == 0 && ret == 124) {
- console.log("case 1 success ");
+ console.log('case 1 success');
}
}
function callbackTestStringTransaction(result: number): void {
if (result == 0) {
- console.log("case 2 success ");
+ console.log('case 2 success');
}
}
@@ -472,17 +472,17 @@ var onAbilityConnectDone = {
testProxy.testStringTransaction('hello', callbackTestStringTransaction);
},
onDisconnect:function (elementName) {
- console.log("onDisconnectService onDisconnect");
+ console.log('onDisconnectService onDisconnect');
},
onFailed:function (code) {
- console.log("onDisconnectService onFailed");
+ console.log('onDisconnectService onFailed');
}
};
function connectAbility: void {
let want = {
- "bundleName":"com.example.myapplicationidl",
- "abilityName": "com.example.myapplicationidl.ServiceAbility"
+ bundleName: 'com.example.myapplicationidl',
+ abilityName: 'com.example.myapplicationidl.ServiceAbility'
};
let connectionId = -1;
connectionId = featureAbility.connectAbility(want, onAbilityConnectDone);
@@ -495,7 +495,7 @@ function connectAbility: void {
You can send a class from one process to another through IPC interfaces. However, you must ensure that the peer can use the code of this class and this class supports the **marshalling** and **unmarshalling** methods. OpenHarmony uses **marshalling** and **unmarshalling** to serialize and deserialize objects into objects that can be identified by each process.
-To create a class that supports the sequenceable type, perform the following operations:
+**To create a class that supports the sequenceable type, perform the following operations:**
1. Implement the **marshalling** method, which obtains the current state of the object and serializes the object into a **Parcel** object.
2. Implement the **unmarshalling** method, which deserializes the object from a **Parcel** object.
@@ -595,7 +595,7 @@ export default class IdlTestServiceProxy implements IIdlTestService {
let _reply = new rpc.MessageParcel();
_data.writeInt(data);
this.proxy.sendRequest(IdlTestServiceProxy.COMMAND_TEST_INT_TRANSACTION, _data, _reply, _option).then(function(result) {
- if (result.errCode === 0) {
+ if (result.errCode == 0) {
let _errCode = result.reply.readInt();
if (_errCode != 0) {
let _returnValue = undefined;
@@ -605,7 +605,7 @@ export default class IdlTestServiceProxy implements IIdlTestService {
let _returnValue = result.reply.readInt();
callback(_errCode, _returnValue);
} else {
- console.log("sendRequest failed, errCode: " + result.errCode);
+ console.log('sendRequest failed, errCode: ' + result.errCode);
}
})
}
@@ -617,11 +617,11 @@ export default class IdlTestServiceProxy implements IIdlTestService {
let _reply = new rpc.MessageParcel();
_data.writeString(data);
this.proxy.sendRequest(IdlTestServiceProxy.COMMAND_TEST_STRING_TRANSACTION, _data, _reply, _option).then(function(result) {
- if (result.errCode === 0) {
+ if (result.errCode == 0) {
let _errCode = result.reply.readInt();
callback(_errCode);
} else {
- console.log("sendRequest failed, errCode: " + result.errCode);
+ console.log('sendRequest failed, errCode: ' + result.errCode);
}
})
}
@@ -644,12 +644,12 @@ import nativeMgr from 'nativeManager';
function testIntTransactionCallback(errCode: number, returnValue: number)
{
- console.log("errCode: " + errCode + " returnValue: " + returnValue);
+ console.log('errCode: ' + errCode + ' returnValue: ' + returnValue);
}
function testStringTransactionCallback(errCode: number)
{
- console.log("errCode: " + errCode);
+ console.log('errCode: ' + errCode);
}
function jsProxyTriggerCppStub()
@@ -660,6 +660,6 @@ function jsProxyTriggerCppStub()
tsProxy.testIntTransaction(10, testIntTransactionCallback);
// Call testStringTransaction.
- tsProxy.testStringTransaction("test", testIntTransactionCallback);
+ tsProxy.testStringTransaction('test', testIntTransactionCallback);
}
```
diff --git a/en/application-dev/Readme-EN.md b/en/application-dev/Readme-EN.md
index ca2c2fda1462b991f8ea60f36b5c181783034874..dba77cf37aab62a7bb4d33b367839a0c0c88bc4e 100644
--- a/en/application-dev/Readme-EN.md
+++ b/en/application-dev/Readme-EN.md
@@ -8,14 +8,13 @@
- Quick Start
- Getting Started
- [Preparations](quick-start/start-overview.md)
- - [Getting Started with eTS in Stage Model](quick-start/start-with-ets-stage.md)
- - [Getting Started with eTS in FA Model](quick-start/start-with-ets-fa.md)
+ - [Getting Started with ArkTS in Stage Model](quick-start/start-with-ets-stage.md)
+ - [Getting Started with ArkTS in FA Model](quick-start/start-with-ets-fa.md)
- [Getting Started with JavaScript in FA Model](quick-start/start-with-js-fa.md)
- Development Fundamentals
- [Application Package Structure Configuration File (FA Model)](quick-start/package-structure.md)
- [Application Package Structure Configuration File (Stage Model)](quick-start/stage-structure.md)
- [SysCap](quick-start/syscap.md)
- - [HarmonyAppProvision Configuration File](quick-start/app-provision-structure.md)
- Development
- [Ability Development](ability/Readme-EN.md)
diff --git a/en/application-dev/ability/Readme-EN.md b/en/application-dev/ability/Readme-EN.md
index 0589643e0f9426f76ac25d3616a41c3b54910e2a..6a11f497d375874b96bfed77a77dce033821d6e3 100644
--- a/en/application-dev/ability/Readme-EN.md
+++ b/en/application-dev/ability/Readme-EN.md
@@ -1,4 +1,5 @@
# Ability Development
+
- [Ability Framework Overview](ability-brief.md)
- [Context Usage](context-userguide.md)
- FA Model
@@ -19,5 +20,3 @@
- [Ability Assistant Usage](ability-assistant-guidelines.md)
- [ContinuationManager Development](continuationmanager.md)
- [Test Framework Usage](ability-delegator.md)
-
-
diff --git a/en/application-dev/ability/continuationmanager.md b/en/application-dev/ability/continuationmanager.md
index a1f5a66478cd53aeabe03ed9be21e08596cb2b6b..20c272e75a16c2bcf14d567c1cbc7afa28a3a69a 100644
--- a/en/application-dev/ability/continuationmanager.md
+++ b/en/application-dev/ability/continuationmanager.md
@@ -14,20 +14,20 @@ As the entry of the ability continuation capability, **continuationManager** is
## Available APIs
| API | Description|
| ---------------------------------------------------------------------------------------------- | ----------- |
-| register(callback: AsyncCallback\): void | Registers the continuation management service and obtains a token. This API does not involve any filter parameters and uses an asynchronous callback to return the result.|
-| register(options: ContinuationExtraParams, callback: AsyncCallback\): void | Registers the continuation management service and obtains a token. This API uses an asynchronous callback to return the result.|
-| register(options?: ContinuationExtraParams): Promise\ | Registers the continuation management service and obtains a token. This API uses a promise to return the result.|
-| on(type: "deviceConnect", token: number, callback: Callback\>): void | Subscribes to device connection events. This API uses an asynchronous callback to return the result.|
-| on(type: "deviceDisconnect", token: number, callback: Callback\>): void | Subscribes to device disconnection events. This API uses an asynchronous callback to return the result.|
-| off(type: "deviceConnect", token: number): void | Unsubscribes from device connection events.|
-| off(type: "deviceDisconnect", token: number): void | Unsubscribes from device disconnection events.|
-| startDeviceManager(token: number, callback: AsyncCallback\): void | Starts the device selection module to show the list of available devices. This API does not involve any filter parameters and uses an asynchronous callback to return the result.|
-| startDeviceManager(token: number, options: ContinuationExtraParams, callback: AsyncCallback\): void | Starts the device selection module to show the list of available devices. This API uses an asynchronous callback to return the result.|
-| startDeviceManager(token: number, options?: ContinuationExtraParams): Promise\ | Starts the device selection module to show the list of available devices. This API uses a promise to return the result.|
-| updateConnectStatus(token: number, deviceId: string, status: DeviceConnectState, callback: AsyncCallback\): void | Instructs the device selection module to update the device connection state. This API uses an asynchronous callback to return the result.|
-| updateConnectStatus(token: number, deviceId: string, status: DeviceConnectState): Promise\ | Instructs the device selection module to update the device connection state. This API uses a promise to return the result.|
-| unregister(token: number, callback: AsyncCallback\): void | Deregisters the continuation management service. This API uses an asynchronous callback to return the result.|
-| unregister(token: number): Promise\ | Deregisters the continuation management service. This API uses a promise to return the result.|
+| registerContinuation(callback: AsyncCallback\): void | Registers the continuation management service and obtains a token. This API does not involve any filter parameters and uses an asynchronous callback to return the result.|
+| registerContinuation(options: ContinuationExtraParams, callback: AsyncCallback\): void | Registers the continuation management service and obtains a token. This API uses an asynchronous callback to return the result.|
+| registerContinuation(options?: ContinuationExtraParams): Promise\ | Registers the continuation management service and obtains a token. This API uses a promise to return the result.|
+| on(type: "deviceSelected", token: number, callback: Callback\>): void | Subscribes to device connection events. This API uses an asynchronous callback to return the result.|
+| on(type: "deviceUnselected", token: number, callback: Callback\>): void | Subscribes to device disconnection events. This API uses an asynchronous callback to return the result.|
+| off(type: "deviceSelected", token: number): void | Unsubscribes from device connection events.|
+| off(type: "deviceUnselected", token: number): void | Unsubscribes from device disconnection events.|
+| startContinuationDeviceManager(token: number, callback: AsyncCallback\): void | Starts the device selection module to show the list of available devices. This API does not involve any filter parameters and uses an asynchronous callback to return the result.|
+| startContinuationDeviceManager(token: number, options: ContinuationExtraParams, callback: AsyncCallback\): void | Starts the device selection module to show the list of available devices. This API uses an asynchronous callback to return the result.|
+| startContinuationDeviceManager(token: number, options?: ContinuationExtraParams): Promise\ | Starts the device selection module to show the list of available devices. This API uses a promise to return the result.|
+| updateContinuationState(token: number, deviceId: string, status: DeviceConnectState, callback: AsyncCallback\): void | Instructs the device selection module to update the device connection state. This API uses an asynchronous callback to return the result.|
+| updateContinuationState(token: number, deviceId: string, status: DeviceConnectState): Promise\ | Instructs the device selection module to update the device connection state. This API uses a promise to return the result.|
+| unregisterContinuation(token: number, callback: AsyncCallback\): void | Deregisters the continuation management service. This API uses an asynchronous callback to return the result.|
+| unregisterContinuation(token: number): Promise\ | Deregisters the continuation management service. This API uses a promise to return the result.|
## How to Develop
1. Import the **continuationManager** module.
@@ -36,7 +36,7 @@ As the entry of the ability continuation capability, **continuationManager** is
import continuationManager from '@ohos.continuation.continuationManager';
```
-2. Apply for permissions required for cross-device continuation or collaboration operations.
+2. Apply for the **DISTRIBUTED_DATASYNC** permission.
The permission application operation varies according to the ability model in use. In the FA mode, add the required permission in the `config.json` file, as follows:
@@ -57,6 +57,7 @@ As the entry of the ability continuation capability, **continuationManager** is
```ts
import abilityAccessCtrl from "@ohos.abilityAccessCtrl";
import bundle from '@ohos.bundle';
+ import featureAbility from '@ohos.ability.featureAbility';
async function requestPermission() {
let permissions: Array = [
@@ -124,7 +125,8 @@ As the entry of the ability continuation capability, **continuationManager** is
// If the permission is not granted, call requestPermissionsFromUser to apply for the permission.
if (needGrantPermission) {
try {
- await globalThis.abilityContext.requestPermissionsFromUser(permissions);
+ // globalThis.context is Ability.context, which must be assigned a value in the MainAbility.ts file in advance.
+ await globalThis.context.requestPermissionsFromUser(permissions);
} catch (err) {
console.error('app permission request permissions error' + JSON.stringify(err));
}
@@ -140,13 +142,16 @@ As the entry of the ability continuation capability, **continuationManager** is
```ts
let token: number = -1; // Used to save the token returned after the registration. The token will be used when listening for device connection/disconnection events, starting the device selection module, and updating the device connection state.
-
- continuationManager.register().then((data) => {
- console.info('register finished, ' + JSON.stringify(data));
- token = data; // Obtain a token and assign a value to the token variable.
- }).catch((err) => {
- console.error('register failed, cause: ' + JSON.stringify(err));
- });
+ try {
+ continuationManager.registerContinuation().then((data) => {
+ console.info('registerContinuation finished, ' + JSON.stringify(data));
+ token = data; // Obtain a token and assign a value to the token variable.
+ }).catch((err) => {
+ console.error('registerContinuation failed, cause: ' + JSON.stringify(err));
+ });
+ } catch (err) {
+ console.error('registerContinuation failed, cause: ' + JSON.stringify(err));
+ }
```
4. Listen for the device connection/disconnection state.
@@ -156,28 +161,31 @@ As the entry of the ability continuation capability, **continuationManager** is
```ts
let remoteDeviceId: string = ""; // Used to save the information about the remote device selected by the user, which will be used for cross-device continuation or collaboration.
- // The token parameter is the token obtained during the registration.
- continuationManager.on("deviceConnect", token, (continuationResults) => {
- console.info('registerDeviceConnectCallback len: ' + continuationResults.length);
- if (continuationResults.length <= 0) {
- console.info('no selected device');
- return;
- }
- remoteDeviceId = continuationResults[0].id; // Assign the deviceId of the first selected remote device to the remoteDeviceId variable.
-
- // Pass the remoteDeviceId parameter to want.
- let want = {
- deviceId: remoteDeviceId,
- bundleName: 'ohos.samples.continuationmanager',
- abilityName: 'MainAbility'
- };
- // To initiate multi-device collaboration, you must obtain the ohos.permission.DISTRIBUTED_DATASYNC permission.
- globalThis.abilityContext.startAbility(want).then((data) => {
- console.info('StartRemoteAbility finished, ' + JSON.stringify(data));
- }).catch((err) => {
- console.error('StartRemoteAbility failed, cause: ' + JSON.stringify(err));
+ try {
+ // The token parameter is the token obtained during the registration.
+ continuationManager.on("deviceSelected", token, (continuationResults) => {
+ console.info('registerDeviceSelectedCallback len: ' + continuationResults.length);
+ if (continuationResults.length <= 0) {
+ console.info('no selected device');
+ return;
+ }
+ remoteDeviceId = continuationResults[0].id; // Assign the deviceId of the first selected remote device to the remoteDeviceId variable.
+
+ // Pass the remoteDeviceId parameter to want.
+ let want = {
+ deviceId: remoteDeviceId,
+ bundleName: 'ohos.samples.continuationmanager',
+ abilityName: 'MainAbility'
+ };
+ globalThis.abilityContext.startAbility(want).then((data) => {
+ console.info('StartRemoteAbility finished, ' + JSON.stringify(data));
+ }).catch((err) => {
+ console.error('StartRemoteAbility failed, cause: ' + JSON.stringify(err));
+ });
});
- });
+ } catch (err) {
+ console.error('on failed, cause: ' + JSON.stringify(err));
+ }
```
The preceding multi-device collaboration operation is performed across devices in the stage model. For details about this operation in the FA model, see [Page Ability Development](https://gitee.com/openharmony/docs/blob/master/en/application-dev/ability/fa-pageability.md).
@@ -189,35 +197,43 @@ As the entry of the ability continuation capability, **continuationManager** is
let deviceConnectStatus: continuationManager.DeviceConnectState = continuationManager.DeviceConnectState.CONNECTED;
// The token parameter is the token obtained during the registration, and the remoteDeviceId parameter is the remoteDeviceId obtained.
- continuationManager.updateConnectStatus(token, remoteDeviceId, deviceConnectStatus).then((data) => {
- console.info('updateConnectStatus finished, ' + JSON.stringify(data));
- }).catch((err) => {
- console.error('updateConnectStatus failed, cause: ' + JSON.stringify(err));
- });
+ try {
+ continuationManager.updateContinuationState(token, remoteDeviceId, deviceConnectStatus).then((data) => {
+ console.info('updateContinuationState finished, ' + JSON.stringify(data));
+ }).catch((err) => {
+ console.error('updateContinuationState failed, cause: ' + JSON.stringify(err));
+ });
+ } catch (err) {
+ console.error('updateContinuationState failed, cause: ' + JSON.stringify(err));
+ }
```
Listen for the device disconnection state so that the user can stop cross-device continuation or collaboration in time. The sample code is as follows:
```ts
- // The token parameter is the token obtained during the registration.
- continuationManager.on("deviceDisconnect", token, (deviceIds) => {
- console.info('onDeviceDisconnect len: ' + deviceIds.length);
- if (deviceIds.length <= 0) {
- console.info('no unselected device');
- return;
- }
+ try {
+ // The token parameter is the token obtained during the registration.
+ continuationManager.on("deviceUnselected", token, (continuationResults) => {
+ console.info('onDeviceUnselected len: ' + continuationResults.length);
+ if (continuationResults.length <= 0) {
+ console.info('no unselected device');
+ return;
+ }
- // Update the device connection state.
- let unselectedDeviceId: string = deviceIds[0]; // Assign the deviceId of the first deselected remote device to the unselectedDeviceId variable.
- let deviceConnectStatus: continuationManager.DeviceConnectState = continuationManager.DeviceConnectState.DISCONNECTING; // Device disconnected.
+ // Update the device connection state.
+ let unselectedDeviceId: string = continuationResults[0].id; // Assign the deviceId of the first deselected remote device to the unselectedDeviceId variable.
+ let deviceConnectStatus: continuationManager.DeviceConnectState = continuationManager.DeviceConnectState.DISCONNECTING; // Device disconnected.
- // The token parameter is the token obtained during the registration, and the unselectedDeviceId parameter is the unselectedDeviceId obtained.
- continuationManager.updateConnectStatus(token, unselectedDeviceId, deviceConnectStatus).then((data) => {
- console.info('updateConnectStatus finished, ' + JSON.stringify(data));
- }).catch((err) => {
- console.error('updateConnectStatus failed, cause: ' + JSON.stringify(err));
+ // The token parameter is the token obtained during the registration, and the unselectedDeviceId parameter is the unselectedDeviceId obtained.
+ continuationManager.updateContinuationState(token, unselectedDeviceId, deviceConnectStatus).then((data) => {
+ console.info('updateContinuationState finished, ' + JSON.stringify(data));
+ }).catch((err) => {
+ console.error('updateContinuationState failed, cause: ' + JSON.stringify(err));
+ });
});
- });
+ } catch (err) {
+ console.error('updateContinuationState failed, cause: ' + JSON.stringify(err));
+ }
```
5. Start the device selection module to show the list of available devices on the network.
@@ -231,12 +247,16 @@ As the entry of the ability continuation capability, **continuationManager** is
continuationMode: continuationManager.ContinuationMode.COLLABORATION_SINGLE // Single-choice mode of the device selection module.
};
- // The token parameter is the token obtained during the registration.
- continuationManager.startDeviceManager(token, continuationExtraParams).then((data) => {
- console.info('startDeviceManager finished, ' + JSON.stringify(data));
- }).catch((err) => {
- console.error('startDeviceManager failed, cause: ' + JSON.stringify(err));
- });
+ try {
+ // The token parameter is the token obtained during the registration.
+ continuationManager.startContinuationDeviceManager(token, continuationExtraParams).then((data) => {
+ console.info('startContinuationDeviceManager finished, ' + JSON.stringify(data));
+ }).catch((err) => {
+ console.error('startContinuationDeviceManager failed, cause: ' + JSON.stringify(err));
+ });
+ } catch (err) {
+ console.error('startContinuationDeviceManager failed, cause: ' + JSON.stringify(err));
+ }
```
6. If you do not need to perform cross-device migration or collaboration operations, you can deregister the continuation management service, by passing the token obtained during the registration.
@@ -244,10 +264,14 @@ As the entry of the ability continuation capability, **continuationManager** is
The sample code is as follows:
```ts
- // The token parameter is the token obtained during the registration.
- continuationManager.unregister(token).then((data) => {
- console.info('unregister finished, ' + JSON.stringify(data));
- }).catch((err) => {
- console.error('unregister failed, cause: ' + JSON.stringify(err));
- });
+ try {
+ // The token parameter is the token obtained during the registration.
+ continuationManager.unregisterContinuation(token).then((data) => {
+ console.info('unregisterContinuation finished, ' + JSON.stringify(data));
+ }).catch((err) => {
+ console.error('unregisterContinuation failed, cause: ' + JSON.stringify(err));
+ });
+ } catch (err) {
+ console.error('unregisterContinuation failed, cause: ' + JSON.stringify(err));
+ }
```
diff --git a/en/application-dev/ability/fa-pageability.md b/en/application-dev/ability/fa-pageability.md
index 3a2629a79996660f48dfc247b9a560ea1abe09b4..f6eb70595322d3f3308c00afcc9a5907ff87054f 100644
--- a/en/application-dev/ability/fa-pageability.md
+++ b/en/application-dev/ability/fa-pageability.md
@@ -1,12 +1,16 @@
# Page Ability Development
## Overview
+
### Concepts
-The Page ability implements the ArkUI and provides the capability of interacting with developers. When you create an ability in DevEco Studio, DevEco Studio automatically creates template code. The capabilities related to the Page ability are implemented through the **featureAbility**, and the lifecycle callbacks are implemented through the callbacks in **app.js** or **app.ets**.
+
+The Page ability implements the ArkUI and provides the capability of interacting with developers. When you create an ability in DevEco Studio, DevEco Studio automatically creates template code.
+
+The capabilities related to the Page ability are implemented through the **featureAbility**, and the lifecycle callbacks are implemented through the callbacks in **app.js** or **app.ets**.
### Page Ability Lifecycle
-**Ability lifecycle**
+Introduction to the Page ability lifecycle:
The Page ability lifecycle defines all states of a Page ability, such as **INACTIVE**, **ACTIVE**, and **BACKGROUND**.
@@ -27,27 +31,30 @@ Description of ability lifecycle states:
- **BACKGROUND**: The Page ability runs in the background. After being re-activated, the Page ability enters the **ACTIVE** state. After being destroyed, the Page ability enters the **INITIAL** state.
-**The following figure shows the relationship between lifecycle callbacks and lifecycle states of the Page ability.**
+The following figure shows the relationship between lifecycle callbacks and lifecycle states of the Page ability.
![fa-pageAbility-lifecycle](figures/fa-pageAbility-lifecycle.png)
You can override the lifecycle callbacks provided by the Page ability in the **app.js** or **app.ets** file. Currently, the **app.js** file provides only the **onCreate** and **onDestroy** callbacks, and the **app.ets** file provides the full lifecycle callbacks.
### Launch Type
+
The ability supports two launch types: singleton and multi-instance.
+
You can specify the launch type by setting **launchType** in the **config.json** file.
-**Table 1** Introduction to startup mode
+**Table 1** Startup modes
| Launch Type | Description |Description |
| ----------- | ------- |---------------- |
| standard | Multi-instance | A new instance is started each time an ability starts.|
-| singleton | Singleton | Only one instance exists in the system. If an instance already exists when an ability is started, that instance is reused.|
+| singleton | Singleton | The ability has only one instance in the system. If an instance already exists when an ability is started, that instance is reused.|
By default, **singleton** is used.
## Development Guidelines
+
### Available APIs
**Table 2** APIs provided by featureAbility
@@ -73,23 +80,21 @@ By default, **singleton** is used.
```javascript
import featureAbility from '@ohos.ability.featureAbility'
featureAbility.startAbility({
- want:
- {
- action: "",
- entities: [""],
- type: "",
- deviceId: "",
- bundleName: "com.example.myapplication",
- /* In the FA model, abilityName consists of package and ability name. */
- abilityName: "com.example.entry.secondAbility",
- uri: ""
- },
- },
- );
+ want: {
+ action: "",
+ entities: [""],
+ type: "",
+ deviceId: "",
+ bundleName: "com.example.myapplication",
+ /* In the FA model, abilityName consists of package and ability name. */
+ abilityName: "com.example.entry.secondAbility",
+ uri: ""
+ }
+ });
```
### Starting a Remote Page Ability
->Note
+>NOTE
>
>This feature applies only to system applications, since the **getTrustedDeviceListSync** API of the **DeviceManager** class is open only to system applications.
diff --git a/en/application-dev/device/device-location-info.md b/en/application-dev/device/device-location-info.md
index f3572352e718bb77493d7dd2d097d2d7a82058c9..a153f69fbfe2b71362a4b7e5808fe57c1b7a4216 100644
--- a/en/application-dev/device/device-location-info.md
+++ b/en/application-dev/device/device-location-info.md
@@ -66,7 +66,7 @@ To learn more about the APIs for obtaining device location information, see [Geo
If your application needs to access the device location information when running on the background, it must be configured to be able to run on the background and be granted the **ohos.permission.LOCATION_IN_BACKGROUND** permission. In this way, the system continues to report device location information after your application moves to the background.
- You can declare the required permission in your application's configuration file. For details, see [Application Package Structure Configuration File](../quick-start/stage-structure.md).
+ You can declare the required permission in your application's configuration file. For details, see [Access Control (Permission) Development](../security/accesstoken-guidelines.md).
2. Import the **geolocation** module by which you can implement all APIs related to the basic location capabilities.
diff --git a/en/application-dev/media/Readme-EN.md b/en/application-dev/media/Readme-EN.md
index 5f6e88fc07c88d3e5913058a26887e818a3cc3bc..07f3425ff5ab3c10beeac312740ff6e756c3cd85 100755
--- a/en/application-dev/media/Readme-EN.md
+++ b/en/application-dev/media/Readme-EN.md
@@ -1,23 +1,24 @@
# Media
-- Audio
- - [Audio Overview](audio-overview.md)
- - [Audio Playback Development](audio-playback.md)
- - [Audio Recording Development](audio-recorder.md)
- - [Audio Rendering Development](audio-renderer.md)
- - [Audio Stream Management Development](audio-stream-manager.md)
- - [Audio Capture Development](audio-capturer.md)
- - [OpenSL ES Audio Playback Development](opensles-playback.md)
- - [OpenSL ES Audio Recording Development](opensles-capture.md)
- - [Audio Interruption Mode Development](audio-interruptmode.md)
-
-- Video
- - [Video Playback Development](video-playback.md)
- - [Video Recording Development](video-recorder.md)
-
-- Image
+- Audio
+ - [Audio Overview](audio-overview.md)
+ - [Audio Playback Development](audio-playback.md)
+ - [Audio Recording Development](audio-recorder.md)
+ - [Audio Rendering Development](audio-renderer.md)
+ - [Audio Stream Management Development](audio-stream-manager.md)
+ - [Audio Capture Development](audio-capturer.md)
+ - [OpenSL ES Audio Playback Development](opensles-playback.md)
+ - [OpenSL ES Audio Recording Development](opensles-capture.md)
+ - [Audio Interruption Mode Development](audio-interruptmode.md)
+
+- Video
+ - [Video Playback Development](video-playback.md)
+ - [Video Recording Development](video-recorder.md)
+
+
+- Image
- [Image Development](image.md)
-
-- Camera
- - [Camera Development](camera.md)
- - [Distributed Camera Development](remote-camera.md)
+
+- Camera
+ - [Camera Development](camera.md)
+ - [Distributed Camera Development](remote-camera.md)
diff --git a/en/application-dev/media/audio-capturer.md b/en/application-dev/media/audio-capturer.md
index 0815ef31a288440271a27a8f03fb417923a46190..539de6bb5c5a0723aa68a8994f7ee1970f393a3f 100644
--- a/en/application-dev/media/audio-capturer.md
+++ b/en/application-dev/media/audio-capturer.md
@@ -1,106 +1,101 @@
# Audio Capture Development
-## When to Use
+## Introduction
-You can use the APIs provided by **AudioCapturer** to record raw audio files.
+You can use the APIs provided by **AudioCapturer** to record raw audio files, thereby implementing audio data collection.
-### State Check
+**Status 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.
-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.
+## Working Principles
-For details about the APIs, see [AudioCapturer in Audio Management](../reference/apis/js-apis-audio.md#audiocapturer8).
+This following figure shows the audio capturer state transitions.
+
+**Figure 1** Audio capturer state transitions
+
+![audio-capturer-state](figures/audio-capturer-state.png)
+
+- **PREPARED**: The audio capturer enters this state by calling **create()**.
+- **RUNNING**: The audio capturer enters this state by calling **start()** when it is in the **PREPARED** state or by calling **start()** when it is in the **STOPPED** state.
+- **STOPPED**: The audio capturer in the **RUNNING** state can call **stop()** to stop playing audio data.
+- **RELEASED**: The audio capturer in the **PREPARED** or **STOPPED** state can use **release()** to release all occupied hardware and software resources. It will not transit to any other state after it enters the **RELEASED** state.
-**Figure 1** Audio capturer state
+## Constraints
-![](figures/audio-capturer-state.png)
+Before developing the audio data collection feature, configure the **ohos.permission.MICROPHONE** permission for your application. For details about permission configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md).
## How to Develop
+For details about the APIs, see [AudioCapturer in Audio Management](../reference/apis/js-apis-audio.md#audiocapturer8).
+
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.
+ Set parameters of the **AudioCapturer** instance in **audioCapturerOptions**. This instance is used to capture audio, control and obtain the recording state, 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,
- 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).
+ import audio from '@ohos.multimedia.audio';
- ```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;
- }
- });
+ let audioStreamInfo = {
+ samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
+ channels: audio.AudioChannel.CHANNEL_1,
+ sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
+ encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
+ }
+
+ let audioCapturerInfo = {
+ source: audio.SourceType.SOURCE_TYPE_MIC,
+ capturerFlags: 0 // 0 is the extended flag bit of the audio capturer. The default value is 0.
+ }
+
+ let audioCapturerOptions = {
+ streamInfo: audioStreamInfo,
+ capturerInfo: audioCapturerInfo
+ }
+
+ let audioCapturer = await audio.createAudioCapturer(audioCapturerOptions);
+ console.log('AudioRecLog: Create audio capturer success.');
```
-3. Use **start()** to start audio recording.
+2. 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.
```js
- await audioCapturer.start();
- if (audioCapturer.state == audio.AudioState.STATE_RUNNING) {
- console.info('AudioRecLog: Capturer started');
- } else {
- console.info('AudioRecLog: Capturer start failed');
- }
- ```
-
-4. Use **getBufferSize()** to obtain the minimum buffer size to read.
+ import audio from '@ohos.multimedia.audio';
+
+ async function startCapturer() {
+ let state = audioCapturer.state;
+ // The audio capturer should be in the STATE_PREPARED, STATE_PAUSED, or STATE_STOPPED state after being started.
+ if (state != audio.AudioState.STATE_PREPARED || state != audio.AudioState.STATE_PAUSED ||
+ state != audio.AudioState.STATE_STOPPED) {
+ console.info('Capturer is not in a correct state to start');
+ return;
+ }
+ await audioCapturer.start();
- ```js
- var bufferSize = await audioCapturer.getBufferSize();
- console.info('AudioRecLog: buffer size: ' + bufferSize);
+ let state = audioCapturer.state;
+ if (state == audio.AudioState.STATE_RUNNING) {
+ console.info('AudioRecLog: Capturer started');
+ } else {
+ console.error('AudioRecLog: Capturer start 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.
+3. Read the captured audio data and convert it to a byte stream. Call **read()** repeatedly to read the data until the application stops the recording.
The following example shows how to write recorded data into a file.
```js
import fileio from '@ohos.fileio';
+
+ let state = audioCapturer.state;
+ // The read operation can be performed only when the state is STATE_RUNNING.
+ if (state != audio.AudioState.STATE_RUNNING) {
+ console.info('Capturer is not in a correct state to read');
+ return;
+ }
- const path = '/data/data/.pulse_dir/capture_js.wav';
+ const path = '/data/data/.pulse_dir/capture_js.wav'; // Path for storing the collected audio file.
let fd = fileio.openSync(path, 0o102, 0o777);
if (fd !== null) {
console.info('AudioRecLog: file fd created');
@@ -115,38 +110,140 @@ If an application needs to perform some operations when the audio renderer state
console.info('AudioRecLog: file fd opened in append mode');
}
- var numBuffersToCapture = 150;
+ let numBuffersToCapture = 150; // Write data for 150 times.
while (numBuffersToCapture) {
- var buffer = await audioCapturer.read(bufferSize, true);
+ let buffer = await audioCapturer.read(bufferSize, true);
if (typeof(buffer) == undefined) {
- console.info('read buffer failed');
+ console.info('AudioRecLog: read buffer failed');
} else {
- var number = fileio.writeSync(fd, buffer);
- console.info('AudioRecLog: data written: ' + number);
+ let number = fileio.writeSync(fd, buffer);
+ console.info(`AudioRecLog: data written: ${number}`);
}
numBuffersToCapture--;
}
```
-6. Once the recording is complete, call **stop()** to stop the recording.
+4. Once the recording is complete, call **stop()** to stop the recording.
+ ```js
+ async function StopCapturer() {
+ let state = audioCapturer.state;
+ // The audio capturer can be stopped only when it is in STATE_RUNNING or STATE_PAUSED state.
+ if (state != audio.AudioState.STATE_RUNNING && state != audio.AudioState.STATE_PAUSED) {
+ console.info('AudioRecLog: Capturer is not running or paused');
+ return;
+ }
+
+ await audioCapturer.stop();
+
+ state = audioCapturer.state;
+ if (state == audio.AudioState.STATE_STOPPED) {
+ console.info('AudioRecLog: Capturer stopped');
+ } else {
+ console.error('AudioRecLog: Capturer stop failed');
+ }
+ }
```
- await audioCapturer.stop();
- if (audioCapturer.state == audio.AudioState.STATE_STOPPED) {
- console.info('AudioRecLog: Capturer stopped');
- } else {
- console.info('AudioRecLog: Capturer stop failed');
- }
+
+5. After the task is complete, call **release()** to release related resources.
+
+ ```js
+ async function releaseCapturer() {
+ let state = audioCapturer.state;
+ // The audio capturer can be released only when it is not in the STATE_RELEASED or STATE_NEW state.
+ if (state == audio.AudioState.STATE_RELEASED || state == audio.AudioState.STATE_NEW) {
+ console.info('AudioRecLog: Capturer already released');
+ return;
+ }
+
+ await audioCapturer.release();
+
+ state = audioCapturer.state;
+ if (state == audio.AudioState.STATE_RELEASED) {
+ console.info('AudioRecLog: Capturer released');
+ } else {
+ console.info('AudioRecLog: Capturer release failed');
+ }
+ }
```
-7. After the task is complete, call **release()** to release related resources.
+6. (Optional) Obtain the audio capturer information.
+
+ You can use the following code to obtain the audio capturer information:
```js
- await audioCapturer.release();
- if (audioCapturer.state == audio.AudioState.STATE_RELEASED) {
- console.info('AudioRecLog: Capturer released');
- } else {
- console.info('AudioRecLog: Capturer release failed');
- }
+ // Obtain the audio capturer state.
+ let state = audioCapturer.state;
+
+ // Obtain the audio capturer information.
+ let audioCapturerInfo : audio.AuduioCapturerInfo = await audioCapturer.getCapturerInfo();
+
+ // Obtain the audio stream information.
+ let audioStreamInfo : audio.AudioStreamInfo = await audioCapturer.getStreamInfo();
+
+ // Obtain the audio stream ID.
+ let audioStreamId : number = await audioCapturer.getAudioStreamId();
+
+ // Obtain the Unix timestamp, in nanoseconds.
+ let audioTime : number = await audioCapturer.getAudioTime();
+
+ // Obtain a proper minimum buffer size.
+ let bufferSize : number = await audioCapturer.getBuffersize();
```
+
+7. (Optional) Use **on('markReach')** to subscribe to the mark reached event, and use **off('markReach')** to unsubscribe from the event.
+
+ After the mark reached event is subscribed to, when the number of frames collected by the audio capturer reaches the specified value, a callback is triggered and the specified value is returned.
+
+ ```js
+ audioCapturer.on('markReach', (reachNumber) => {
+ console.info('Mark reach event Received');
+ console.info(`The Capturer reached frame: ${reachNumber}`);
+ });
+
+ audioCapturer.off('markReach'); // Unsubscribe from the mark reached event. This event will no longer be listened for.
+ ```
+
+8. (Optional) Use **on('periodReach')** to subscribe to the period reached event, and use **off('periodReach')** to unsubscribe from the event.
+
+ After the period reached event is subscribed to, each time the number of frames collected by the audio capturer reaches the specified value, a callback is triggered and the specified value is returned.
+
+ ```js
+ audioCapturer.on('periodReach', (reachNumber) => {
+ console.info('Period reach event Received');
+ console.info(`In this period, the Capturer reached frame: ${reachNumber}`);
+ });
+
+ audioCapturer.off('periodReach'); // Unsubscribe from the period reached event. This event will no longer be listened for.
+ ```
+
+9. If your application needs to perform some operations when the audio capturer state is updated, it can subscribe to the state change event. When the audio capturer state is updated, the application receives a callback containing the event type.
+
+ ```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;
+ }
+ });
+ ```
diff --git a/en/application-dev/media/audio-interruptmode.md b/en/application-dev/media/audio-interruptmode.md
index 8be8a00cedd10ff4ecd08ee46d746d9803b3c71a..48a53bf5d5990ac88aae1271466a6aa36d52ac98 100644
--- a/en/application-dev/media/audio-interruptmode.md
+++ b/en/application-dev/media/audio-interruptmode.md
@@ -1,49 +1,50 @@
# Audio Interruption Mode Development
-## When to Use
-The audio interruption mode is used to control the playback of multiple audio streams.
-Audio applications can set the audio interruption mode to independent or shared under **AudioRenderer**.
-In shared mode, multiple audio streams share one session ID. In independent mode, each audio stream has an independent session ID.
+## Introduction
+The audio interruption mode is used to control the playback of multiple audio streams.
+
+Audio applications can set the audio interruption mode to independent or shared under **AudioRenderer**.
-### Asynchronous Operations
+In shared mode, multiple audio streams share one session ID. In independent mode, each audio stream has an independent session ID.
-To prevent the UI thread from being blocked, most **AudioRenderer** calls are asynchronous. Each API provides the callback and promise functions. The following examples use the promise functions.
+**Asynchronous operation**: To prevent the UI thread from being blocked, most **AudioRenderer** calls are asynchronous. Each API provides the callback and promise functions. The following examples use the promise functions.
## How to Develop
For details about the APIs, see [AudioRenderer in Audio Management](../reference/apis/js-apis-audio.md#audiorenderer8).
+1. Use **createAudioRenderer()** to create an **AudioRenderer** instance.
+
+ Set parameters of the **AudioRenderer** instance in **audioRendererOptions**.
-1. Use **createAudioRenderer()** to create an **AudioRenderer** instance.
- Set parameters of the **AudioRenderer** instance in **audioRendererOptions**.
- This instance is used to render audio, control and obtain the rendering status, and register a callback for notification.
-
- ```js
+ This instance is used to render audio, control and obtain the rendering status, and register a callback for notification.
+
+```js
import audio from '@ohos.multimedia.audio';
-
- var audioStreamInfo = {
- samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
- channels: audio.AudioChannel.CHANNEL_1,
- sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
- encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
- }
- var audioRendererInfo = {
- content: audio.ContentType.CONTENT_TYPE_SPEECH,
- usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION,
- rendererFlags: 1
- }
+ var audioStreamInfo = {
+ samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
+ channels: audio.AudioChannel.CHANNEL_1,
+ sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
+ encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
+ }
+
+ var audioRendererInfo = {
+ content: audio.ContentType.CONTENT_TYPE_SPEECH,
+ usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION,
+ rendererFlags: 1
+ }
- var audioRendererOptions = {
- streamInfo: audioStreamInfo,
- rendererInfo: audioRendererInfo
- }
+ var audioRendererOptions = {
+ streamInfo: audioStreamInfo,
+ rendererInfo: audioRendererInfo
+ }
- let audioRenderer = await audio.createAudioRenderer(audioRendererOptions);
+let audioRenderer = await audio.createAudioRenderer(audioRendererOptions);
```
-
-2. Set the audio interruption mode.
+2. Set the audio interruption mode.
+
After the **AudioRenderer** instance is initialized, you can set the audio interruption mode.
```js
diff --git a/en/application-dev/media/audio-playback.md b/en/application-dev/media/audio-playback.md
index 5227f6cdd1b9ec89818b0d1762c99267ec7eba97..92aa1cd4fc35a4b64ad9b1044c1a7bd59f24453d 100644
--- a/en/application-dev/media/audio-playback.md
+++ b/en/application-dev/media/audio-playback.md
@@ -1,25 +1,35 @@
# Audio Playback Development
-## When to Use
+## Introduction
-You can use audio playback APIs to convert audio data into audible analog signals, play the signals using output devices, and manage playback tasks.
+You can use audio playback APIs to convert audio data into audible analog signals and play the signals using output devices. You can also manage playback tasks. For example, you can start, suspend, stop playback, release resources, set the volume, seek to a playback position, and obtain track information.
-**Figure 1** Playback status
+## Working Principles
+
+The following figures show the audio playback status changes and the interaction with external modules for audio playback.
+
+**Figure 1** Audio playback state transition
![en-us_image_audio_state_machine](figures/en-us_image_audio_state_machine.png)
-**Note**: If the status is **Idle**, setting the **src** attribute does not change the status. In addition, after the **src** attribute is set successfully, you must call **reset()** before setting it to another value.
+**NOTE**: If the status is **Idle**, setting the **src** attribute does not change the status. In addition, after the **src** attribute is set successfully, you must call **reset()** before setting it to another value.
-**Figure 2** Layer 0 diagram of audio playback
+**Figure 2** Interaction with external modules for audio playback
![en-us_image_audio_player](figures/en-us_image_audio_player.png)
+**NOTE**: When a third-party application calls the JS interface provided by the JS interface layer to implement a feature, the framework layer invokes the audio component through the media service of the native framework and outputs the audio data decoded by the software to the audio HDI of the hardware interface layer to implement audio playback.
+
## How to Develop
For details about the APIs, see [AudioPlayer in the Media API](../reference/apis/js-apis-media.md#audioplayer).
+> **NOTE**
+>
+> The method for obtaining the path in the FA model is different from that in the stage model. **pathDir** used in the sample code below is an example. You need to obtain the path based on project requirements. For details about how to obtain the path, see [Application Sandbox Path Guidelines](../reference/apis/js-apis-fileio.md#guidelines).
+
### Full-Process Scenario
The full audio playback process includes creating an instance, setting the URI, playing audio, seeking to the playback position, setting the volume, pausing playback, obtaining track information, stopping playback, resetting the player, and releasing resources.
@@ -99,8 +109,9 @@ async function audioPlayerDemo() {
setCallBack(audioPlayer); // Set the event callbacks.
// 2. Set the URI of the audio file.
let fdPath = 'fd://'
- // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command.
- let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3';
+ let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements.
+ // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
+ let path = pathDir + '/01.mp3'
await fileIO.open(path).then((fdNumber) => {
fdPath = fdPath + '' + fdNumber;
console.info('open fd success fd is' + fdPath);
@@ -118,6 +129,7 @@ async function audioPlayerDemo() {
```js
import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio'
+
export class AudioDemo {
// Set the player callbacks.
setCallBack(audioPlayer) {
@@ -139,8 +151,9 @@ export class AudioDemo {
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
this.setCallBack(audioPlayer); // Set the event callbacks.
let fdPath = 'fd://'
- // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command.
- let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3';
+ let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements.
+ // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
+ let path = pathDir + '/01.mp3'
await fileIO.open(path).then((fdNumber) => {
fdPath = fdPath + '' + fdNumber;
console.info('open fd success fd is' + fdPath);
@@ -159,6 +172,7 @@ export class AudioDemo {
```js
import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio'
+
export class AudioDemo {
// Set the player callbacks.
private isNextMusic = false;
@@ -185,8 +199,9 @@ export class AudioDemo {
async nextMusic(audioPlayer) {
this.isNextMusic = true;
let nextFdPath = 'fd://'
- // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\02.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command.
- let nextpath = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/02.mp3';
+ let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements.
+ // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\02.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
+ let nextpath = pathDir + '/02.mp3'
await fileIO.open(nextpath).then((fdNumber) => {
nextFdPath = nextFdPath + '' + fdNumber;
console.info('open fd success fd is' + nextFdPath);
@@ -202,8 +217,9 @@ export class AudioDemo {
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
this.setCallBack(audioPlayer); // Set the event callbacks.
let fdPath = 'fd://'
- // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command.
- let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3';
+ let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements.
+ // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
+ let path = pathDir + '/01.mp3'
await fileIO.open(path).then((fdNumber) => {
fdPath = fdPath + '' + fdNumber;
console.info('open fd success fd is' + fdPath);
@@ -222,6 +238,7 @@ export class AudioDemo {
```js
import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio'
+
export class AudioDemo {
// Set the player callbacks.
setCallBack(audioPlayer) {
@@ -239,8 +256,9 @@ export class AudioDemo {
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
this.setCallBack(audioPlayer); // Set the event callbacks.
let fdPath = 'fd://'
- // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command.
- let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3';
+ let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements.
+ // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command.
+ let path = pathDir + '/01.mp3'
await fileIO.open(path).then((fdNumber) => {
fdPath = fdPath + '' + fdNumber;
console.info('open fd success fd is' + fdPath);
diff --git a/en/application-dev/media/audio-recorder.md b/en/application-dev/media/audio-recorder.md
index f465db2b88118b77c9a4e64307170da07c3e8918..78650a61d0a803811394e623ab0bc46155438ba9 100644
--- a/en/application-dev/media/audio-recorder.md
+++ b/en/application-dev/media/audio-recorder.md
@@ -1,8 +1,12 @@
# Audio Recording Development
-## When to Use
+## Introduction
-During audio recording, audio signals are captured, encoded, and saved to files. You can specify parameters such as the sampling rate, number of audio channels, encoding format, encapsulation format, and file path for audio recording.
+During audio recording, audio signals are captured, encoded, and saved to files. You can specify parameters such as the sampling rate, number of audio channels, encoding format, encapsulation format, and output file path for audio recording.
+
+## Working Principles
+
+The following figures show the audio recording state transition and the interaction with external modules for audio recording.
**Figure 1** Audio recording state transition
@@ -10,10 +14,16 @@ During audio recording, audio signals are captured, encoded, and saved to files.
-**Figure 2** Layer 0 diagram of audio recording
+**Figure 2** Interaction with external modules for audio recording
![en-us_image_audio_recorder_zero](figures/en-us_image_audio_recorder_zero.png)
+**NOTE**: When a third-party recording application or recorder calls the JS interface provided by the JS interface layer to implement a feature, the framework layer invokes the audio component through the media service of the native framework to obtain the audio data captured through the audio HDI. The framework layer then encodes the audio data through software and saves the encoded and encapsulated audio data to a file to implement audio recording.
+
+## Constraints
+
+Before developing audio recording, configure the **ohos.permission.MICROPHONE** permission for your application. For details about the configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md).
+
## How to Develop
For details about the APIs, see [AudioRecorder in the Media API](../reference/apis/js-apis-media.md#audiorecorder).
diff --git a/en/application-dev/media/audio-renderer.md b/en/application-dev/media/audio-renderer.md
index 82a0753b66384e6f1a991ba97f7d6c7580936e0e..699eb7cb6cae5f198c1620e22b7c3f0df4a90813 100644
--- a/en/application-dev/media/audio-renderer.md
+++ b/en/application-dev/media/audio-renderer.md
@@ -1,214 +1,197 @@
# Audio Rendering Development
-## When to Use
+## Introduction
**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
+Before calling the APIs, be familiar with the following terms:
-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).
+- **Audio interruption**: 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.
+- **Status 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.
+- **Asynchronous operation**: To prevent the UI thread from being 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).
+- **Audio interruption mode**: OpenHarmony provides two audio interruption modes: **shared mode** and **independent mode**. In shared mode, all **AudioRenderer** instances created by the same application share one focus object, and there is no focus transfer inside the application. Therefore, no callback will be triggered. In independent mode, each **AudioRenderer** instance has an independent focus object, and focus preemption occurs. Focus preemption triggers focus transfer, and the **AudioRenderer** instance that originally has the focus receives a notification through the callback. By default, the shared mode is used. You can call **setInterruptMode()** to set the independent mode.
-### State Check
+## Working Principles
-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.
+The following figure shows the audio renderer state transitions.
-**Figure 1** Audio renderer state
+Figure 1 Audio renderer state transitions
-![](figures/audio-renderer-state.png)
+![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).
+- **PREPARED**: The audio renderer enters this state by calling **create()**.
+- **RUNNING**: The audio renderer enters this state by calling **start()** when it is in the **PREPARED** state or by calling **start()** when it is in the **STOPPED** state.
+- **PAUSED**: The audio renderer in the **RUNNING** state can call **pause()** to pause the audio playback. After the audio playback is paused, it can call **start()** to resume the playback.
+- **STOPPED**: The audio renderer in the **PAUSED** or **RUNNING** state can call **stop()** to stop the playback.
+- **RELEASED**: The audio renderer in the **PREPARED**, **PAUSED**, or **STOPPED** state can use **release()** to release all occupied hardware and software resources. It will not transit to any other state after it enters the **RELEASED** state.
## How to Develop
+For details about the APIs, see [AudioRenderer in Audio Management](../reference/apis/js-apis-audio.md#audiorenderer8).
+
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.
+
+
+Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. This instance is used to render audio, control and obtain the rendering status, and register a callback for notification.
```js
- var audioStreamInfo = {
+ import audio from '@ohos.multimedia.audio';
+
+ let audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_1,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
}
-
- var audioRendererInfo = {
+ let audioRendererInfo = {
content: audio.ContentType.CONTENT_TYPE_SPEECH,
usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION,
- rendererFlags: 1
+ rendererFlags: 0 // 0 is the extended flag bit of the audio renderer. The default value is 0.
}
-
- var audioRendererOptions = {
+ let audioRendererOptions = {
streamInfo: audioStreamInfo,
rendererInfo: audioRendererInfo
- }
+ }
let audioRenderer = await audio.createAudioRenderer(audioRendererOptions);
+ console.log("Create audio renderer success.");
```
-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.
+2. Use **start()** to start audio rendering.
- 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);
+ async function startRenderer() {
+ let state = audioRenderer.state;
+ // The audio renderer should be in the STATE_PREPARED, STATE_PAUSED, or STATE_STOPPED state after being started.
+ 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;
+ }
- 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.
+ await audioRenderer.start();
+ state = audioRenderer.state;
+ if (state == audio.AudioState.STATE_RUNNING) {
+ console.info('Renderer started');
+ } else {
+ console.error('Renderer start failed');
+ }
+ }
+ ```
The renderer state will be **STATE_RUNNING** once the audio renderer is started. The application can then begin reading buffers.
- ```js
- async function startRenderer() {
- var state = audioRenderer.state;
- // 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');
- } else {
- console.error('Renderer start failed');
- }
- }
- ```
-4. Call **write()** to write data to the buffer.
+3. 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) {
- console.error('Renderer is not running, do not write');
- isPlay = false;
- 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';
- let ss = fileio.createStreamSync(path, 'r');
- const totalSize = 2146166; // file_example_WAV_2MG.wav
- let rlen = 0;
- let discardHeader = new ArrayBuffer(44);
- ss.readSync(discardHeader);
- rlen += 44;
-
- var id = setInterval(() => {
- if (isPlay || isRelease) {
- if (rlen >= totalSize || isRelease) {
- ss.closeSync();
- stopRenderer();
- clearInterval(id);
- }
- let buf = new ArrayBuffer(bufferSize);
- rlen += ss.readSync(buf);
- console.info('Total bytes read from file: ' + rlen);
- writeBuffer(buf);
- } else {
- console.info('check after next interval');
- }
- } , 30); // interval to be set based on audio file format
+ import fileio from '@ohos.fileio';
+ import audio from '@ohos.multimedia.audio';
+
+ async function writeBuffer(buf) {
+ // The write operation can be performed only when the state is STATE_RUNNING.
+ if (audioRenderer.state != audio.AudioState.STATE_RUNNING) {
+ console.error('Renderer is not running, do not write');
+ 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');
+ }
+ }
+
+ // Set a proper buffer size for the audio renderer. You can also select a buffer of another size.
+ const bufferSize = await audioRenderer.getBufferSize();
+ let dir = globalThis.fileDir; // You must use the sandbox path.
+ const path = dir + '/file_example_WAV_2MG.wav'; // The file to render is in the following path: /data/storage/el2/base/haps/entry/files/file_example_WAV_2MG.wav
+ console.info(`file path: ${ path}`);
+ let ss = fileio.createStreamSync(path, 'r');
+ const totalSize = fileio.statSync(path).size; // Size of the file to render.
+ let discardHeader = new ArrayBuffer(bufferSize);
+ ss.readSync(discardHeader);
+ let rlen = 0;
+ rlen += bufferSize;
+
+ let id = setInterval(() => {
+ if (audioRenderer.state == audio.AudioState.STATE_RELEASED) { // The rendering stops if the audio renderer is in the STATE_RELEASED state.
+ ss.closeSync();
+ await audioRenderer.stop();
+ clearInterval(id);
+ }
+ if (audioRenderer.state == audio.AudioState.STATE_RUNNING) {
+ if (rlen >= totalSize) { // The rendering stops if the file finishes reading.
+ ss.closeSync();
+ await audioRenderer.stop();
+ clearInterval(id);
+ }
+ let buf = new ArrayBuffer(bufferSize);
+ rlen += ss.readSync(buf);
+ console.info(`Total bytes read from file: ${rlen}`);
+ writeBuffer(buf);
+ } else {
+ console.info('check after next interval');
+ }
+ }, 30); // The timer interval is set based on the audio format. The unit is millisecond.
```
-5. (Optional) Call **pause()** or **stop()** to pause or stop rendering.
+4. (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');
- }
+ let state = audioRenderer.state;
+ // The audio renderer can be paused only when it is in the STATE_RUNNING 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');
- }
- }
+ let state = audioRenderer.state;
+ // The audio renderer can be stopped only when it is in STATE_RUNNING or STATE_PAUSED 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');
+ }
+ }
+ ```
+
+5. (Optional) Call **drain()** to clear the buffer.
+
+ ```js
+ async function drainRenderer() {
+ let state = audioRenderer.state;
+ // drain() can be used only when the audio renderer is in the STATE_RUNNING state.
+ if (state != audio.AudioState.STATE_RUNNING) {
+ console.info('Renderer is not running');
+ return;
+ }
+
+ await audioRenderer.drain();
+
+ state = audioRenderer.state;
+ }
```
6. After the task is complete, call **release()** to release related resources.
@@ -217,19 +200,349 @@ To ensure that the UI thread is not blocked, most **AudioRenderer** calls are as
```js
async function releaseRenderer() {
- if (state_ == RELEASED || state_ == NEW) {
- console.info('Resourced already released');
- return;
- }
+ let state = audioRenderer.state;
+ // The audio renderer can be released only when it is not in the STATE_RELEASED or STATE_NEW state.
+ if (state == audio.AudioState.STATE_RELEASED || state == audio.AudioState.STATE_NEW) {
+ console.info('Renderer already released');
+ return;
+ }
+
+ await audioRenderer.release();
+
+ state = audioRenderer.state;
+ if (state == audio.AudioState.STATE_RELEASED) {
+ console.info('Renderer released');
+ } else {
+ console.info('Renderer release failed');
+ }
+ }
+ ```
- await audioRenderer.release();
+7. (Optional) Obtain the audio renderer information.
+
+ You can use the following code to obtain the audio renderer information:
- state = audioRenderer.state;
- if (state == STATE_RELEASED) {
- console.info('Renderer released');
- } else {
- console.info('Renderer release failed');
- }
+ ```js
+ // Obtain the audio renderer state.
+ let state = audioRenderer.state;
+
+ // Obtain the audio renderer information.
+ let audioRendererInfo : audio.AudioRendererInfo = await audioRenderer.getRendererInfo();
- }
+ // Obtain the audio stream information.
+ let audioStreamInfo : audio.AudioStreamInfo = await audioRenderer.getStreamInfo();
+
+ // Obtain the audio stream ID.
+ let audioStreamId : number = await audioRenderer.getAudioStreamId();
+
+ // Obtain the Unix timestamp, in nanoseconds.
+ let audioTime : number = await audioRenderer.getAudioTime();
+
+ // Obtain a proper minimum buffer size.
+ let bufferSize : number = await audioRenderer.getBuffersize();
+
+ // Obtain the audio renderer rate.
+ let renderRate : audio.AudioRendererRate = await audioRenderer.getRenderRate();
```
+
+8. (Optional) Set the audio renderer information.
+
+ You can use the following code to set the audio renderer information:
+
+ ```js
+ // Set the audio renderer rate to RENDER_RATE_NORMAL.
+ let renderRate : audio.AudioRendererRate = audio.AudioRendererRate.RENDER_RATE_NORMAL;
+ await audioRenderer.setRenderRate(renderRate);
+
+ // Set the interruption mode of the audio renderer to SHARE_MODE.
+ let interruptMode : audio.InterruptMode = audio.InterruptMode.SHARE_MODE;
+ await audioRenderer.setInterruptMode(interruptMode);
+
+ // Set the volume of the stream to 10.
+ let volume : number = 10;
+ await audioRenderer.setVolume(volume);
+ ```
+
+9. (Optional) Use **on('audioInterrupt')** to subscribe to the audio interruption event, and use **off('audioInterrupt')** to unsubscribe from the event.
+
+ Audio interruption means that Stream A will be 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 audio 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).
+
+ It should be noted that the audio interruption event subscription of the **AudioRenderer** module is slightly different from **on('interrupt')** in [AudioManager](../reference/apis/js-apis-audio.md#audiomanager). The **on('interrupt')** and **off('interrupt')** APIs are deprecated since API version 9. In the **AudioRenderer** module, you only need to call **on('audioInterrupt')** to listen for focus change events. When the **AudioRenderer** instance created by the application performs actions such as start, stop, and pause, it requests the focus, which triggers focus transfer and in return enables the related **AudioRenderer** instance to receive a notification through the callback. For instances other than **AudioRenderer**, such as frequency modulation (FM) and voice wakeup, the application does not create an instance. In this case, the application can call **on('interrupt')** in **AudioManager** to receive a focus change notification.
+
+ ```js
+ audioRenderer.on('audioInterrupt', (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) {
+ // Forcible pausing initiated by the audio framework. To prevent data loss, stop the write operation.
+ case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
+ isPlay = false;
+ break;
+ // Forcible stopping initiated by the audio framework. To prevent data loss, stop the write operation.
+ case audio.InterruptHint.INTERRUPT_HINT_STOP:
+ isPlay = false;
+ break;
+ // Forcible ducking initiated by the audio framework.
+ case audio.InterruptHint.INTERRUPT_HINT_DUCK:
+ break;
+ // Undocking initiated by the audio framework.
+ case audio.InterruptHint.INTERRUPT_HINT_UNDUCK:
+ break;
+ }
+ } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) {
+ switch (interruptEvent.hintType) {
+ // Notify the application that the rendering starts.
+ case audio.InterruptHint.INTERRUPT_HINT_RESUME:
+ startRenderer();
+ break;
+ // Notify the application that the audio stream is interrupted. The application determines whether to continue. (In this example, the application pauses the rendering.)
+ case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
+ isPlay = false;
+ pauseRenderer();
+ break;
+ }
+ }
+ });
+
+ audioRenderer.off('audioInterrupt'); // Unsubscribe from the audio interruption event. This event will no longer be received.
+ ```
+
+10. (Optional) Use **on('markReach')** to subscribe to the mark reached event, and use **off('markReach')** to unsubscribe from the event.
+
+ After the mark reached event is subscribed to, when the number of frames rendered by the audio renderer reaches the specified value, a callback is triggered and the specified value is returned.
+
+ ```js
+ audioRenderer.on('markReach', (reachNumber) => {
+ console.info('Mark reach event Received');
+ console.info(`The renderer reached frame: ${reachNumber}`);
+ });
+
+ audioRenderer.off('markReach'); // Unsubscribe from the mark reached event. This event will no longer be listened for.
+ ```
+
+11. (Optional) Use **on('periodReach')** to subscribe to the period reached event, and use **off('periodReach')** to unsubscribe from the event.
+
+ After the period reached event is subscribed to, each time the number of frames rendered by the audio renderer reaches the specified value, a callback is triggered and the specified value is returned.
+
+ ```js
+ audioRenderer.on('periodReach', (reachNumber) => {
+ console.info('Period reach event Received');
+ console.info(`In this period, the renderer reached frame: ${reachNumber} `);
+ });
+
+ audioRenderer.off('periodReach'); // Unsubscribe from the period reached event. This event will no longer be listened for.
+ ```
+
+12. (Optional) Use **on('stateChange')** to subscribe to audio renderer state changes.
+
+ After the **stateChange** event is subscribed to, when the audio renderer state changes, a callback is triggered and the audio renderer state is returned.
+
+ ```js
+ audioRenderer.on('stateChange', (audioState) => {
+ console.info('State change event Received');
+ console.info(`Current renderer state is: ${audioState}`);
+ });
+ ```
+
+13. (Optional) Handle exceptions of **on()**.
+
+ If the string or the parameter type passed in **on()** is incorrect , the application throws an exception. In this case, you can use **try catch** to capture the exception.
+
+ ```js
+ try {
+ audioRenderer.on('invalidInput', () => { // The string does not match.
+ })
+ } catch (err) {
+ console.info(`Call on function error, ${err}`); // The application throws exception 401.
+ }
+ try {
+ audioRenderer.on(1, () => { // The type of the input parameter is incorrect.
+ })
+ } catch (err) {
+ console.info(`Call on function error, ${err}`); // The application throws exception 6800101.
+ }
+ ```
+
+14. (Optional) Refer to the complete example of **on('audioInterrupt')**.
+
+ Create **AudioRender1** and **AudioRender2** in an application, configure the independent interruption mode, and call **on('audioInterrupt')** to subscribe to audio interruption events. At the beginning, **AudioRender1** has the focus. When **AudioRender2** attempts to obtain the focus, **AudioRenderer1** receives a focus transfer notification and the related log information is printed. If the shared mode is used, the log information will not be printed during application running.
+
+ ```js
+ async runningAudioRender1(){
+ let audioStreamInfo = {
+ samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000,
+ channels: audio.AudioChannel.CHANNEL_1,
+ sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE,
+ encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
+ }
+ let audioRendererInfo = {
+ content: audio.ContentType.CONTENT_TYPE_MUSIC,
+ usage: audio.StreamUsage.STREAM_USAGE_MEDIA,
+ rendererFlags: 0 // 0 is the extended flag bit of the audio renderer. The default value is 0.
+ }
+ let audioRendererOptions = {
+ streamInfo: audioStreamInfo,
+ rendererInfo: audioRendererInfo
+ }
+
+ // 1.1 Create an instance.
+ audioRenderer1 = await audio.createAudioRenderer(audioRendererOptions);
+ console.info("Create audio renderer 1 success.");
+
+ // 1.2 Set the independent mode.
+ audioRenderer1.setInterruptMode(1).then( data => {
+ console.info('audioRenderer1 setInterruptMode Success!');
+ }).catch((err) => {
+ console.error(`audioRenderer1 setInterruptMode Fail: ${err}`);
+ });
+
+ // 1.3 Set the listener.
+ audioRenderer1.on('audioInterrupt', async(interruptEvent) => {
+ console.info(`audioRenderer1 on audioInterrupt : ${JSON.stringify(interruptEvent)}`)
+ });
+
+ // 1.4 Start rendering.
+ await audioRenderer1.start();
+ console.info('startAudioRender1 success');
+
+ // 1.5 Obtain the buffer size, which is the proper minimum buffer size of the audio renderer. You can also select a buffer of another size.
+ const bufferSize = await audioRenderer1.getBufferSize();
+ console.info(`audio bufferSize: ${bufferSize}`);
+
+ // 1.6 Obtain the original audio data file.
+ let dir = globalThis.fileDir; // You must use the sandbox path.
+ const path1 = dir + '/music001_48000_32_1.wav'; // The file to render is in the following path: /data/storage/el2/base/haps/entry/files/music001_48000_32_1.wav
+ console.info(`audioRender1 file path: ${ path1}`);
+ let ss1 = await fileio.createStream(path1,'r');
+ const totalSize1 = fileio.statSync(path1).size; // Size of the file to render.
+ console.info(`totalSize1 -------: ${totalSize1}`);
+ let discardHeader = new ArrayBuffer(bufferSize);
+ ss1.readSync(discardHeader);
+ let rlen = 0;
+ rlen += bufferSize;
+
+ // 1.7 Render the original audio data in the buffer by using audioRenderer.
+ let id = setInterval(async () => {
+ if (audioRenderer1.state == audio.AudioState.STATE_RELEASED) { // The rendering stops if the audio renderer is in the STATE_RELEASED state.
+ ss1.closeSync();
+ audioRenderer1.stop();
+ clearInterval(id);
+ }
+ if (audioRenderer1.state == audio.AudioState.STATE_RUNNING) {
+ if (rlen >= totalSize1) { // The rendering stops if the file finishes reading.
+ ss1.closeSync();
+ await audioRenderer1.stop();
+ clearInterval(id);
+ }
+ let buf = new ArrayBuffer(bufferSize);
+ rlen += ss1.readSync(buf);
+ console.info(`Total bytes read from file: ${rlen}`);
+ await writeBuffer(buf, that.audioRenderer1);
+ } else {
+ console.info('check after next interval');
+ }
+ }, 30); // The timer interval is set based on the audio format. The unit is millisecond.
+ }
+
+ async runningAudioRender2(){
+ let audioStreamInfo = {
+ samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000,
+ channels: audio.AudioChannel.CHANNEL_1,
+ sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE,
+ encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
+ }
+ let audioRendererInfo = {
+ content: audio.ContentType.CONTENT_TYPE_MUSIC,
+ usage: audio.StreamUsage.STREAM_USAGE_MEDIA,
+ rendererFlags: 0 // 0 is the extended flag bit of the audio renderer. The default value is 0.
+ }
+ let audioRendererOptions = {
+ streamInfo: audioStreamInfo,
+ rendererInfo: audioRendererInfo
+ }
+
+ // 2.1 Create another instance.
+ audioRenderer2 = await audio.createAudioRenderer(audioRendererOptions);
+ console.info("Create audio renderer 2 success.");
+
+ // 2.2 Set the independent mode.
+ audioRenderer2.setInterruptMode(1).then( data => {
+ console.info('audioRenderer2 setInterruptMode Success!');
+ }).catch((err) => {
+ console.error(`audioRenderer2 setInterruptMode Fail: ${err}`);
+ });
+
+ // 2.3 Set the listener.
+ audioRenderer2.on('audioInterrupt', async(interruptEvent) => {
+ console.info(`audioRenderer2 on audioInterrupt : ${JSON.stringify(interruptEvent)}`)
+ });
+
+ // 2.4 Start rendering.
+ await audioRenderer2.start();
+ console.info('startAudioRender2 success');
+
+ // 2.5 Obtain the buffer size.
+ const bufferSize = await audioRenderer2.getBufferSize();
+ console.info(`audio bufferSize: ${bufferSize}`);
+
+ // 2.6 Read the original audio data file.
+ let dir = globalThis.fileDir; // You must use the sandbox path.
+ const path2 = dir + '/music002_48000_32_1.wav'; // The file to render is in the following path: /data/storage/el2/base/haps/entry/files/music002_48000_32_1.wav
+ console.error(`audioRender1 file path: ${ path2}`);
+ let ss2 = await fileio.createStream(path2,'r');
+ const totalSize2 = fileio.statSync(path2).size; // Size of the file to render.
+ console.error(`totalSize2 -------: ${totalSize2}`);
+ let discardHeader2 = new ArrayBuffer(bufferSize);
+ ss2.readSync(discardHeader2);
+ let rlen = 0;
+ rlen += bufferSize;
+
+ // 2.7 Render the original audio data in the buffer by using audioRenderer.
+ let id = setInterval(async () => {
+ if (audioRenderer2.state == audio.AudioState.STATE_RELEASED) { // The rendering stops if the audio renderer is in the STATE_RELEASED state.
+ ss2.closeSync();
+ that.audioRenderer2.stop();
+ clearInterval(id);
+ }
+ if (audioRenderer1.state == audio.AudioState.STATE_RUNNING) {
+ if (rlen >= totalSize2) { // The rendering stops if the file finishes reading.
+ ss2.closeSync();
+ await audioRenderer2.stop();
+ clearInterval(id);
+ }
+ let buf = new ArrayBuffer(bufferSize);
+ rlen += ss2.readSync(buf);
+ console.info(`Total bytes read from file: ${rlen}`);
+ await writeBuffer(buf, that.audioRenderer2);
+ } else {
+ console.info('check after next interval');
+ }
+ }, 30); // The timer interval is set based on the audio format. The unit is millisecond.
+ }
+
+ async writeBuffer(buf, audioRender) {
+ let writtenbytes;
+ await audioRender.write(buf).then((value) => {
+ writtenbytes = value;
+ console.info(`Actual written bytes: ${writtenbytes} `);
+ });
+ if (typeof(writtenbytes) != 'number' || writtenbytes < 0) {
+ console.error('get Write buffer failed. check the state of renderer');
+ }
+ }
+
+ // Integrated invoking entry.
+ async test(){
+ await runningAudioRender1();
+ await runningAudioRender2();
+ }
+
+ ```
diff --git a/en/application-dev/media/audio-stream-manager.md b/en/application-dev/media/audio-stream-manager.md
index eb89957e9b8793b149c368445f1232bf0ff3b563..44ec37cd11f3666131214e5e908a1ce761fea111 100644
--- a/en/application-dev/media/audio-stream-manager.md
+++ b/en/application-dev/media/audio-stream-manager.md
@@ -1,57 +1,61 @@
# Audio Stream Management Development
-## When to Use
+## Introduction
You can use **AudioStreamManager** to manage audio streams.
-### Development Process
+## Working Principles
-During application development, use **getStreamManager()** to create an **AudioStreamManager** instance. Then, you can call **on('audioRendererChange')** or **on('audioCapturerChange')** to listen for status, client, and audio attribute changes of the audio playback or recording application. To cancel the listening for these changes, call **off('audioRendererChange')** or **off('audioCapturerChange')**. You can call **getCurrentAudioRendererInfoArray()** to obtain information about the audio playback application, such as the unique audio stream ID, UID of the audio playback client, and audio status. Similarly, you can call **getCurrentAudioCapturerInfoArray()** to obtain information about the audio recording application. The figure below shows the invoking relationship.
+The following figure shows the calling relationship of **AudioStreamManager** APIs.
-For details about the APIs, see [AudioStreamManager](../reference/apis/js-apis-audio.md#audiostreammanager9).
+**Figure 1** AudioStreamManager API calling relationship
-**Figure 1** Audio stream management invoking relationship
+![en-us_image_audio_stream_manager](figures/en-us_image_audio_stream_manager.png)
-![](figures/en-us_image_audio_stream_manager.png)
+**NOTE**: During application development, use **getStreamManager()** to create an **AudioStreamManager** instance. Then, you can call **on('audioRendererChange')** or **on('audioCapturerChange')** to listen for status, client, and audio attribute changes of the audio playback or recording application. To cancel the listening for these changes, call **off('audioRendererChange')** or **off('audioCapturerChange')**. You can call **getCurrentAudioRendererInfoArray()** to obtain information about the audio playback application, such as the unique audio stream ID, UID of the audio playback client, and audio status. Similarly, you can call **getCurrentAudioCapturerInfoArray()** to obtain information about the audio recording application.
## How to Develop
+For details about the APIs, see [AudioStreamManager](../reference/apis/js-apis-audio.md#audiostreammanager9).
+
1. Create an **AudioStreamManager** instance.
Before using **AudioStreamManager** APIs, you must use **getStreamManager()** to create an **AudioStreamManager** instance.
```js
- var audioStreamManager = audio.getStreamManager();
+ var audioManager = audio.getAudioManager();
+ var audioStreamManager = audioManager.getStreamManager();
```
2. (Optional) Call **on('audioRendererChange')** to listen for audio renderer changes.
-If an application needs to receive notifications when the audio playback application status, audio playback client, or audio attribute changes, it can subscribe to this event. For more events that can be subscribed to, see [Audio Management](../reference/apis/js-apis-audio.md).
- ```js
- audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => {
- for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) {
- AudioRendererChangeInfo = AudioRendererChangeInfoArray[i];
- console.info('## RendererChange on is called for ' + i + ' ##');
- console.info('StreamId for ' + i + ' is:' + AudioRendererChangeInfo.streamId);
- console.info('ClientUid for ' + i + ' is:' + AudioRendererChangeInfo.clientUid);
- console.info('Content for ' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.content);
- console.info('Stream for ' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.usage);
- console.info('Flag ' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.rendererFlags);
- console.info('State for ' + i + ' is:' + AudioRendererChangeInfo.rendererState);
- var devDescriptor = AudioRendererChangeInfo.deviceDescriptors;
- for (let j = 0; j < AudioRendererChangeInfo.deviceDescriptors.length; j++) {
- console.info('Id:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].id);
- console.info('Type:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].deviceType);
- console.info('Role:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].deviceRole);
- console.info('Name:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].name);
- console.info('Address:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].address);
- console.info('SampleRates:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]);
- console.info('ChannelCounts' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]);
- console.info('ChannelMask:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelMasks);
- }
- }
- });
- ```
+ If an application needs to receive notifications when the audio playback application status, audio playback client, or audio attribute changes, it can subscribe to this event. For more events that can be subscribed to, see [Audio Management](../reference/apis/js-apis-audio.md).
+
+ ```js
+ audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => {
+ for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) {
+ AudioRendererChangeInfo = AudioRendererChangeInfoArray[i];
+ console.info('## RendererChange on is called for ' + i + ' ##');
+ console.info('StreamId for ' + i + ' is:' + AudioRendererChangeInfo.streamId);
+ console.info('ClientUid for ' + i + ' is:' + AudioRendererChangeInfo.clientUid);
+ console.info('Content for ' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.content);
+ console.info('Stream for ' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.usage);
+ console.info('Flag ' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.rendererFlags);
+ console.info('State for ' + i + ' is:' + AudioRendererChangeInfo.rendererState);
+ var devDescriptor = AudioRendererChangeInfo.deviceDescriptors;
+ for (let j = 0; j < AudioRendererChangeInfo.deviceDescriptors.length; j++) {
+ console.info('Id:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].id);
+ console.info('Type:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].deviceType);
+ console.info('Role:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].deviceRole);
+ console.info('Name:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].name);
+ console.info('Address:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].address);
+ console.info('SampleRates:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]);
+ console.info('ChannelCounts' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]);
+ console.info('ChannelMask:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelMasks);
+ }
+ }
+ });
+ ```
3. (Optional) Call **off('audioRendererChange')** to cancel listening for audio renderer changes.
@@ -61,30 +65,31 @@ If an application needs to receive notifications when the audio playback applica
```
4. (Optional) Call **on('audioCapturerChange')** to listen for audio capturer changes.
-If an application needs to receive notifications when the audio recording application status, audio recording client, or audio attribute changes, it can subscribe to this event. For more events that can be subscribed to, see [Audio Management](../reference/apis/js-apis-audio.md).
- ```js
- audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => {
- for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) {
- console.info(' ## audioCapturerChange on is called for element ' + i + ' ##');
- console.info('StreamId for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].streamId);
- console.info('ClientUid for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].clientUid);
- console.info('Source for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.source);
- console.info('Flag ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags);
- console.info('State for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerState);
- for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) {
- console.info('Id:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id);
- console.info('Type:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType);
- console.info('Role:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole);
- console.info('Name:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name);
- console.info('Address:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address);
- console.info('SampleRates:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]);
- console.info('ChannelCounts' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]);
- console.info('ChannelMask:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks);
- }
- }
- });
- ```
+ If an application needs to receive notifications when the audio recording application status, audio recording client, or audio attribute changes, it can subscribe to this event. For more events that can be subscribed to, see [Audio Management](../reference/apis/js-apis-audio.md).
+
+ ```js
+ audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => {
+ for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) {
+ console.info(' ## audioCapturerChange on is called for element ' + i + ' ##');
+ console.info('StreamId for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].streamId);
+ console.info('ClientUid for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].clientUid);
+ console.info('Source for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.source);
+ console.info('Flag ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags);
+ console.info('State for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerState);
+ for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) {
+ console.info('Id:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id);
+ console.info('Type:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType);
+ console.info('Role:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole);
+ console.info('Name:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name);
+ console.info('Address:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address);
+ console.info('SampleRates:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]);
+ console.info('ChannelCounts' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]);
+ console.info('ChannelMask:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks);
+ }
+ }
+ });
+ ```
5. (Optional) Call **off('audioCapturerChange')** to cancel listening for audio capturer changes.
@@ -94,65 +99,66 @@ If an application needs to receive notifications when the audio recording applic
```
6. (Optional) Call **getCurrentAudioRendererInfoArray()** to obtain information about the current audio renderer.
-This API can be used to obtain the unique ID of the audio stream, UID of the audio playback client, audio status, and other information about the audio player. Before calling this API, a third-party application must have the **ohos.permission.USE_BLUETOOTH** permission configured, for the device name and device address to be displayed correctly.
-
- ```js
- await audioStreamManager.getCurrentAudioRendererInfoArray().then( function (AudioRendererChangeInfoArray) {
- console.info('######### Get Promise is called ##########');
- if (AudioRendererChangeInfoArray != null) {
- for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) {
- AudioRendererChangeInfo = AudioRendererChangeInfoArray[i];
- console.info('StreamId for ' + i +' is:' + AudioRendererChangeInfo.streamId);
- console.info('ClientUid for ' + i + ' is:' + AudioRendererChangeInfo.clientUid);
- console.info('Content ' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.content);
- console.info('Stream' + i +' is:' + AudioRendererChangeInfo.rendererInfo.usage);
- console.info('Flag' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.rendererFlags);
- console.info('State for ' + i + ' is:' + AudioRendererChangeInfo.rendererState);
- var devDescriptor = AudioRendererChangeInfo.deviceDescriptors;
- for (let j = 0; j < AudioRendererChangeInfo.deviceDescriptors.length; j++) {
- console.info('Id:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].id);
- console.info('Type:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].deviceType);
- console.info('Role:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].deviceRole);
- console.info('Name:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].name);
- console.info('Address:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].address);
- console.info('SampleRates:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]);
- console.info('ChannelCounts' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]);
- console.info('ChannelMask:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelMasks);
- }
- }
- }
- }).catch((err) => {
- console.log('getCurrentAudioRendererInfoArray :ERROR: ' + err.message);
- });
- ```
+
+ This API can be used to obtain the unique ID of the audio stream, UID of the audio playback client, audio status, and other information about the audio player. Before calling this API, a third-party application must have the **ohos.permission.USE_BLUETOOTH** permission configured, for the device name and device address to be displayed correctly.
+
+ ```js
+ await audioStreamManager.getCurrentAudioRendererInfoArray().then( function (AudioRendererChangeInfoArray) {
+ console.info('######### Get Promise is called ##########');
+ if (AudioRendererChangeInfoArray != null) {
+ for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) {
+ AudioRendererChangeInfo = AudioRendererChangeInfoArray[i];
+ console.info('StreamId for ' + i +' is:' + AudioRendererChangeInfo.streamId);
+ console.info('ClientUid for ' + i + ' is:' + AudioRendererChangeInfo.clientUid);
+ console.info('Content ' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.content);
+ console.info('Stream' + i +' is:' + AudioRendererChangeInfo.rendererInfo.usage);
+ console.info('Flag' + i + ' is:' + AudioRendererChangeInfo.rendererInfo.rendererFlags);
+ console.info('State for ' + i + ' is:' + AudioRendererChangeInfo.rendererState);
+ var devDescriptor = AudioRendererChangeInfo.deviceDescriptors;
+ for (let j = 0; j < AudioRendererChangeInfo.deviceDescriptors.length; j++) {
+ console.info('Id:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].id);
+ console.info('Type:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].deviceType);
+ console.info('Role:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].deviceRole);
+ console.info('Name:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].name);
+ console.info('Address:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].address);
+ console.info('SampleRates:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]);
+ console.info('ChannelCounts' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]);
+ console.info('ChannelMask:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelMasks);
+ }
+ }
+ }
+ }).catch((err) => {
+ console.log('getCurrentAudioRendererInfoArray :ERROR: ' + err.message);
+ });
+ ```
7. (Optional) Call **getCurrentAudioCapturerInfoArray()** to obtain information about the current audio capturer.
-This API can be used to obtain the unique ID of the audio stream, UID of the audio recording client, audio status, and other information about the audio capturer. Before calling this API, a third-party application must have the **ohos.permission.USE_BLUETOOTH** permission configured, for the device name and device address to be displayed correctly.
-
- ```js
- await audioStreamManager.getCurrentAudioCapturerInfoArray().then( function (AudioCapturerChangeInfoArray) {
- console.info('getCurrentAudioCapturerInfoArray: **** Get Promise Called ****');
- if (AudioCapturerChangeInfoArray != null) {
- for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) {
- console.info('StreamId for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].streamId);
- console.info('ClientUid for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].clientUid);
- console.info('Source for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.source);
- console.info('Flag ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags);
- console.info('State for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerState);
- var devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors;
- for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) {
- console.info('Id:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id);
- console.info('Type:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType);
- console.info('Role:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole);
- console.info('Name:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name)
- console.info('Address:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address);
- console.info('SampleRates:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]);
- console.info('ChannelCounts' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]);
- console.info('ChannelMask:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks);
- }
- }
- }
- }).catch((err) => {
- console.log('getCurrentAudioCapturerInfoArray :ERROR: ' + err.message);
- });
- ```
+ This API can be used to obtain the unique ID of the audio stream, UID of the audio recording client, audio status, and other information about the audio capturer. Before calling this API, a third-party application must have the **ohos.permission.USE_BLUETOOTH** permission configured, for the device name and device address to be displayed correctly.
+
+ ```js
+ await audioStreamManager.getCurrentAudioCapturerInfoArray().then( function (AudioCapturerChangeInfoArray) {
+ console.info('getCurrentAudioCapturerInfoArray: **** Get Promise Called ****');
+ if (AudioCapturerChangeInfoArray != null) {
+ for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) {
+ console.info('StreamId for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].streamId);
+ console.info('ClientUid for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].clientUid);
+ console.info('Source for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.source);
+ console.info('Flag ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags);
+ console.info('State for ' + i + 'is:' + AudioCapturerChangeInfoArray[i].capturerState);
+ var devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors;
+ for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) {
+ console.info('Id:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id);
+ console.info('Type:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType);
+ console.info('Role:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole);
+ console.info('Name:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name)
+ console.info('Address:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address);
+ console.info('SampleRates:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]);
+ console.info('ChannelCounts' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]);
+ console.info('ChannelMask:' + i + ':' + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks);
+ }
+ }
+ }
+ }).catch((err) => {
+ console.log('getCurrentAudioCapturerInfoArray :ERROR: ' + err.message);
+ });
+ ```
diff --git a/en/application-dev/media/camera.md b/en/application-dev/media/camera.md
index 06439dd049be835cdf5a96a35e2a2a42012ee6f8..25e5e573057661487895bc003c143393287b4829 100644
--- a/en/application-dev/media/camera.md
+++ b/en/application-dev/media/camera.md
@@ -2,7 +2,13 @@
## When to Use
-You can use the camera module to develop basic camera functions, including previewing, photographing, and video recording.
+With the APIs provided by the **Camera** module, you can access and operate camera devices and develop new functions. Common operations include preview, photographing, and video recording. You can also implement flash control, exposure time control, focus mode control, zooming control, and many others.
+
+Before calling camera APIs, be familiar with the following concepts:
+
+- **Static camera capabilities**: A series of parameters used to describe inherent capabilities of a camera, such as orientation and supported resolution.
+- **Physical camera**: An independent camera device. The physical camera ID is a string that uniquely identifies a physical camera.
+- **Asynchronous operation**: To prevent the UI thread from being blocked, most **Camera** calls are asynchronous. Each API provides the callback and promise functions.
## How to Develop
@@ -12,152 +18,298 @@ For details about the APIs, see [Camera Management](../reference/apis/js-apis-ca
### Full-Process Scenario
-The full process includes creating an instance, setting parameters, managing sessions, taking photos, recording videos, and releasing resources.
+The full process includes applying for permissions, creating an instance, setting parameters, managing sessions, taking photos, recording videos, and releasing resources.
+
+#### Applying for Permissions
+
+You must apply for the permission for your application to access the camera device and other functions. The following table lists camera-related permissions.
+
+| Permission| Attribute Value |
+| -------- | ------------------------------ |
+| Camera| ohos.permission.CAMERA |
+| Call recording| ohos.permission.MICROPHONE |
+| Storage| ohos.permission.WRITE_MEDIA |
+| Read| ohos.permission.READ_MEDIA |
+| Location| ohos.permission.MEDIA_LOCATION |
-The method for creating an XComponent is also provided. For details, see [XComponent Creation](#xcomponent-creation).
+The code snippet is as follows:
-For details about the APIs used to save images, see [Image Processing](../reference/apis/js-apis-image.md).
+```typescript
+const PERMISSIONS: Array = [
+ 'ohos.permission.CAMERA',
+ 'ohos.permission.MICROPHONE',
+ 'ohos.permission.MEDIA_LOCATION',
+ 'ohos.permission.READ_MEDIA',
+ 'ohos.permission.WRITE_MEDIA'
+]
+
+function applyPermission() {
+ console.info('[permission] get permission');
+ globalThis.abilityContext.requestPermissionFromUser(PERMISSIONS)
+ }
+```
#### Creating an Instance
-```js
+You must create an independent **CameraManager** instance before performing camera operations. If this operation fails, the camera may be occupied or unusable. If the camera is occupied, wait until it is released. You can call **getSupportedCameras()** to obtain the list of cameras supported by the current device. The list stores all camera IDs of the current device. If the list is not empty, each ID in the list can be used to create an independent camera instance. If the list is empty, no camera is available for the current device and subsequent operations cannot be performed. The camera has preview, shooting, video recording, and metadata streams. You can use **getSupportedOutputCapability()** to obtain the output stream capabilities of the camera and configure them in the **profile** field in **CameraOutputCapability**. The procedure for creating a **CameraManager** instance is as follows:
+
+```typescript
import camera from '@ohos.multimedia.camera'
import image from '@ohos.multimedia.image'
import media from '@ohos.multimedia.media'
-import featureAbility from '@ohos.ability.featureAbility'
// Create a CameraManager object.
-let cameraManager
-await camera.getCameraManager(globalThis.Context, (err, manager) => {
- if (err) {
- console.error('Failed to get the CameraManager instance ${err.message}');
- return;
- }
- console.log('Callback returned with the CameraManager instance');
- cameraManager = manager
-})
-
-// Register a callback to listen for camera status changes and obtain the updated camera status information.
-cameraManager.on('cameraStatus', (cameraStatusInfo) => {
- console.log('camera : ' + cameraStatusInfo.camera.cameraId);
- console.log('status: ' + cameraStatusInfo.status);
-})
+context: any = getContext(this)
+let cameraManager = await camera.getCameraManager(this.context)
+if (!cameraManager) {
+ console.error('Failed to get the CameraManager instance');
+}
// Obtain the camera list.
-let cameraArray
-await cameraManager.getCameras((err, cameras) => {
- if (err) {
- console.error('Failed to get the cameras. ${err.message}');
- return;
- }
- console.log('Callback returned with an array of supported cameras: ' + cameras.length);
- cameraArray = cameras
-})
+let cameraArray = await cameraManager.getSupportedCameras()
+if (!cameraArray) {
+ console.error('Failed to get the cameras');
+}
-for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex++) {
- console.log('cameraId : ' + cameraArray[cameraIndex].cameraId) // Obtain the camera ID.
- console.log('cameraPosition : ' + cameraArray[cameraIndex].cameraPosition) // Obtain the camera position.
- console.log('cameraType : ' + cameraArray[cameraIndex].cameraType) // Obtain the camera type.
- console.log('connectionType : ' + cameraArray[cameraIndex].connectionType) // Obtain the camera connection type.
+for (let index = 0; index < cameraArray.length; index++) {
+ console.log('cameraId : ' + cameraArray[index].cameraId) // Obtain the camera ID.
+ console.log('cameraPosition : ' + cameraArray[index].cameraPosition) // Obtain the camera position.
+ console.log('cameraType : ' + cameraArray[index].cameraType) // Obtain the camera type.
+ console.log('connectionType : ' + cameraArray[index].connectionType) // Obtain the camera connection type.
}
// Create a camera input stream.
-let cameraInput
-await cameraManager.createCameraInput(cameraArray[0].cameraId).then((input) => {
- console.log('Promise returned with the CameraInput instance');
- cameraInput = input
-})
+let cameraInput = await cameraManager.createCameraInput(cameraArray[0])
+
+// Obtain the output stream capabilities supported by the camera.
+let cameraOutputCap = await cameraManager.getSupportedOutputCapability(cameraArray[0]);
+if (!cameraOutputCap) {
+ console.error("outputCapability outputCapability == null || undefined")
+} else {
+ console.info("outputCapability: " + JSON.stringify(cameraOutputCap));
+}
-// Create a preview output stream.
-let previewOutput
-camera.createPreviewOutput((globalThis.surfaceId), (err, output) => {
- if (err) {
- console.error('Failed to create the PreviewOutput instance. ${err.message}');
- return;
- }
- console.log('Callback returned with previewOutput instance');
- previewOutput = output
-});
+let previewProfilesArray = cameraOutputCap.GetPreviewProfiles();
+if (!previewProfilesArray) {
+ console.error("createOutput previewProfilesArray == null || undefined")
+}
+
+let photoProfilesArray = cameraOutputCap.GetPhotoProfiles();
+if (!photoProfilesArray) {
+ console.error("createOutput photoProfilesArray == null || undefined")
+}
+
+let videoProfilesArray = cameraOutputCap.GetVideoProfiles();
+if (!videoProfilesArray) {
+ console.error("createOutput videoProfilesArray == null || undefined")
+}
+
+let metadataObjectTypesArray = cameraOutputCap.GetSupportedMetadataObjectType();
+if (!metadataObjectTypesArray) {
+ console.error("createOutput metadataObjectTypesArray == null || undefined")
+}
+
+// Create a preview stream. For details about the surfaceId parameter, see the XComponent section. The preview stream is the surface provided by the XComponent.
+let previewOutput = await cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId)
+if (!previewOutput) {
+ console.error("Failed to create the PreviewOutput instance.")
+}
-// Create an ImageReceiver object and set image parameters.
+// Create an ImageReceiver object and set photo parameters. The resolution is set based on the photographing resolutions supported by the current device, which are obtained by photoProfilesArray.
let imageReceiver = await image.createImageReceiver(1920, 1080, 4, 8)
// Obtain the surface ID for displaying the photos.
let photoSurfaceId = await imageReceiver.getReceivingSurfaceId()
// Create a photographing output stream.
-let photoOutput
-camera.createPhotoOutput((photoSurfaceId), (err, output) => {
- if (err) {
- console.error('Failed to create the PhotoOutput instance. ${err.message}');
- return;
- }
- console.log('Callback returned with the PhotoOutput instance.');
- photoOutput = output
-});
+let photoOutput = await cameraManager.createPhotoOutput(photoProfilesArray[0], photoSurfaceId)
+if (!photoOutput) {
+ console.error('Failed to create the PhotoOutput instance.');
+ return;
+}
// Define video recording parameters.
-let videoProfile = {
- audioBitrate : 48000,
- audioChannels : 2,
- audioCodec : 'audio/mp4a-latm',
- audioSampleRate : 48000,
- fileFormat : 'mp4',
- videoBitrate : 48000,
- videoCodec : 'video/mp4v-es',
- videoFrameWidth : 640,
- videoFrameHeight : 480,
- videoFrameRate : 30
-}
let videoConfig = {
- audioSourceType : 1,
- videoSourceType : 0,
- profile : videoProfile,
- url : 'file:///data/media/01.mp4',
- orientationHint : 0,
- location : { latitude : 30, longitude : 130 },
+ audioSourceType: 1,
+ videoSourceType: 1,
+ profile: {
+ audioBitrate: 48000,
+ audioChannels: 2,
+ audioCodec: 'audio/mp4v-es',
+ audioSampleRate: 48000,
+ durationTime: 1000,
+ fileFormat: 'mp4',
+ videoBitrate: 48000,
+ videoCodec: 'video/mp4v-es',
+ videoFrameWidth: 640,
+ videoFrameHeight: 480,
+ videoFrameRate: 30
+ },
+ url: 'file:///data/media/01.mp4',
+ orientationHint: 0,
+ maxSize: 100,
+ maxDuration: 500,
+ rotation: 0
}
// Create a video recording output stream.
let videoRecorder
-await media.createVideoRecorder().then((recorder) => {
+media.createVideoRecorder().then((recorder) => {
console.log('createVideoRecorder called')
videoRecorder = recorder
})
// Set video recording parameters.
-await videoRecorder.prepare(videoConfig)
+videoRecorder.prepare(videoConfig)
// Obtain the surface ID for video recording.
-await videoRecorder.getInputSurface().then((id) => {
+let videoSurfaceId
+videoRecorder.getInputSurface().then((id) => {
console.log('getInputSurface called')
videoSurfaceId = id
})
-```
-For details about how to create a video recorder, see [Video Recording Development](./video-recorder.md).
-```js
+
// Create a VideoOutput object.
-let videoOutput
-camera.createVideoOutput((surfaceId), (err, output) => {
- if (err) {
- console.error('Failed to create the VideoOutput instance. ${err.message}');
- return;
+let videoOutput = await cameraManager.createVideoOutput(videoProfilesArray[0], videoSurfaceId)
+if (!videoOutput) {
+ console.error('Failed to create the videoOutput instance.');
+ return;
+}
+```
+Surfaces must be created in advance for the preview, shooting, and video recording stream. The preview stream is the surface provided by the **XComponent**, the shooting stream is the surface provided by **ImageReceiver**, and the video recording stream is the surface provided by **VideoRecorder**.
+
+**XComponent**
+
+```typescript
+mXComponentController: XComponentController = new XComponentController // Create an XComponentController.
+
+build() {
+ Flex() {
+ XComponent({ // Create an XComponent.
+ id: '',
+ type: 'surface',
+ libraryname: '',
+ controller: this.mXComponentController
+ })
+ .onload(() => { // Set the onload callback.
+ // Set the surface width and height (1920 x 1080). For details about how to set the preview size, see the preview resolutions supported by the current device, which are obtained by previewProfilesArray.
+ this.mXComponentController.setXComponentSurfaceSize({surfaceWidth:1920,surfaceHeight:1080})
+ // Obtain the surface ID.
+ globalThis.surfaceId = mXComponentController.getXComponentSurfaceId()
+ })
+ .width('1920px') // Set the width of the XComponent.
+ .height('1080px') // Set the height of the XComponent.
}
- console.log('Callback returned with the VideoOutput instance');
- videoOutput = output
-});
+}
+```
+
+**ImageReceiver**
+
+```typescript
+function getImageReceiverSurfaceId() {
+ let receiver = image.createImageReceiver(640, 480, 4, 8)
+ console.log(TAG + 'before ImageReceiver check')
+ if (receiver !== undefined) {
+ console.log('ImageReceiver is ok')
+ surfaceId1 = receiver.getReceivingSurfaceId()
+ console.log('ImageReceived id: ' + JSON.stringify(surfaceId1))
+ } else {
+ console.log('ImageReceiver is not ok')
+ }
+ }
+```
+
+**VideoRecorder**
+
+```typescript
+function getVideoRecorderSurface() {
+ await getFd('CameraManager.mp4');
+ mVideoConfig.url = mFdPath;
+ media.createVideoRecorder((err, recorder) => {
+ console.info('Entering create video receiver')
+ mVideoRecorder = recorder
+ console.info('videoRecorder is :' + JSON.stringify(mVideoRecorder))
+ console.info('videoRecorder.prepare called.')
+ mVideoRecorder.prepare(mVideoConfig, (err) => {
+ console.info('videoRecorder.prepare success.')
+ mVideoRecorder.getInputSurface((err, id) => {
+ console.info('getInputSurface called')
+ mVideoSurface = id
+ console.info('getInputSurface surfaceId: ' + JSON.stringify(mVideoSurface))
+ })
+ })
+ })
+ }
+```
+
+#### Managing Sessions
+
+##### Creating a Session
+
+```typescript
+// Create a session.
+let captureSession = await camera.createCaptureSession()
+if (!captureSession) {
+ console.error('Failed to create the CaptureSession instance.');
+ return;
+}
+console.log('Callback returned with the CaptureSession instance.' + session);
+
+// Start configuration for the session.
+await captureSession.beginConfig()
+
+// Add the camera input stream to the session.
+await captureSession.addInput(cameraInput)
+
+// Add the preview input stream to the session.
+await captureSession.addOutput(previewOutput)
+
+// Add the photographing output stream to the session.
+await captureSession.addOutput(photoOutput)
+
+// Commit the session configuration.
+await captureSession.commitConfig()
+
+// Start the session.
+await captureSession.start().then(() => {
+ console.log('Promise returned to indicate the session start success.');
+})
+```
+##### Switching a Session
+
+```typescript
+// Stop the session.
+await captureSession.stop()
+
+// Start configuration for the session.
+await captureSession.beginConfig()
+
+// Remove the photographing output stream from the session.
+await captureSession.removeOutput(photoOutput)
+
+// Add a video recording output stream to the session.
+await captureSession.addOutput(videoOutput)
+
+// Commit the session configuration.
+await captureSession.commitConfig()
+
+// Start the session.
+await captureSession.start().then(() => {
+ console.log('Promise returned to indicate the session start success.');
+})
```
#### Setting Parameters
-```js
+```typescript
// Check whether the camera has flash.
-let flashStatus
-await cameraInput.hasFlash().then((status) => {
- console.log('Promise returned with the flash light support status:' + status);
- flashStatus = status
-})
-if(flashStatus) {
+let flashStatus = await captureSession.hasFlash()
+if (!flashStatus) {
+ console.error('Failed to check whether the device has the flash mode.');
+}
+console.log('Promise returned with the flash light support status:' + flashStatus);
+
+if (flashStatus) {
// Check whether the auto flash mode is supported.
let flashModeStatus
- cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, (err, status) => {
+ captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, async (err, status) => {
if (err) {
console.error('Failed to check whether the flash mode is supported. ${err.message}');
return;
@@ -167,7 +319,7 @@ if(flashStatus) {
})
if(flashModeStatus) {
// Set the flash mode to auto.
- cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, (err) => {
+ captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, async (err) => {
if (err) {
console.error('Failed to set the flash mode ${err.message}');
return;
@@ -179,7 +331,7 @@ if(flashStatus) {
// Check whether the continuous auto focus is supported.
let focusModeStatus
-cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, (err, status) => {
+captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, async (err, status) => {
if (err) {
console.error('Failed to check whether the focus mode is supported. ${err.message}');
return;
@@ -187,9 +339,9 @@ cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, (e
console.log('Callback returned with the focus mode support status: ' + status);
focusModeStatus = status
})
-if(focusModeStatus) {
+if (focusModeStatus) {
// Set the focus mode to continuous auto focus.
- cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, (err) => {
+ captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, async (err) => {
if (err) {
console.error('Failed to set the focus mode ${err.message}');
return;
@@ -199,18 +351,14 @@ if(focusModeStatus) {
}
// Obtain the zoom ratio range supported by the camera.
-let zoomRatioRange
-cameraInput.getZoomRatioRange((err, range) => {
- if (err) {
- console.error('Failed to get the zoom ratio range. ${err.message}');
- return;
- }
- console.log('Callback returned with zoom ratio range: ' + range.length);
- zoomRatioRange = range
-})
+let zoomRatioRange = await captureSession.getZoomRatioRange()
+if (!zoomRatioRange) {
+ console.error('Failed to get the zoom ratio range.');
+ return;
+}
// Set a zoom ratio.
-cameraInput.setZoomRatio(zoomRatioRange[0], (err) => {
+captureSession.setZoomRatio(zoomRatioRange[0], async (err) => {
if (err) {
console.error('Failed to set the zoom ratio value ${err.message}');
return;
@@ -219,139 +367,15 @@ cameraInput.setZoomRatio(zoomRatioRange[0], (err) => {
})
```
-#### Managing Sessions
-
-##### Creating a Session
-
-```js
-// Create a Context object.
-let context = featureAbility.getContext()
-
-// Create a session.
-let captureSession
-await camera.createCaptureSession((context), (err, session) => {
- if (err) {
- console.error('Failed to create the CaptureSession instance. ${err.message}');
- return;
- }
- console.log('Callback returned with the CaptureSession instance.' + session);
- captureSession = session
-});
-
-// Start configuration for the session.
-await captureSession.beginConfig((err) => {
- if (err) {
- console.error('Failed to start the configuration. ${err.message}');
- return;
- }
- console.log('Callback invoked to indicate the begin config success.');
-});
-
-// Add the camera input stream to the session.
-await captureSession.addInput(cameraInput, (err) => {
- if (err) {
- console.error('Failed to add the CameraInput instance. ${err.message}');
- return;
- }
- console.log('Callback invoked to indicate that the CameraInput instance is added.');
-});
-
-// Add the preview input stream to the session.
-await captureSession.addOutput(previewOutput, (err) => {
- if (err) {
- console.error('Failed to add the PreviewOutput instance ${err.message}');
- return;
- }
- console.log('Callback invoked to indicate that the PreviewOutput instance is added.');
-});
-
-// Add the photographing output stream to the session.
-await captureSession.addOutput(photoOutput, (err) => {
- if (err) {
- console.error('Failed to add the PhotoOutput instance ${err.message}');
- return;
- }
- console.log('Callback invoked to indicate that the PhotoOutput instance is added.');
-});
-
-// Commit the session configuration.
-await captureSession.commitConfig((err) => {
- if (err) {
- console.error('Failed to commit the configuration. ${err.message}');
- return;
- }
- console.log('Callback invoked to indicate the commit config success.');
-});
-
-// Start the session.
-await captureSession.start().then(() => {
- console.log('Promise returned to indicate the session start success.');
-})
-```
-
-##### Switching a Session
-
-```js
-// Stop the session.
-await captureSession.stop((err) => {
- if (err) {
- console.error('Failed to stop the session ${err.message}');
- return;
- }
- console.log('Callback invoked to indicate the session stop success.');
-});
-
-// Start configuration for the session.
-await captureSession.beginConfig((err) => {
- if (err) {
- console.error('Failed to start the configuration. ${err.message}');
- return;
- }
- console.log('Callback invoked to indicate the begin config success.');
-});
-
-// Remove the photographing output stream from the session.
-await captureSession.removeOutput(photoOutput, (err) => {
- if (err) {
- console.error('Failed to remove the PhotoOutput instance. ${err.message}');
- return;
- }
- console.log('Callback invoked to indicate that the PhotoOutput instance is removed.');
-});
-
-// Add a video recording output stream to the session.
-await captureSession.addOutput(videoOutput, (err) => {
- if (err) {
- console.error('Failed to add the VideoOutput instance ${err.message}');
- return;
- }
- console.log('Callback invoked to indicate that the VideoOutput instance is added.');
-});
-
-// Commit the session configuration.
-await captureSession.commitConfig((err) => {
- if (err) {
- console.error('Failed to commit the configuration. ${err.message}');
- return;
- }
- console.log('Callback invoked to indicate the commit config success.');
-});
-
-// Start the session.
-await captureSession.start().then(() => {
- console.log('Promise returned to indicate the session start success.');
-})
-```
-
#### Taking Photos
-```js
+```typescript
let settings = {
quality: camera.QualityLevel.QUALITY_LEVEL_HIGH, // Set the image quality to high.
rotation: camera.ImageRotation.ROTATION_0 // Set the image rotation angle to 0.
}
// Use the current photographing settings to take photos.
-photoOutput.capture(settings, (err) => {
+photoOutput.capture(settings, async (err) => {
if (err) {
console.error('Failed to capture the photo ${err.message}');
return;
@@ -362,9 +386,9 @@ photoOutput.capture(settings, (err) => {
#### Recording Videos
-```js
+```typescript
// Start the video recording output stream.
-videoOutput.start((err) => {
+videoOutput.start(async (err) => {
if (err) {
console.error('Failed to start the video output ${err.message}');
return;
@@ -373,17 +397,17 @@ videoOutput.start((err) => {
});
// Start video recording.
-await videoRecorder.start().then(() => {
+videoRecorder.start().then(() => {
console.info('videoRecorder start success');
}
// Stop video recording.
-await videoRecorder.stop().then(() => {
+videoRecorder.stop().then(() => {
console.info('stop success');
}
// Stop the video recording output stream.
-await videoOutput.stop((err) => {
+videoOutput.stop((err) => {
if (err) {
console.error('Failed to stop the video output ${err.message}');
return;
@@ -392,81 +416,34 @@ await videoOutput.stop((err) => {
});
```
+For details about the APIs used for saving photos, see [Image Processing](image.md#using-imagereceiver).
+
#### Releasing Resources
-```js
+```typescript
// Stop the session.
-await captureSession.stop((err) => {
- if (err) {
- console.error('Failed to stop the session ${err.message}');
- return;
- }
- console.log('Callback invoked to indicate the session stop success.');
-});
+captureSession.stop()
+
// Release the camera input stream.
-await cameraInput.release((err) => {
- if (err) {
- console.error('Failed to release the CameraInput instance ${err.message}');
- return;
- }
- console.log('Callback invoked to indicate that the CameraInput instance is released successfully.');
-});
+cameraInput.release()
+
// Release the preview output stream.
-await previewOutput.release((err) => {
- if (err) {
- console.error('Failed to release the PreviewOutput instance ${err.message}');
- return;
- }
- console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.');
-});
+previewOutput.release()
+
// Release the photographing output stream.
-await photoOutput.release((err) => {
- if (err) {
- console.error('Failed to release the PhotoOutput instance ${err.message}');
- return;
- }
- console.log('Callback invoked to indicate that the PhotoOutput instance is released successfully.');
-});
+photoOutput.release()
+
// Release the video recording output stream.
-await videoOutput.release((err) => {
- if (err) {
- console.error('Failed to release the VideoOutput instance ${err.message}');
- return;
- }
- console.log('Callback invoked to indicate that the VideoOutput instance is released successfully.');
-});
+videoOutput.release()
+
// Release the session.
-await captureSession.release((err) => {
- if (err) {
- console.error('Failed to release the CaptureSession instance ${err.message}');
- return;
- }
- console.log('Callback invoked to indicate that the CaptureSession instance is released successfully.');
-});
-```
+captureSession.release()
-#### XComponent Creation
-The surface ID must be obtained for image preview.
+// Set the session to null.
+captureSession = null
+```
-```js
-mXComponentController: XComponentController = new XComponentController // Create an XComponentController.
+## Process Flowchart
-build() {
- Flex() {
- XComponent({ // Create an XComponent.
- id: '',
- type: 'surface',
- libraryname: '',
- controller: this.mXComponentController
- })
- .onload(() => { // Set the onload callback.
- // Set the width and height of the surface to 1920 and 1080, respectively.
- this.mXComponentController.setXComponentSurfaceSize({surfaceWidth:1920,surfaceHeight:1080})
- // Obtain the surface ID.
- globalThis.surfaceId = mXComponentController.getXComponentSurfaceId()
- })
- .width('1920px') // Set the width of the XComponent.
- .height('1080px') // Set the height of the XComponent.
- }
-}
-```
+The following figure shows the process of using the camera.
+![camera_framework process](figures/camera_framework_process.jpg)
diff --git a/en/application-dev/media/figures/camera_framework_process.jpg b/en/application-dev/media/figures/camera_framework_process.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..1207a9a4adb5d5886f9427b07f0ec7d717fc5bf8
Binary files /dev/null and b/en/application-dev/media/figures/camera_framework_process.jpg differ
diff --git a/en/application-dev/media/opensles-capture.md b/en/application-dev/media/opensles-capture.md
index 0d0946ca87256f6409a62b81958a2ad784af8161..4e1775e178db20e01f15ee7a9b8f685a5c47b07b 100644
--- a/en/application-dev/media/opensles-capture.md
+++ b/en/application-dev/media/opensles-capture.md
@@ -1,6 +1,6 @@
# OpenSL ES Audio Recording Development
-## When to Use
+## Introduction
You can use OpenSL ES to develop the audio recording function in OpenHarmony. Currently, only some [OpenSL ES APIs](https://gitee.com/openharmony/third_party_opensles/blob/master/api/1.0.1/OpenSLES.h) are implemented. If an API that has not been implemented is called, **SL_RESULT_FEATURE_UNSUPPORTED** will be returned.
diff --git a/en/application-dev/media/opensles-playback.md b/en/application-dev/media/opensles-playback.md
index 661bf70ca1551964b05b086d7ec0ab25f46c984d..fe89bc9553da3163e1e18ca43922ff99e13c1307 100644
--- a/en/application-dev/media/opensles-playback.md
+++ b/en/application-dev/media/opensles-playback.md
@@ -1,6 +1,6 @@
# OpenSL ES Audio Playback Development
-## When to Use
+## Introduction
You can use OpenSL ES to develop the audio playback function in OpenHarmony. Currently, only some [OpenSL ES APIs](https://gitee.com/openharmony/third_party_opensles/blob/master/api/1.0.1/OpenSLES.h) are implemented. If an API that has not been implemented is called, **SL_RESULT_FEATURE_UNSUPPORTED** will be returned.
@@ -58,7 +58,7 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform
5. Obtain the **bufferQueueItf** instance of the **SL_IID_OH_BUFFERQUEUE** interface.
- ```
+ ```c++
SLOHBufferQueueItf bufferQueueItf;
(*pcmPlayerObject)->GetInterface(pcmPlayerObject, SL_IID_OH_BUFFERQUEUE, &bufferQueueItf);
```
diff --git a/en/application-dev/media/video-playback.md b/en/application-dev/media/video-playback.md
index 6ee5cf660069294f717c5cac614ed707db9f1a8c..b324f19b3cf0f3621bd74809c4f1a2d0b57d0abd 100644
--- a/en/application-dev/media/video-playback.md
+++ b/en/application-dev/media/video-playback.md
@@ -1,17 +1,23 @@
# Video Playback Development
-## When to Use
+## Introduction
-You can use video playback APIs to convert video data into visible signals, play the signals using output devices, and manage playback tasks. This document describes development for the following video playback scenarios: full-process, normal playback, video switching, and loop playback.
+You can use video playback APIs to convert audio data into audible analog signals and play the signals using output devices. You can also manage playback tasks. For example, you can start, suspend, stop playback, release resources, set the volume, seek to a playback position, set the playback speed, and obtain track information. This document describes development for the following video playback scenarios: full-process, normal playback, video switching, and loop playback.
+
+## Working Principles
+
+The following figures show the video playback state transition and the interaction with external modules for video playback.
**Figure 1** Video playback state transition
![en-us_image_video_state_machine](figures/en-us_image_video_state_machine.png)
-**Figure 2** Layer 0 diagram of video playback
+**Figure 2** Interaction with external modules for video playback
![en-us_image_video_player](figures/en-us_image_video_player.png)
+**NOTE**: When a third-party application calls a JS interface provided by the JS interface layer, the framework layer invokes the audio component through the media service of the native framework to output the audio data decoded by the software to the audio HDI. The graphics subsystem outputs the image data decoded by the codec HDI at the hardware interface layer to the display HDI. In this way, video playback is implemented.
+
*Note: Video playback requires hardware capabilities such as display, audio, and codec.*
1. A third-party application obtains a surface ID from the XComponent.
diff --git a/en/application-dev/media/video-recorder.md b/en/application-dev/media/video-recorder.md
index 62e81cf05c384a7cd1a780c562697be046153d05..bef55899bcb51359a6b6d68ef6d7894d70e435ae 100644
--- a/en/application-dev/media/video-recorder.md
+++ b/en/application-dev/media/video-recorder.md
@@ -1,17 +1,27 @@
# Video Recording Development
-## When to Use
+## Introduction
-During video recording, audio and video signals are captured, encoded, and saved to files. You can specify parameters such as the encoding format, encapsulation format, and file path for video recording.
+You can use video recording APIs to capture audio and video signals, encode them, and save them to files. You can start, suspend, resume, and stop recording, and release resources. You can also specify parameters such as the encoding format, encapsulation format, and file path for video recording.
+
+## Working Principles
+
+The following figures show the video recording state transition and the interaction with external modules for video recording.
**Figure 1** Video recording state transition
![en-us_image_video_recorder_state_machine](figures/en-us_image_video_recorder_state_machine.png)
-**Figure 2** Layer 0 diagram of video recording
+**Figure 2** Interaction with external modules for video recording
![en-us_image_video_recorder_zero](figures/en-us_image_video_recorder_zero.png)
+**NOTE**: When a third-party camera application or system camera calls a JS interface provided by the JS interface layer, the framework layer uses the media service of the native framework to invoke the audio component. Through the audio HDI, the audio component captures audio data, encodes the audio data through software, and saves the encoded audio data to a file. The graphics subsystem captures image data through the video HDI, encodes the image data through the video codec HDI, and saves the encoded image data to a file. In this way, video recording is implemented.
+
+## Constraints
+
+Before developing video recording, configure the permissions **ohos.permission.MICROPHONE** and **ohos.permission.CAMERA** for your application. For details about the configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md).
+
## How to Develop
For details about the APIs, see [VideoRecorder in the Media API](../reference/apis/js-apis-media.md#videorecorder9).
@@ -147,3 +157,4 @@ export class VideoRecorderDemo {
}
}
```
+
diff --git a/en/application-dev/napi/Readme-EN.md b/en/application-dev/napi/Readme-EN.md
index bf16d91435bf68ebd6f93a1a52b5f6da35e67169..0030d1d3cceb059a7f0d4d8308b3ae223e8de990 100644
--- a/en/application-dev/napi/Readme-EN.md
+++ b/en/application-dev/napi/Readme-EN.md
@@ -4,6 +4,4 @@
- [Drawing Development](drawing-guidelines.md)
- [Raw File Development](rawfile-guidelines.md)
- [Native Window Development](native-window-guidelines.md)
-- [Using MindSpore Lite for Model Inference](native-window-guidelines.md)
-
-
+- [Using MindSpore Lite for Model Inference](mindspore-lite-guidelines.md)
diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md
index 754d30b06c7dda42dbe16203be2342bf6f70fc2a..a9d34533736558a48cb9415f19e6175b458aee94 100644
--- a/en/application-dev/reference/apis/Readme-EN.md
+++ b/en/application-dev/reference/apis/Readme-EN.md
@@ -125,6 +125,8 @@
- Security
- [@ohos.abilityAccessCtrl](js-apis-abilityAccessCtrl.md)
- [@ohos.privacyManager](js-apis-privacyManager.md)
+ - [@ohos.security.cert](js-apis-cert.md)
+ - [@ohos.security.cryptoFramework]js-apis-cryptoFramework.md)
- [@ohos.security.huks ](js-apis-huks.md)
- [@ohos.userIAM.faceAuth](js-apis-useriam-faceauth.md)
- [@ohos.userIAM.userAuth ](js-apis-useriam-userauth.md)
@@ -146,6 +148,8 @@
- [@ohos.document](js-apis-document.md)
- [@ohos.environment](js-apis-environment.md)
+ - [@ohos.data.fileAccess](js-apis-fileAccess.md)
+ - [@ohos.fileExtensionInfo](js-apis-fileExtensionInfo.md)
- [@ohos.fileio](js-apis-fileio.md)
- [@ohos.filemanagement.userfile_manager](js-apis-userfilemanager.md)
- [@ohos.multimedia.medialibrary](js-apis-medialibrary.md)
@@ -215,6 +219,7 @@
- [@ohos.geolocation](js-apis-geolocation.md)
- [@ohos.multimodalInput.inputConsumer](js-apis-inputconsumer.md)
- [@ohos.multimodalInput.inputDevice](js-apis-inputdevice.md)
+ - [@ohos.multimodalInput.inputDeviceCooperate](js-apis-cooperate.md)
- [@ohos.multimodalInput.inputEvent](js-apis-inputevent.md)
- [@ohos.multimodalInput.inputEventClient](js-apis-inputeventclient.md)
- [@ohos.multimodalInput.inputMonitor](js-apis-inputmonitor.md)
diff --git a/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md b/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md
index f321aca70ed972845f73ca702501e574aeafe5e0..8701a6b80d7d54dc8bf6a30850c3551a741e77ed 100644
--- a/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md
+++ b/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md
@@ -24,7 +24,9 @@ SystemCapability.BundleManager.DistributedBundleFramework
For details, see [Permission Levels](../../security/accesstoken-overview.md#permission-levels).
-## distributedBundle.getRemoteAbilityInfo
+## distributedBundle.getRemoteAbilityInfodeprecated
+
+> This API is deprecated since API version 9. You are advised to use [getRemoteAbilityInfo](js-apis-distributedBundle.md) instead.
getRemoteAbilityInfo(elementName: ElementName, callback: AsyncCallback<RemoteAbilityInfo>): void;
@@ -51,7 +53,9 @@ This is a system API and cannot be called by third-party applications.
-## distributedBundle.getRemoteAbilityInfo
+## distributedBundle.getRemoteAbilityInfodeprecated
+
+> This API is deprecated since API version 9. You are advised to use [getRemoteAbilityInfo](js-apis-distributedBundle.md) instead.
getRemoteAbilityInfo(elementName: ElementName): Promise<RemoteAbilityInfo>
@@ -81,7 +85,9 @@ This is a system API and cannot be called by third-party applications.
| ------------------------------------------------------------ | --------------------------------- |
| Promise\<[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md)> | Promise used to return the remote ability information.|
-## distributedBundle.getRemoteAbilityInfos
+## distributedBundle.getRemoteAbilityInfosdeprecated
+
+> This API is deprecated since API version 9. You are advised to use [getRemoteAbilityInfo](js-apis-distributedBundle.md) instead.
getRemoteAbilityInfos(elementNames: Array<ElementName>, callback: AsyncCallback<Array<RemoteAbilityInfo>>): void;
@@ -104,11 +110,13 @@ This is a system API and cannot be called by third-party applications.
| Name | Type | Mandatory| Description |
| ------------ | ------------------------------------------------------------ | ---- | -------------------------------------------------- |
| elementNames | Array<[ElementName](js-apis-bundle-ElementName.md)> | Yes | **ElementName** array, whose maximum length is 10. |
-| callback | AsyncCallback< Array<[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md)>> | Yes | Callback used to return an array of the remote ability information.|
+| callback | AsyncCallback< Array<[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md)>> | Yes | Callback used to return the remote ability information.|
+
+## distributedBundle.getRemoteAbilityInfosdeprecated
-## distributedBundle.getRemoteAbilityInfos
+> This API is deprecated since API version 9. You are advised to use [getRemoteAbilityInfo](js-apis-distributedBundle.md) instead.
getRemoteAbilityInfos(elementNames: Array<ElementName>): Promise<Array<RemoteAbilityInfo>>
diff --git a/en/application-dev/reference/apis/js-apis-audio.md b/en/application-dev/reference/apis/js-apis-audio.md
index acd9ef20950cd35f4f25d0b63b5e33b4e4021e89..8296185a2866ab0148e68ee56e52eea68e708892 100644
--- a/en/application-dev/reference/apis/js-apis-audio.md
+++ b/en/application-dev/reference/apis/js-apis-audio.md
@@ -21,13 +21,11 @@ import audio from '@ohos.multimedia.audio';
## Constants
-**System API**: This is a system API.
-
-**System capability**: SystemCapability.Multimedia.Audio.Device
-
-| Name | Type | Readable| Writable| Description |
-| ----- | -------------------------- | ---- | ---- | ------------------ |
-| LOCAL_NETWORK_ID9+ | string | Yes | No | Network ID of the local device.|
+| Name | Type | Readable | Writable| Description |
+| --------------------------------------- | ----------| ---- | ---- | ------------------ |
+| LOCAL_NETWORK_ID9+ | string | Yes | No | Network ID of the local device.
This is a system API.
**System capability**: SystemCapability.Multimedia.Audio.Device |
+| DEFAULT_VOLUME_GROUP_ID9+ | number | Yes | No | Default volume group ID.
**System capability**: SystemCapability.Multimedia.Audio.Volume |
+| DEFAULT_INTERRUPT_GROUP_ID9+ | number | Yes | No | Default audio interruption group ID.
**System capability**: SystemCapability.Multimedia.Audio.Interrupt |
**Example**
@@ -35,6 +33,8 @@ import audio from '@ohos.multimedia.audio';
import audio from '@ohos.multimedia.audio';
const localNetworkId = audio.LOCAL_NETWORK_ID;
+const defaultVolumeGroupId = audio.DEFAULT_VOLUME_GROUP_ID;
+const defaultInterruptGroupId = audio.DEFAULT_INTERRUPT_GROUP_ID;
```
## audio.getAudioManager
@@ -53,7 +53,7 @@ Obtains an **AudioManager** instance.
**Example**
```js
-var audioManager = audio.getAudioManager();
+let audioManager = audio.getAudioManager();
```
## audio.createAudioRenderer8+
@@ -75,20 +75,20 @@ Creates an **AudioRenderer** instance. This API uses an asynchronous callback to
```js
import audio from '@ohos.multimedia.audio';
-var audioStreamInfo = {
+let audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_1,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
}
-var audioRendererInfo = {
+let audioRendererInfo = {
content: audio.ContentType.CONTENT_TYPE_SPEECH,
usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION,
rendererFlags: 0
}
-var audioRendererOptions = {
+let audioRendererOptions = {
streamInfo: audioStreamInfo,
rendererInfo: audioRendererInfo
}
@@ -128,25 +128,25 @@ Creates an **AudioRenderer** instance. This API uses a promise to return the res
```js
import audio from '@ohos.multimedia.audio';
-var audioStreamInfo = {
+let audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_1,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
}
-var audioRendererInfo = {
+let audioRendererInfo = {
content: audio.ContentType.CONTENT_TYPE_SPEECH,
usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION,
rendererFlags: 0
}
-var audioRendererOptions = {
+let audioRendererOptions = {
streamInfo: audioStreamInfo,
rendererInfo: audioRendererInfo
}
-var audioRenderer;
+let audioRenderer;
audio.createAudioRenderer(audioRendererOptions).then((data) => {
audioRenderer = data;
console.info('AudioFrameworkRenderLog: AudioRenderer Created : Success : Stream Type: SUCCESS');
@@ -176,19 +176,19 @@ Creates an **AudioCapturer** instance. This API uses an asynchronous callback to
```js
import audio from '@ohos.multimedia.audio';
-var audioStreamInfo = {
+let audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_2,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
}
-var audioCapturerInfo = {
+let audioCapturerInfo = {
source: audio.SourceType.SOURCE_TYPE_MIC,
capturerFlags: 0
}
-var audioCapturerOptions = {
+let audioCapturerOptions = {
streamInfo: audioStreamInfo,
capturerInfo: audioCapturerInfo
}
@@ -230,24 +230,24 @@ Creates an **AudioCapturer** instance. This API uses a promise to return the res
```js
import audio from '@ohos.multimedia.audio';
-var audioStreamInfo = {
+let audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_2,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
}
-var audioCapturerInfo = {
+let audioCapturerInfo = {
source: audio.SourceType.SOURCE_TYPE_MIC,
capturerFlags: 0
}
-var audioCapturerOptions = {
+let audioCapturerOptions = {
streamInfo: audioStreamInfo,
capturerInfo: audioCapturerInfo
}
-var audioCapturer;
+let audioCapturer;
audio.createAudioCapturer(audioCapturerOptions).then((data) => {
audioCapturer = data;
console.info('AudioCapturer Created : Success : Stream Type: SUCCESS');
@@ -264,6 +264,8 @@ Creates a **TonePlayer** instance. This API uses an asynchronous callback to ret
**System capability**: SystemCapability.Multimedia.Audio.Tone
+**System API**: This is a system API.
+
**Parameters**
| Name | Type | Mandatory| Description |
@@ -276,12 +278,12 @@ Creates a **TonePlayer** instance. This API uses an asynchronous callback to ret
```js
import audio from '@ohos.multimedia.audio';
-var audioRendererInfo = {
+let audioRendererInfo = {
"contentType": audio.ContentType.CONTENT_TYPE_MUSIC,
"streamUsage": audio.StreamUsage.STREAM_USAGE_MEDIA,
"rendererFlags": 0
}
-var tonePlayer;
+let tonePlayer;
audio.createTonePlayer(audioRendererInfo, (err, data) => {
console.info(`callback call createTonePlayer: audioRendererInfo: ${audioRendererInfo}`);
@@ -302,6 +304,8 @@ Creates a **TonePlayer** instance. This API uses a promise to return the result.
**System capability**: SystemCapability.Multimedia.Audio.Tone
+**System API**: This is a system API.
+
**Parameters**
| Name | Type | Mandatory| Description |
@@ -319,12 +323,12 @@ Creates a **TonePlayer** instance. This API uses a promise to return the result.
```js
import audio from '@ohos.multimedia.audio';
async function createTonePlayer(){
- var audioRendererInfo = {
+ let audioRendererInfo = {
"contentType": audio.ContentType.CONTENT_TYPE_MUSIC,
"streamUsage": audio.StreamUsage.STREAM_USAGE_MEDIA,
"rendererFlags": 0
}
- let tonePlayer = await audio.createTonePlayer(this.audioRendererInfo);
+ let tonePlayer = await audio.createTonePlayer(audioRendererInfo);
}
```
@@ -340,18 +344,31 @@ Enumerates the audio stream types.
| RINGTONE | 2 | Audio stream for ringtones. |
| MEDIA | 3 | Audio stream for media purpose. |
| VOICE_ASSISTANT8+ | 9 | Audio stream for voice assistant.|
-| ALL9+ | 100 | All public audio streams.
This is a system API and cannot be called by third-party applications.|
+| ALL9+ | 100 | All public audio streams.
This is a system API.|
+
+## InterruptRequestResultType9+
+
+Enumerates the result types of audio interruption requests.
+
+**System capability**: SystemCapability.Multimedia.Audio.Interrupt
+
+**System API**: This is a system API.
+
+| Name | Default Value| Description |
+| ---------------------------- | ------ | ---------- |
+| INTERRUPT_REQUEST_GRANT | 0 | The audio interruption request is accepted.|
+| INTERRUPT_REQUEST_REJECT | 1 | The audio interruption request is denied. There may be a stream with a higher priority.|
## InterruptMode9+
Enumerates the audio interruption modes.
-**System capability**: SystemCapability.Multimedia.Audio.Core
+**System capability**: SystemCapability.Multimedia.Audio.Interrupt
| Name | Default Value| Description |
| ---------------------------- | ------ | ---------- |
-| SHARE_MODE | 0 | Shared mode.|
-| INDEPENDENT_MODE| 1 | Independent mode. |
+| SHARE_MODE | 0 | Shared mode.|
+| INDEPENDENT_MODE | 1 | Independent mode.|
## DeviceFlag
@@ -361,14 +378,13 @@ Enumerates the audio device flags.
| Name | Default Value | Description |
| ------------------------------- | ------ | ------------------------------------------------- |
-| NONE_DEVICES_FLAG9+ | 0 | No device.
This is a system API and cannot be called by third-party applications. |
+| NONE_DEVICES_FLAG9+ | 0 | No device.
This is a system API. |
| OUTPUT_DEVICES_FLAG | 1 | Output device.|
| INPUT_DEVICES_FLAG | 2 | Input device.|
| ALL_DEVICES_FLAG | 3 | All devices.|
-| DISTRIBUTED_OUTPUT_DEVICES_FLAG9+ | 4 | Distributed output device.
This is a system API and cannot be called by third-party applications. |
-| DISTRIBUTED_INPUT_DEVICES_FLAG9+ | 8 | Distributed input device.
This is a system API and cannot be called by third-party applications. |
-| ALL_DISTRIBUTED_DEVICES_FLAG9+ | 12 | Distributed input and output device.
This is a system API and cannot be called by third-party applications. |
-
+| DISTRIBUTED_OUTPUT_DEVICES_FLAG9+ | 4 | Distributed output device.
This is a system API. |
+| DISTRIBUTED_INPUT_DEVICES_FLAG9+ | 8 | Distributed input device.
This is a system API. |
+| ALL_DISTRIBUTED_DEVICES_FLAG9+ | 12 | Distributed input and output device.
This is a system API. |
## DeviceRole
@@ -381,7 +397,6 @@ Enumerates the audio device roles.
| INPUT_DEVICE | 1 | Input role.|
| OUTPUT_DEVICE | 2 | Output role.|
-
## DeviceType
Enumerates the audio device types.
@@ -401,16 +416,15 @@ Enumerates the audio device types.
| USB_HEADSET | 22 | USB Type-C headset. |
| DEFAULT9+ | 1000 | Default device type. |
-## ActiveDeviceType
+## CommunicationDeviceType9+
-Enumerates the active device types.
+Enumerates the device types used for communication.
-**System capability**: SystemCapability.Multimedia.Audio.Device
+**System capability**: SystemCapability.Multimedia.Audio.Communication
-| Name | Default Value| Description |
-| ------------- | ------ | ---------------------------------------------------- |
-| SPEAKER | 2 | Speaker. |
-| BLUETOOTH_SCO | 7 | Bluetooth device using the SCO links.|
+| Name | Default Value| Description |
+| ------------- | ------ | -------------|
+| SPEAKER | 2 | Speaker. |
## AudioRingMode
@@ -426,7 +440,7 @@ Enumerates the ringer modes.
## AudioSampleFormat8+
-Enumerate the audio sample formats.
+Enumerates the audio sample formats.
**System capability**: SystemCapability.Multimedia.Audio.Core
@@ -439,6 +453,22 @@ Enumerate the audio sample formats.
| SAMPLE_FORMAT_S32LE | 3 | Signed 32-bit integer, little endian.
Due to system restrictions, only some devices support this sampling format.|
| SAMPLE_FORMAT_F32LE9+ | 4 | Signed 32-bit integer, little endian.
Due to system restrictions, only some devices support this sampling format.|
+## AudioErrors9+
+
+Enumerates the audio error codes.
+
+**System capability**: SystemCapability.Multimedia.Audio.Core
+
+| Error Message | Error Code | Error Description |
+| ---------------------| --------| ----------------- |
+| ERROR_INVALID_PARAM | 6800101 | Invalid parameter. |
+| ERROR_NO_MEMORY | 6800102 | Memory allocation failure. |
+| ERROR_ILLEGAL_STATE | 6800103 | Unsupported state. |
+| ERROR_UNSUPPORTED | 6800104 | Unsupported parameter value. |
+| ERROR_TIMEOUT | 6800105 | Processing timeout. |
+| ERROR_STREAM_LIMIT | 6800201 | Too many audio streams.|
+| ERROR_SYSTEM | 6800301 | System error. |
+
## AudioChannel8+
Enumerates the audio channels.
@@ -510,18 +540,17 @@ Enumerates the audio stream usage.
| STREAM_USAGE_VOICE_ASSISTANT9+ | 3 | Used for voice assistant.|
| STREAM_USAGE_NOTIFICATION_RINGTONE | 6 | Used for notification.|
-## FocusType9+
+## InterruptRequestType9+
-Enumerates the focus types.
+Enumerates the audio interruption request types.
**System API**: This is a system API.
-**System capability**: SystemCapability.Multimedia.Audio.Core
-
-| Name | Default Value | Description |
-| ---------------------------------- | ------ | ------------------------------- |
-| FOCUS_TYPE_RECORDING | 0 | Other audios will be interrupted in recording scenarios. |
+**System capability**: SystemCapability.Multimedia.Audio.Interrupt
+| Name | Default Value | Description |
+| ---------------------------------- | ------ | ------------------------- |
+| INTERRUPT_REQUEST_TYPE_DEFAULT | 0 | Default type, which can be used to interrupt audio requests. |
## AudioState8+
@@ -588,29 +617,18 @@ Enumerates the hints provided along with audio interruption.
| INTERRUPT_HINT_DUCK | 4 | Ducked the playback. (In ducking, the audio volume is reduced, but not silenced.)|
| INTERRUPT_HINT_UNDUCK8+ | 5 | Unducked the playback. |
-## InterruptActionType
-
-Enumerates the returned event types for audio interruption events.
-
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
-
-| Name | Default Value| Description |
-| -------------- | ------ | ------------------ |
-| TYPE_ACTIVATED | 0 | Focus gain event.|
-| TYPE_INTERRUPT | 1 | Audio interruption event.|
-
## AudioStreamInfo8+
Describes audio stream information.
**System capability**: SystemCapability.Multimedia.Audio.Core
-| Name | Type | Mandatory| Description |
-| ------------ | ---------------------------------------- | ---- | ------------------ |
-| samplingRate | [AudioSamplingRate](#audiosamplingrate8) | Yes | Audio sampling rate.|
-| channels | [AudioChannel](#audiochannel8) | Yes | Number of audio channels.|
-| sampleFormat | [AudioSampleFormat](#audiosampleformat8) | Yes | Audio sample format. |
-| encodingType | [AudioEncodingType](#audioencodingtype8) | Yes | Audio encoding type. |
+| Name | Type | Mandatory| Description |
+| ------------ | ------------------------------------------------- | ---- | ------------------ |
+| samplingRate | [AudioSamplingRate](#audiosamplingrate8) | Yes | Audio sampling rate.|
+| channels | [AudioChannel](#audiochannel8) | Yes | Number of audio channels.|
+| sampleFormat | [AudioSampleFormat](#audiosampleformat8) | Yes | Audio sample format. |
+| encodingType | [AudioEncodingType](#audioencodingtype8) | Yes | Audio encoding type. |
## AudioRendererInfo8+
@@ -624,6 +642,19 @@ Describes audio renderer information.
| usage | [StreamUsage](#streamusage) | Yes | Audio stream usage.|
| rendererFlags | number | Yes | Audio renderer flags.|
+## InterruptResult9+
+
+Describes the audio interruption result.
+
+**System capability**: SystemCapability.Multimedia.Audio.Interrupt
+
+**System API**: This is a system API.
+
+| Name | Type | Mandatory| Description |
+| --------------| -------------------------------------------------------------- | ---- | ---------------- |
+| requestResult | [InterruptRequestResultType](#interruptrequestresulttype9) | Yes | Audio interruption request type.|
+| interruptNode | number | Yes | Node to interrupt.|
+
## AudioRendererOptions8+
Describes audio renderer configurations.
@@ -647,31 +678,6 @@ Describes the interruption event received by the application when playback is in
| forceType | [InterruptForceType](#interruptforcetype9) | Yes | Whether the interruption is taken by the system or to be taken by the application.|
| hintType | [InterruptHint](#interrupthint) | Yes | Hint provided along the interruption. |
-## AudioInterrupt
-
-Describes input parameters of audio interruption events.
-
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
-
-| Name | Type | Mandatory| Description |
-| --------------- | --------------------------- | ---- | ------------------------------------------------------------ |
-| streamUsage | [StreamUsage](#streamusage) | Yes | Audio stream usage. |
-| contentType | [ContentType](#contenttype) | Yes | Audio content type. |
-| pauseWhenDucked | boolean | Yes | Whether audio playback can be paused during audio interruption. The value **true** means that audio playback can be paused during audio interruption, and **false** means the opposite.|
-
-## InterruptAction
-
-Describes the callback invoked for audio interruption or focus gain events.
-
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
-
-| Name | Type | Mandatory| Description |
-| ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ |
-| actionType | [InterruptActionType](#interruptactiontype) | Yes | Returned event type. The value **TYPE_ACTIVATED** means the focus gain event, and **TYPE_INTERRUPT** means the audio interruption event.|
-| type | [InterruptType](#interrupttype) | No | Type of the audio interruption event. |
-| hint | [InterruptHint](#interrupthint) | No | Hint provided along with the audio interruption event. |
-| activated | boolean | No | Whether the focus is gained or released. The value **true** means that the focus is gained or released, and **false** means that the focus fails to be gained or released.|
-
## VolumeEvent8+
Describes the event received by the application when the volume is changed.
@@ -683,24 +689,42 @@ Describes the event received by the application when the volume is changed.
| Name | Type | Mandatory| Description |
| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- |
| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
-| volume | number | Yes | Volume level. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**.|
+| volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**.|
| updateUi | boolean | Yes | Whether to show the volume change in UI. |
| volumeGroupId9+ | number | Yes | Volume group ID. It can be used as an input parameter of **getGroupManager**. |
| networkId9+ | string | Yes | Network ID. |
+## MicStateChangeEvent9+
+
+Describes the event received by the application when the microphone mute status changes.
+
+**System capability**: SystemCapability.Multimedia.Audio.Device
+
+| Name | Type | Mandatory| Description |
+| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- |
+| mute | boolean | Yes | Mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite. |
+
## ConnectType9+
Enumerates the types of connected devices.
**System API**: This is a system API.
-**System capability**: SystemCapability.Multimedia.Audio.Device
+**System capability**: SystemCapability.Multimedia.Audio.Volume
| Name | Default Value| Description |
| :------------------------------ | :----- | :--------------------- |
| CONNECT_TYPE_LOCAL | 1 | Local device. |
| CONNECT_TYPE_DISTRIBUTED | 2 | Distributed device. |
+## VolumeGroupInfos9+
+
+Describes the volume group information. The value is an array of [VolumeGroupInfo](#volumegroupinfo9) and is read-only.
+
+**System API**: This is a system API.
+
+**System capability**: SystemCapability.Multimedia.Audio.Volume
+
## VolumeGroupInfo9+
Describes the volume group information.
@@ -717,26 +741,6 @@ Describes the volume group information.
| groupName9+ | number | Yes | No | Group name.|
| type9+ | [ConnectType](#connecttype9)| Yes | No | Type of the connected device.|
-## VolumeGroupInfos9+
-
-Describes the volume group information. The value is an array of [VolumeGroupInfo](#volumegroupinfo9) and is read-only.
-
-**System API**: This is a system API.
-
-**System capability**: SystemCapability.Multimedia.Audio.Volume
-
-**Example**
-
-```js
-import audio from '@ohos.multimedia.audio';
-
-async function getVolumeGroupInfos(){
- let volumegroupinfos = await audio.getAudioManager().getVolumeGroups(audio.LOCAL_NETWORK_ID);
- console.info('Promise returned to indicate that the volumeGroup list is obtained.'+JSON.stringify(volumegroupinfos))
-}
-getVolumeGroupInfos();
-```
-
## DeviceChangeAction
Describes the device connection status and device information.
@@ -803,889 +807,968 @@ Enumerates the audio scenes.
| Name | Default Value| Description |
| :--------------------- | :----- | :-------------------------------------------- |
| AUDIO_SCENE_DEFAULT | 0 | Default audio scene. |
-| AUDIO_SCENE_RINGING | 1 | Ringing audio scene.
This is a system API and cannot be called by third-party applications.|
-| AUDIO_SCENE_PHONE_CALL | 2 | Phone call audio scene.
This is a system API and cannot be called by third-party applications.|
+| AUDIO_SCENE_RINGING | 1 | Ringing audio scene.
This is a system API.|
+| AUDIO_SCENE_PHONE_CALL | 2 | Phone call audio scene.
This is a system API.|
| AUDIO_SCENE_VOICE_CHAT | 3 | Voice chat audio scene. |
## AudioManager
Implements audio volume and audio device management. Before calling any API in **AudioManager**, you must use [getAudioManager](#audiogetaudiomanager) to create an **AudioManager** instance.
-### getRoutingManager9+
+### setAudioParameter
+
+setAudioParameter(key: string, value: string, callback: AsyncCallback<void>): void
-getRoutingManager(callback: AsyncCallback<AudioRoutingManager>): void
+Sets an audio parameter. This API uses an asynchronous callback to return the result.
-Obtains an **AudioRoutingManager** instance. This API uses an asynchronous callback to return the result.
+This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only.
-**System capability**: SystemCapability.Multimedia.Audio.Device
+**Required permissions**: ohos.permission.MODIFY_AUDIO_SETTINGS
+
+**System capability**: SystemCapability.Multimedia.Audio.Core
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ---------------------------------------------------------------- | ---- | --------------------------------- |
-| callback | AsyncCallback<[AudioRoutingManager](#audioroutingmanager9)> | Yes | Callback used to return the **AudioRoutingManager** instance.|
+| Name | Type | Mandatory| Description |
+| -------- | ------------------------- | ---- | ------------------------ |
+| key | string | Yes | Key of the audio parameter to set. |
+| value | string | Yes | Value of the audio parameter to set. |
+| callback | AsyncCallback<void> | Yes | Callback used to return the result.|
**Example**
+
```js
-audioManager.getRoutingManager((err, callback) => {
+audioManager.setAudioParameter('key_example', 'value_example', (err) => {
if (err) {
- console.error(`Result ERROR: ${err}`);
+ console.error(`Failed to set the audio parameter. ${err}`);
+ return;
}
- console.info('getRoutingManager Callback SUCCESS.');
- var audioRoutingManager;
- audioRoutingManager = callback;
+ console.info('Callback invoked to indicate a successful setting of the audio parameter.');
});
```
-### getRoutingManager9+
+### setAudioParameter
-getRoutingManager(): Promise<AudioRoutingManager>
+setAudioParameter(key: string, value: string): Promise<void>
-Obtains an **AudioRoutingManager** instance. This API uses a promise to return the result.
+Sets an audio parameter. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Device
+This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only.
+
+**Required permissions**: ohos.permission.MODIFY_AUDIO_SETTINGS
+
+**System capability**: SystemCapability.Multimedia.Audio.Core
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | ------ | ---- | ---------------------- |
+| key | string | Yes | Key of the audio parameter to set.|
+| value | string | Yes | Value of the audio parameter to set.|
**Return value**
-| Type | Description |
-| ----------------------------------------------------------- | --------------------------------------- |
-| Promise<[AudioRoutingManager](#audioroutingmanager9)> | Promise used to return the **AudioRoutingManager** instance.|
+| Type | Description |
+| ------------------- | ------------------------------- |
+| Promise<void> | Promise used to return the result.|
**Example**
+
```js
-var audioManager = audio.getAudioManager();
-async function getRoutingManager(){
- await audioManager.getRoutingManager().then((value) => {
- var routingManager = value;
- console.info('getRoutingManager Promise SUCCESS.');
- }).catch((err) => {
- console.error(`Result ERROR: ${err}`);
- });
-}
+audioManager.setAudioParameter('key_example', 'value_example').then(() => {
+ console.info('Promise returned to indicate a successful setting of the audio parameter.');
+});
```
-### setVolume
-
-setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback<void>): void
+### getAudioParameter
-Sets the volume for a stream. This API uses an asynchronous callback to return the result.
+getAudioParameter(key: string, callback: AsyncCallback<string>): void
-**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY
+Obtains the value of an audio parameter. This API uses an asynchronous callback to return the result.
-This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**.
+This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only.
-**System capability**: SystemCapability.Multimedia.Audio.Volume
+**System capability**: SystemCapability.Multimedia.Audio.Core
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- |
-| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
-| volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**.|
-| callback | AsyncCallback<void> | Yes | Callback used to return the result. |
+| Name | Type | Mandatory| Description |
+| -------- | --------------------------- | ---- | ---------------------------- |
+| key | string | Yes | Key of the audio parameter whose value is to be obtained. |
+| callback | AsyncCallback<string> | Yes | Callback used to return the value of the audio parameter.|
**Example**
```js
-audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => {
+audioManager.getAudioParameter('key_example', (err, value) => {
if (err) {
- console.error(`Failed to set the volume. ${err}`);
+ console.error(`Failed to obtain the value of the audio parameter. ${err}`);
return;
}
- console.info('Callback invoked to indicate a successful volume setting.');
+ console.info(`Callback invoked to indicate that the value of the audio parameter is obtained ${value}.`);
});
```
-### setVolume
-
-setVolume(volumeType: AudioVolumeType, volume: number): Promise<void>
+### getAudioParameter
-Sets the volume for a stream. This API uses a promise to return the result.
+getAudioParameter(key: string): Promise<string>
-**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY
+Obtains the value of an audio parameter. This API uses a promise to return the result.
-This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**.
+This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only.
-**System capability**: SystemCapability.Multimedia.Audio.Volume
+**System capability**: SystemCapability.Multimedia.Audio.Core
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- |
-| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
-| volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**.|
+| Name| Type | Mandatory| Description |
+| ------ | ------ | ---- | ---------------------- |
+| key | string | Yes | Key of the audio parameter whose value is to be obtained.|
**Return value**
-| Type | Description |
-| ------------------- | ----------------------------- |
-| Promise<void> | Promise used to return the result.|
+| Type | Description |
+| --------------------- | ----------------------------------- |
+| Promise<string> | Promise used to return the value of the audio parameter.|
**Example**
```js
-audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => {
- console.info('Promise returned to indicate a successful volume setting.');
+audioManager.getAudioParameter('key_example').then((value) => {
+ console.info(`Promise returned to indicate that the value of the audio parameter is obtained ${value}.`);
});
```
-### getVolume
+### setAudioScene8+
-getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void
+setAudioScene\(scene: AudioScene, callback: AsyncCallback\): void
-Obtains the volume of a stream. This API uses an asynchronous callback to return the result.
+Sets an audio scene. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Volume
+**System API**: This is a system API.
+
+**System capability**: SystemCapability.Multimedia.Audio.Communication
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ----------------------------------- | ---- | ------------------ |
-| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
-| callback | AsyncCallback<number> | Yes | Callback used to return the volume.|
+| Name | Type | Mandatory| Description |
+| :------- | :----------------------------------- | :--- | :------------------- |
+| scene | AudioScene | Yes | Audio scene to set. |
+| callback | AsyncCallback | Yes | Callback used to return the result.|
**Example**
```js
-audioManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => {
+let audioManager = audio.getAudioManager();
+audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL, (err) => {
if (err) {
- console.error(`Failed to obtain the volume. ${err}`);
+ console.error(`Failed to set the audio scene mode. ${err}`);
return;
}
- console.info('Callback invoked to indicate that the volume is obtained.');
+ console.info('Callback invoked to indicate a successful setting of the audio scene mode.');
});
```
-### getVolume
+### setAudioScene8+
-getVolume(volumeType: AudioVolumeType): Promise<number>
+setAudioScene\(scene: AudioScene\): Promise
-Obtains the volume of a stream. This API uses a promise to return the result.
+Sets an audio scene. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Volume
+**System API**: This is a system API.
+
+**System capability**: SystemCapability.Multimedia.Audio.Communication
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ----------------------------------- | ---- | ------------ |
-| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.|
+| Name| Type | Mandatory| Description |
+| :----- | :----------------------------------- | :--- | :------------- |
+| scene | AudioScene | Yes | Audio scene to set.|
**Return value**
-| Type | Description |
-| --------------------- | ------------------------- |
-| Promise<number> | Promise used to return the volume.|
+| Type | Description |
+| :------------- | :------------------- |
+| Promise | Promise used to return the result.|
**Example**
```js
-audioManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => {
- console.info(`Promise returned to indicate that the volume is obtained ${value} .`);
+let audioManager = audio.getAudioManager();
+audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL).then(() => {
+ console.info('Promise returned to indicate a successful setting of the audio scene mode.');
+}).catch ((err) => {
+ console.error(`Failed to set the audio scene mode ${err}`);
});
```
-### getMinVolume
+### getAudioScene8+
-getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void
+getAudioScene\(callback: AsyncCallback\): void
-Obtains the minimum volume allowed for a stream. This API uses an asynchronous callback to return the result.
+Obtains the audio scene. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Volume
+**System capability**: SystemCapability.Multimedia.Audio.Communication
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ----------------------------------- | ---- | ------------------ |
-| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
-| callback | AsyncCallback<number> | Yes | Callback used to return the minimum volume.|
-
-**Example**
+| Name | Type | Mandatory| Description |
+| :------- | :-------------------------------------------------- | :--- | :--------------------------- |
+| callback | AsyncCallback<AudioScene> | Yes | Callback used to return the audio scene.|
+
+**Example**
```js
-audioManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => {
+let audioManager = audio.getAudioManager();
+audioManager.getAudioScene((err, value) => {
if (err) {
- console.error(`Failed to obtain the minimum volume. ${err}`);
+ console.error(`Failed to obtain the audio scene mode. ${err}`);
return;
}
- console.info(`Callback invoked to indicate that the minimum volume is obtained. ${value}`);
+ console.info(`Callback invoked to indicate that the audio scene mode is obtained ${value}.`);
});
```
-### getMinVolume
-
-getMinVolume(volumeType: AudioVolumeType): Promise<number>
-
-Obtains the minimum volume allowed for a stream. This API uses a promise to return the result.
+### getAudioScene8+
-**System capability**: SystemCapability.Multimedia.Audio.Volume
+getAudioScene\(\): Promise
-**Parameters**
+Obtains the audio scene. This API uses a promise to return the result.
-| Name | Type | Mandatory| Description |
-| ---------- | ----------------------------------- | ---- | ------------ |
-| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.|
+**System capability**: SystemCapability.Multimedia.Audio.Communication
**Return value**
-| Type | Description |
-| --------------------- | ------------------------- |
-| Promise<number> | Promise used to return the minimum volume.|
+| Type | Description |
+| :-------------------------------------------- | :--------------------------- |
+| Promise<AudioScene> | Promise used to return the audio scene.|
**Example**
```js
-audioManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => {
- console.info(`Promised returned to indicate that the minimum volume is obtained. ${value}`);
+let audioManager = audio.getAudioManager();
+audioManager.getAudioScene().then((value) => {
+ console.info(`Promise returned to indicate that the audio scene mode is obtained ${value}.`);
+}).catch ((err) => {
+ console.error(`Failed to obtain the audio scene mode ${err}`);
});
```
-### getMaxVolume
+### getVolumeManager9+
-getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void
+getVolumeManager(): AudioVolumeManager
-Obtains the maximum volume allowed for a stream. This API uses an asynchronous callback to return the result.
+Obtains an **AudioVolumeManager** instance.
**System capability**: SystemCapability.Multimedia.Audio.Volume
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| ---------- | ----------------------------------- | ---- | ---------------------- |
-| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
-| callback | AsyncCallback<number> | Yes | Callback used to return the maximum volume.|
-
**Example**
```js
-audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => {
- if (err) {
- console.error(`Failed to obtain the maximum volume. ${err}`);
- return;
- }
- console.info(`Callback invoked to indicate that the maximum volume is obtained. ${value}`);
-});
+let audioVolumeManager = audioManager.getVolumeManager();
```
-### getMaxVolume
+### getStreamManager9+
-getMaxVolume(volumeType: AudioVolumeType): Promise<number>
+getStreamManager(): AudioStreamManager
-Obtains the maximum volume allowed for a stream. This API uses a promise to return the result.
+Obtains an **AudioStreamManager** instance.
-**System capability**: SystemCapability.Multimedia.Audio.Volume
+**System capability**: SystemCapability.Multimedia.Audio.Core
-**Parameters**
+**Example**
-| Name | Type | Mandatory| Description |
-| ---------- | ----------------------------------- | ---- | ------------ |
-| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.|
+```js
+let audioStreamManager = audioManager.getStreamManager();
+```
-**Return value**
+### getRoutingManager9+
-| Type | Description |
-| --------------------- | ----------------------------- |
-| Promise<number> | Promise used to return the maximum volume.|
+getRoutingManager(): AudioRoutingManager
+
+Obtains an **AudioRoutingManager** instance.
+
+**System capability**: SystemCapability.Multimedia.Audio.Device
**Example**
```js
-audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => {
- console.info('Promised returned to indicate that the maximum volume is obtained.');
-});
+let audioRoutingManager = audioManager.getRoutingManager();
```
-### mute
+## AudioVolumeManager9+
-mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void>): void
+Implements audio volume management. Before calling an API in **AudioVolumeManager**, you must use [getVolumeManager](#getvolumemanager9) to obtain an **AudioVolumeManager** instance.
-Mutes or unmutes a stream. This API uses an asynchronous callback to return the result.
+### getVolumeGroupInfos9+
-**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY
+getVolumeGroupInfos(networkId: string, callback: AsyncCallback\): void
-This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**.
+Obtains the volume groups. This API uses an asynchronous callback to return the result.
+
+**System API**: This is a system API.
**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ----------------------------------- | ---- | ------------------------------------- |
-| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
-| mute | boolean | Yes | Mute status to set. The value **true** means to mute the stream, and **false** means the opposite.|
-| callback | AsyncCallback<void> | Yes | Callback used to return the result. |
+| Name | Type | Mandatory| Description |
+| ---------- | ------------------------------------------------------------ | ---- | -------------------- |
+| networkId | string | Yes | Network ID of the device. The network ID of the local device is **audio.LOCAL_NETWORK_ID**. |
+| callback | AsyncCallback<[VolumeGroupInfos](#volumegroupinfos9)> | Yes | Callback used to return the volume group information array.|
**Example**
-
```js
-audioManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => {
+audioVolumeManager.getVolumeGroupInfos(audio.LOCAL_NETWORK_ID, (err, value) => {
if (err) {
- console.error(`Failed to mute the stream. ${err}`);
+ console.error(`Failed to obtain the volume group infos list. ${err}`);
return;
}
- console.info('Callback invoked to indicate that the stream is muted.');
+ console.info('Callback invoked to indicate that the volume group infos list is obtained.');
});
```
-### mute
-
-mute(volumeType: AudioVolumeType, mute: boolean): Promise<void>
+### getVolumeGroupInfos9+
-Mutes or unmutes a stream. This API uses a promise to return the result.
+getVolumeGroupInfos(networkId: string\): Promise
-**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY
+Obtains the volume groups. This API uses a promise to return the result.
-This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**.
+**System API**: This is a system API.
**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ----------------------------------- | ---- | ------------------------------------- |
-| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
-| mute | boolean | Yes | Mute status to set. The value **true** means to mute the stream, and **false** means the opposite.|
+| Name | Type | Mandatory| Description |
+| ---------- | ------------------| ---- | -------------------- |
+| networkId | string | Yes | Network ID of the device. The network ID of the local device is **audio.LOCAL_NETWORK_ID**. |
**Return value**
| Type | Description |
| ------------------- | ----------------------------- |
-| Promise<void> | Promise used to return the result.|
+| Promise<[VolumeGroupInfos](#volumegroupinfos9)> | Volume group information array.|
**Example**
-
```js
-audioManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => {
- console.info('Promise returned to indicate that the stream is muted.');
-});
+async function getVolumeGroupInfos(){
+ let volumegroupinfos = await audio.getAudioManager().getVolumeManager().getVolumeGroupInfos(audio.LOCAL_NETWORK_ID);
+ console.info('Promise returned to indicate that the volumeGroup list is obtained.'+JSON.stringify(volumegroupinfos))
+}
```
+### getVolumeGroupManager9+
-### isMute
-
-isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void
+getVolumeGroupManager(groupId: number, callback: AsyncCallback\): void
-Checks whether a stream is muted. This API uses an asynchronous callback to return the result.
+Obtains the audio group manager. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ----------------------------------- | ---- | ----------------------------------------------- |
-| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
-| callback | AsyncCallback<boolean> | Yes | Callback used to return the mute status of the stream. The value **true** means that the stream is muted, and **false** means the opposite.|
+| Name | Type | Mandatory| Description |
+| ---------- | ------------------------------------------------------------ | ---- | -------------------- |
+| groupId | number | Yes | Volume group ID. |
+| callback | AsyncCallback< [AudioVolumeGroupManager](#audiovolumegroupmanager9) > | Yes | Callback used to return the audio group manager.|
**Example**
```js
-audioManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => {
+let groupid = audio.DEFAULT_VOLUME_GROUP_ID;
+audioVolumeManager.getVolumeGroupManager(groupid, (err, value) => {
if (err) {
- console.error(`Failed to obtain the mute status. ${err}`);
+ console.error(`Failed to obtain the volume group infos list. ${err}`);
return;
}
- console.info(`Callback invoked to indicate that the mute status of the stream is obtained. ${value}`);
+ console.info('Callback invoked to indicate that the volume group infos list is obtained.');
});
-```
+```
-### isMute
+### getVolumeGroupManager9+
-isMute(volumeType: AudioVolumeType): Promise<boolean>
+getVolumeGroupManager(groupId: number\): Promise
-Checks whether a stream is muted. This method uses a promise to return the result.
+Obtains the audio group manager. This API uses a promise to return the result.
**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ----------------------------------- | ---- | ------------ |
-| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.|
+| Name | Type | Mandatory| Description |
+| ---------- | ---------------------------------------- | ---- | ---------------- |
+| groupId | number | Yes | Volume group ID. |
**Return value**
-| Type | Description |
-| ---------------------- | ------------------------------------------------------ |
-| Promise<boolean> | Promise used to return the mute status of the stream. The value **true** means that the stream is muted, and **false** means the opposite.|
+| Type | Description |
+| ------------------- | ----------------------------- |
+| Promise< [AudioVolumeGroupManager](#audiovolumegroupmanager9) > | Promise used to return the audio group manager.|
**Example**
```js
-audioManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => {
- console.info(`Promise returned to indicate that the mute status of the stream is obtained ${value}.`);
-});
+let groupid = audio.DEFAULT_VOLUME_GROUP_ID;
+let audioVolumeGroupManager = await audioVolumeManager.getVolumeGroupManager(groupid);
+console.info('Callback invoked to indicate that the volume group infos list is obtained.');
```
-### isActive
+### on('volumeChange')9+
-isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void
+on(type: 'volumeChange', callback: Callback\): void
-Checks whether a stream is active. This API uses an asynchronous callback to return the result.
+Subscribes to system volume change events. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ----------------------------------- | ---- | ------------------------------------------------- |
-| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
-| callback | AsyncCallback<boolean> | Yes | Callback used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite.|
+| Name | Type | Mandatory| Description |
+| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ |
+| type | string | Yes | Event type. The value **'volumeChange'** means the system volume change event, which is triggered when the system volume changes.|
+| callback | Callback<[VolumeEvent](#volumeevent8)> | Yes | Callback used to return the system volume change event. |
+
+**Error codes**
+
+For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md).
+
+| ID| Error Message|
+| ------- | --------------------------------------------|
+| 6800101 | if input parameter value error. |
**Example**
```js
-audioManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => {
- if (err) {
- console.error(`Failed to obtain the active status of the stream. ${err}`);
- return;
- }
- console.info(`Callback invoked to indicate that the active status of the stream is obtained ${value}.`);
+audioVolumeManager.on('volumeChange', (volumeEvent) => {
+ console.info(`VolumeType of stream: ${volumeEvent.volumeType} `);
+ console.info(`Volume level: ${volumeEvent.volume} `);
+ console.info(`Whether to updateUI: ${volumeEvent.updateUi} `);
});
```
-### isActive
+## AudioVolumeGroupManager9+
-isActive(volumeType: AudioVolumeType): Promise<boolean>
+Manages the volume of an audio group. Before calling any API in **AudioVolumeGroupManager**, you must use [getVolumeGroupManager](#getvolumegroupmanager9) to obtain an **AudioVolumeGroupManager** instance.
-Checks whether a stream is active. This method uses a promise to return the result.
+**System API**: This is a system API.
**System capability**: SystemCapability.Multimedia.Audio.Volume
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| ---------- | ----------------------------------- | ---- | ------------ |
-| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.|
-
-**Return value**
-
-| Type | Description |
-| ---------------------- | -------------------------------------------------------- |
-| Promise<boolean> | Promise used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite.|
-
-**Example**
-
-```js
-audioManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => {
- console.info(`Promise returned to indicate that the active status of the stream is obtained ${value}.`);
-});
-```
-
-### setRingerMode
+### setVolume9+
-setRingerMode(mode: AudioRingMode, callback: AsyncCallback<void>): void
+setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback<void>): void
-Sets the ringer mode. This API uses an asynchronous callback to return the result.
+Sets the volume for a stream. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY
-This permission is required only for muting or unmuting the ringer.
+This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**.
-**System capability**: SystemCapability.Multimedia.Audio.Communication
+**System API**: This is a system API.
+
+**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | ------------------------------- | ---- | ------------------------ |
-| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode. |
-| callback | AsyncCallback<void> | Yes | Callback used to return the result.|
+| Name | Type | Mandatory| Description |
+| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- |
+| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
+| volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**.|
+| callback | AsyncCallback<void> | Yes | Callback used to return the result. |
**Example**
```js
-audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => {
+audioVolumeGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => {
if (err) {
- console.error(`Failed to set the ringer mode. ${err}`);
+ console.error(`Failed to set the volume. ${err}`);
return;
}
- console.info('Callback invoked to indicate a successful setting of the ringer mode.');
+ console.info('Callback invoked to indicate a successful volume setting.');
});
```
-### setRingerMode
+### setVolume9+
-setRingerMode(mode: AudioRingMode): Promise<void>
+setVolume(volumeType: AudioVolumeType, volume: number): Promise<void>
-Sets the ringer mode. This API uses a promise to return the result.
+Sets the volume for a stream. This API uses a promise to return the result.
**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY
-This permission is required only for muting or unmuting the ringer.
+This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**.
-**System capability**: SystemCapability.Multimedia.Audio.Communication
+**System API**: This is a system API.
+
+**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
-| Name| Type | Mandatory| Description |
-| ------ | ------------------------------- | ---- | -------------- |
-| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode.|
+| Name | Type | Mandatory| Description |
+| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- |
+| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
+| volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**.|
**Return value**
-| Type | Description |
-| ------------------- | ------------------------------- |
+| Type | Description |
+| ------------------- | ----------------------------- |
| Promise<void> | Promise used to return the result.|
**Example**
```js
-audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => {
- console.info('Promise returned to indicate a successful setting of the ringer mode.');
+audioVolumeGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => {
+ console.info('Promise returned to indicate a successful volume setting.');
});
```
+### getVolume9+
-### getRingerMode
-
-getRingerMode(callback: AsyncCallback<AudioRingMode>): void
+getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void
-Obtains the ringer mode. This API uses an asynchronous callback to return the result.
+Obtains the volume of a stream. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Communication
+**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | ---------------------------------------------------- | ---- | ------------------------ |
-| callback | AsyncCallback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the ringer mode.|
-
-**Example**
+| Name | Type | Mandatory| Description |
+| ---------- | ----------------------------------- | ---- | ------------------ |
+| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
+| callback | AsyncCallback<number> | Yes | Callback used to return the volume.|
+
+**Example**
```js
-audioManager.getRingerMode((err, value) => {
+audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => {
if (err) {
- console.error(`Failed to obtain the ringer mode. ${err}`);
+ console.error(`Failed to obtain the volume. ${err}`);
return;
}
- console.info(`Callback invoked to indicate that the ringer mode is obtained ${value}.`);
+ console.info('Callback invoked to indicate that the volume is obtained.');
});
```
+### getVolume9+
-### getRingerMode
+getVolume(volumeType: AudioVolumeType): Promise<number>
-getRingerMode(): Promise<AudioRingMode>
+Obtains the volume of a stream. This API uses a promise to return the result.
-Obtains the ringer mode. This API uses a promise to return the result.
+**System capability**: SystemCapability.Multimedia.Audio.Volume
-**System capability**: SystemCapability.Multimedia.Audio.Communication
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ---------- | ----------------------------------- | ---- | ------------ |
+| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.|
**Return value**
-| Type | Description |
-| ---------------------------------------------- | ------------------------------- |
-| Promise<[AudioRingMode](#audioringmode)> | Promise used to return the ringer mode.|
+| Type | Description |
+| --------------------- | ------------------------- |
+| Promise<number> | Promise used to return the volume.|
**Example**
```js
-audioManager.getRingerMode().then((value) => {
- console.info(`Promise returned to indicate that the ringer mode is obtained ${value}.`);
+audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => {
+ console.info(`Promise returned to indicate that the volume is obtained ${value}.`);
});
```
-### setAudioParameter
-
-setAudioParameter(key: string, value: string, callback: AsyncCallback<void>): void
-
-Sets an audio parameter. This API uses an asynchronous callback to return the result.
+### getMinVolume9+
-This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only.
+getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void
-**Required permissions**: ohos.permission.MODIFY_AUDIO_SETTINGS
+Obtains the minimum volume allowed for a stream. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Core
+**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | ------------------------- | ---- | ------------------------ |
-| key | string | Yes | Key of the audio parameter to set. |
-| value | string | Yes | Value of the audio parameter to set. |
-| callback | AsyncCallback<void> | Yes | Callback used to return the result.|
+| Name | Type | Mandatory| Description |
+| ---------- | ----------------------------------- | ---- | ------------------ |
+| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
+| callback | AsyncCallback<number> | Yes | Callback used to return the minimum volume.|
**Example**
```js
-audioManager.setAudioParameter('key_example', 'value_example', (err) => {
+audioVolumeGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => {
if (err) {
- console.error(`Failed to set the audio parameter. ${err}`);
+ console.error(`Failed to obtain the minimum volume. ${err}`);
return;
}
- console.info('Callback invoked to indicate a successful setting of the audio parameter.');
+ console.info(`Callback invoked to indicate that the minimum volume is obtained. ${value}`);
});
```
-### setAudioParameter
-
-setAudioParameter(key: string, value: string): Promise<void>
-
-Sets an audio parameter. This API uses a promise to return the result.
+### getMinVolume9+
-This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only.
+getMinVolume(volumeType: AudioVolumeType): Promise<number>
-**Required permissions**: ohos.permission.MODIFY_AUDIO_SETTINGS
+Obtains the minimum volume allowed for a stream. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Core
+**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
-| Name| Type | Mandatory| Description |
-| ------ | ------ | ---- | ---------------------- |
-| key | string | Yes | Key of the audio parameter to set.|
-| value | string | Yes | Value of the audio parameter to set.|
+| Name | Type | Mandatory| Description |
+| ---------- | ----------------------------------- | ---- | ------------ |
+| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.|
**Return value**
-| Type | Description |
-| ------------------- | ------------------------------- |
-| Promise<void> | Promise used to return the result.|
+| Type | Description |
+| --------------------- | ------------------------- |
+| Promise<number> | Promise used to return the minimum volume.|
**Example**
```js
-audioManager.setAudioParameter('key_example', 'value_example').then(() => {
- console.info('Promise returned to indicate a successful setting of the audio parameter.');
+audioVolumeGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => {
+ console.info(`Promised returned to indicate that the minimum volume is obtained ${value}.`);
});
```
-### getAudioParameter
-
-getAudioParameter(key: string, callback: AsyncCallback<string>): void
+### getMaxVolume9+
-Obtains the value of an audio parameter. This API uses an asynchronous callback to return the result.
+getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void
-This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only.
+Obtains the maximum volume allowed for a stream. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Core
+**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | --------------------------- | ---- | ---------------------------- |
-| key | string | Yes | Key of the audio parameter whose value is to be obtained. |
-| callback | AsyncCallback<string> | Yes | Callback used to return the value of the audio parameter.|
+| Name | Type | Mandatory| Description |
+| ---------- | ----------------------------------- | ---- | ---------------------- |
+| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
+| callback | AsyncCallback<number> | Yes | Callback used to return the maximum volume.|
**Example**
```js
-audioManager.getAudioParameter('key_example', (err, value) => {
+audioVolumeGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => {
if (err) {
- console.error(`Failed to obtain the value of the audio parameter. ${err}`);
+ console.error(`Failed to obtain the maximum volume. ${err}`);
return;
}
- console.info(`Callback invoked to indicate that the value of the audio parameter is obtained ${value}.`);
+ console.info(`Callback invoked to indicate that the maximum volume is obtained. ${value}`);
});
```
-### getAudioParameter
-
-getAudioParameter(key: string): Promise<string>
+### getMaxVolume9+
-Obtains the value of an audio parameter. This API uses a promise to return the result.
+getMaxVolume(volumeType: AudioVolumeType): Promise<number>
-This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only.
+Obtains the maximum volume allowed for a stream. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Core
+**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
-| Name| Type | Mandatory| Description |
-| ------ | ------ | ---- | ---------------------- |
-| key | string | Yes | Key of the audio parameter whose value is to be obtained.|
+| Name | Type | Mandatory| Description |
+| ---------- | ----------------------------------- | ---- | ------------ |
+| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.|
**Return value**
-| Type | Description |
-| --------------------- | ----------------------------------- |
-| Promise<string> | Promise used to return the value of the audio parameter.|
+| Type | Description |
+| --------------------- | ----------------------------- |
+| Promise<number> | Promise used to return the maximum volume.|
**Example**
```js
-audioManager.getAudioParameter('key_example').then((value) => {
- console.info(`Promise returned to indicate that the value of the audio parameter is obtained ${value}.`);
+audioVolumeGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => {
+ console.info('Promised returned to indicate that the maximum volume is obtained.');
});
```
-### getDevices
+### mute9+
-getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void
+mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void>): void
-Obtains the audio devices with a specific flag. This API uses an asynchronous callback to return the result.
+Mutes or unmutes a stream. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Device
+**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY
+
+This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**.
+
+**System API**: This is a system API.
+
+**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ------------------------------------------------------------ | ---- | -------------------- |
-| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. |
-| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the device list.|
+| Name | Type | Mandatory| Description |
+| ---------- | ----------------------------------- | ---- | ------------------------------------- |
+| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
+| mute | boolean | Yes | Mute status to set. The value **true** means to mute the stream, and **false** means the opposite.|
+| callback | AsyncCallback<void> | Yes | Callback used to return the result. |
**Example**
+
```js
-audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => {
+audioVolumeGroupManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => {
if (err) {
- console.error(`Failed to obtain the device list. ${err}`);
+ console.error(`Failed to mute the stream. ${err}`);
return;
}
- console.info('Callback invoked to indicate that the device list is obtained.');
+ console.info('Callback invoked to indicate that the stream is muted.');
});
```
-### getDevices
+### mute9+
-getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors>
+mute(volumeType: AudioVolumeType, mute: boolean): Promise<void>
-Obtains the audio devices with a specific flag. This API uses a promise to return the result.
+Mutes or unmutes a stream. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Device
+**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY
+
+This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**.
+
+**System API**: This is a system API.
+
+**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ------------------------- | ---- | ---------------- |
-| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag.|
+| Name | Type | Mandatory| Description |
+| ---------- | ----------------------------------- | ---- | ------------------------------------- |
+| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
+| mute | boolean | Yes | Mute status to set. The value **true** means to mute the stream, and **false** means the opposite.|
**Return value**
-| Type | Description |
-| ------------------------------------------------------------ | ------------------------- |
-| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise used to return the device list.|
+| Type | Description |
+| ------------------- | ----------------------------- |
+| Promise<void> | Promise used to return the result.|
**Example**
```js
-audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => {
- console.info('Promise returned to indicate that the device list is obtained.');
+audioVolumeGroupManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => {
+ console.info('Promise returned to indicate that the stream is muted.');
});
```
-### setDeviceActive
+### isMute9+
-setDeviceActive(deviceType: ActiveDeviceType, active: boolean, callback: AsyncCallback<void>): void
+isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void
-Sets a device to the active state. This API uses an asynchronous callback to return the result.
+Checks whether a stream is muted. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Device
+**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ------------------------------------- | ---- | ------------------------ |
-| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. |
-| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. |
-| callback | AsyncCallback<void> | Yes | Callback used to return the result.|
+| Name | Type | Mandatory| Description |
+| ---------- | ----------------------------------- | ---- | ----------------------------------------------- |
+| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
+| callback | AsyncCallback<boolean> | Yes | Callback used to return the mute status of the stream. The value **true** means that the stream is muted, and **false** means the opposite.|
**Example**
```js
-audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true, (err) => {
+audioVolumeGroupManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => {
if (err) {
- console.error(`Failed to set the active status of the device. ${err}`);
+ console.error(`Failed to obtain the mute status. ${err}`);
return;
}
- console.info('Callback invoked to indicate that the device is set to the active status.');
+ console.info(`Callback invoked to indicate that the mute status of the stream is obtained ${value}.`);
});
```
-### setDeviceActive
+### isMute9+
-setDeviceActive(deviceType: ActiveDeviceType, active: boolean): Promise<void>
+isMute(volumeType: AudioVolumeType): Promise<boolean>
-Sets a device to the active state. This API uses a promise to return the result.
+Checks whether a stream is muted. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Device
+**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ------------------------------------- | ---- | ------------------ |
-| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type.|
-| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. |
+| Name | Type | Mandatory| Description |
+| ---------- | ----------------------------------- | ---- | ------------ |
+| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.|
**Return value**
-| Type | Description |
-| ------------------- | ------------------------------- |
-| Promise<void> | Promise used to return the result.|
+| Type | Description |
+| ---------------------- | ------------------------------------------------------ |
+| Promise<boolean> | Promise used to return the mute status of the stream. The value **true** means that the stream is muted, and **false** means the opposite.|
**Example**
-
```js
-audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true).then(() => {
- console.info('Promise returned to indicate that the device is set to the active status.');
+audioVolumeGroupManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => {
+ console.info(`Promise returned to indicate that the mute status of the stream is obtained ${value}.`);
});
```
-### isDeviceActive
+### setRingerMode9+
-isDeviceActive(deviceType: ActiveDeviceType, callback: AsyncCallback<boolean>): void
+setRingerMode(mode: AudioRingMode, callback: AsyncCallback<void>): void
-Checks whether a device is active. This API uses an asynchronous callback to return the result.
+Sets the ringer mode. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Device
+**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY
+
+This permission is required only for muting or unmuting the ringer.
+
+**System API**: This is a system API.
+
+**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ------------------------------------- | ---- | ------------------------ |
-| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. |
-| callback | AsyncCallback<boolean> | Yes | Callback used to return the active state of the device.|
+| Name | Type | Mandatory| Description |
+| -------- | ------------------------------- | ---- | ------------------------ |
+| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode. |
+| callback | AsyncCallback<void> | Yes | Callback used to return the result.|
**Example**
```js
-audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER, (err, value) => {
+audioVolumeGroupManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => {
if (err) {
- console.error(`Failed to obtain the active status of the device. ${err}`);
+ console.error(`Failed to set the ringer mode. ${err}`);
return;
}
- console.info('Callback invoked to indicate that the active status of the device is obtained.');
+ console.info('Callback invoked to indicate a successful setting of the ringer mode.');
});
```
+### setRingerMode9+
-### isDeviceActive
+setRingerMode(mode: AudioRingMode): Promise<void>
-isDeviceActive(deviceType: ActiveDeviceType): Promise<boolean>
+Sets the ringer mode. This API uses a promise to return the result.
-Checks whether a device is active. This API uses a promise to return the result.
+**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY
-**System capability**: SystemCapability.Multimedia.Audio.Device
+This permission is required only for muting or unmuting the ringer.
+
+**System API**: This is a system API.
+
+**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ------------------------------------- | ---- | ------------------ |
-| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type.|
+| Name| Type | Mandatory| Description |
+| ------ | ------------------------------- | ---- | -------------- |
+| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode.|
**Return value**
-| Type | Description |
-| ---------------------- | ------------------------------- |
-| Promise<boolean> | Promise used to return the active state of the device.|
+| Type | Description |
+| ------------------- | ------------------------------- |
+| Promise<void> | Promise used to return the result.|
**Example**
```js
-audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER).then((value) => {
- console.info(`Promise returned to indicate that the active status of the device is obtained ${value}.`);
+audioVolumeGroupManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => {
+ console.info('Promise returned to indicate a successful setting of the ringer mode.');
+});
+```
+
+### getRingerMode9+
+
+getRingerMode(callback: AsyncCallback<AudioRingMode>): void
+
+Obtains the ringer mode. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Audio.Volume
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ---------------------------------------------------- | ---- | ------------------------ |
+| callback | AsyncCallback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the ringer mode.|
+
+**Example**
+
+```js
+audioVolumeGroupManager.getRingerMode((err, value) => {
+ if (err) {
+ console.error(`Failed to obtain the ringer mode. ${err}`);
+ return;
+ }
+ console.info(`Callback invoked to indicate that the ringer mode is obtained ${value}.`);
+});
+```
+
+### getRingerMode9+
+
+getRingerMode(): Promise<AudioRingMode>
+
+Obtains the ringer mode. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Audio.Volume
+
+**Return value**
+
+| Type | Description |
+| ---------------------------------------------- | ------------------------------- |
+| Promise<[AudioRingMode](#audioringmode)> | Promise used to return the ringer mode.|
+
+**Example**
+
+```js
+audioVolumeGroupManager.getRingerMode().then((value) => {
+ console.info(`Promise returned to indicate that the ringer mode is obtained ${value}.`);
});
```
-### setMicrophoneMute
+### on('ringerModeChange')9+
+
+on(type: 'ringerModeChange', callback: Callback\): void
+
+Subscribes to ringer mode change events.
+
+**System capability**: SystemCapability.Multimedia.Audio.Volume
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
+| type | string | Yes | Event type. The value **'ringerModeChange'** means the ringer mode change event, which is triggered when a ringer mode change is detected.|
+| callback | Callback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the system volume change event. |
+
+**Error codes**
+
+For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md).
+
+| ID| Error Message|
+| ------- | --------------------------------------------|
+| 6800101 | if input parameter value error. |
+
+**Example**
+
+```js
+audioVolumeGroupManager.on('ringerModeChange', (ringerMode) => {
+ console.info(`Updated ringermode: ${ringerMode}`);
+});
+```
+### setMicrophoneMute9+
setMicrophoneMute(mute: boolean, callback: AsyncCallback<void>): void
Mutes or unmutes the microphone. This API uses an asynchronous callback to return the result.
-**Required permissions**: ohos.permission.MICROPHONE
+**Required permissions**: ohos.permission.MANAGE_AUDIO_CONFIG
-**System capability**: SystemCapability.Multimedia.Audio.Device
+**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
@@ -1697,7 +1780,7 @@ Mutes or unmutes the microphone. This API uses an asynchronous callback to retur
**Example**
```js
-audioManager.setMicrophoneMute(true, (err) => {
+audioVolumeGroupManager.setMicrophoneMute(true, (err) => {
if (err) {
console.error(`Failed to mute the microphone. ${err}`);
return;
@@ -1706,15 +1789,15 @@ audioManager.setMicrophoneMute(true, (err) => {
});
```
-### setMicrophoneMute
+### setMicrophoneMute9+
setMicrophoneMute(mute: boolean): Promise<void>
Mutes or unmutes the microphone. This API uses a promise to return the result.
-**Required permissions:** ohos.permission.MICROPHONE
+**Required permissions**: ohos.permission.MANAGE_AUDIO_CONFIG
-**System capability**: SystemCapability.Multimedia.Audio.Device
+**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
@@ -1731,20 +1814,18 @@ Mutes or unmutes the microphone. This API uses a promise to return the result.
**Example**
```js
-audioManager.setMicrophoneMute(true).then(() => {
+audioVolumeGroupManager.setMicrophoneMute(true).then(() => {
console.info('Promise returned to indicate that the microphone is muted.');
});
```
-### isMicrophoneMute
+### isMicrophoneMute9+
isMicrophoneMute(callback: AsyncCallback<boolean>): void
Checks whether the microphone is muted. This API uses an asynchronous callback to return the result.
-**Required permissions**: ohos.permission.MICROPHONE
-
-**System capability**: SystemCapability.Multimedia.Audio.Device
+**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
@@ -1755,7 +1836,7 @@ Checks whether the microphone is muted. This API uses an asynchronous callback t
**Example**
```js
-audioManager.isMicrophoneMute((err, value) => {
+audioVolumeGroupManager.isMicrophoneMute((err, value) => {
if (err) {
console.error(`Failed to obtain the mute status of the microphone. ${err}`);
return;
@@ -1764,15 +1845,13 @@ audioManager.isMicrophoneMute((err, value) => {
});
```
-### isMicrophoneMute
+### isMicrophoneMute9+
isMicrophoneMute(): Promise<boolean>
Checks whether the microphone is muted. This API uses a promise to return the result.
-**Required permissions**: ohos.permission.MICROPHONE
-
-**System capability**: SystemCapability.Multimedia.Audio.Device
+**System capability**: SystemCapability.Multimedia.Audio.Volume
**Return value**
@@ -1782,20 +1861,17 @@ Checks whether the microphone is muted. This API uses a promise to return the re
**Example**
-
```js
-audioManager.isMicrophoneMute().then((value) => {
+audioVolumeGroupManager.isMicrophoneMute().then((value) => {
console.info(`Promise returned to indicate that the mute status of the microphone is obtained ${value}.`);
});
```
-### on('volumeChange')8+
+### on('micStateChange')9+
-on(type: 'volumeChange', callback: Callback\): void
-
-Subscribes to system volume change events.
+on(type: 'micStateChange', callback: Callback<MicStateChangeEvent>): void
-**System API**: This is a system API.
+Subscribes to system mic state change events.
Currently, when multiple **AudioManager** instances are used in a single process, only the subscription of the last instance takes effect, and the subscription of other instances is overwritten (even if the last instance does not initiate a subscription). Therefore, you are advised to use a single **AudioManager** instance.
@@ -1805,3709 +1881,4263 @@ Currently, when multiple **AudioManager** instances are used in a single process
| Name | Type | Mandatory| Description |
| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ |
-| type | string | Yes | Event type. The value **volumeChange** means the system volume change event, which is triggered when a system volume change is detected.|
-| callback | Callback<[VolumeEvent](#volumeevent8)> | Yes | Callback used to return the system volume change event. |
+| type | string | Yes | Event type. The value **'micStateChange'** means the system mic state change event, which is triggered when the system mic state changes.|
+| callback | Callback<[MicStateChangeEvent](#micstatechangeevent9)> | Yes | Callback used to return the changed micr state. |
+
+**Error codes**
+
+For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md).
+
+| ID| Error Message|
+| ------- | --------------------------------------------|
+| 6800101 | if input parameter value error. |
**Example**
```js
-audioManager.on('volumeChange', (volumeEvent) => {
- console.info(`VolumeType of stream: ${volumeEvent.volumeType} `);
- console.info(`Volume level: ${volumeEvent.volume} `);
- console.info(`Whether to updateUI: ${volumeEvent.updateUi} `);
+audioVolumeGroupManager.on('micStateChange', (micStateChange) => {
+ console.info(`Current microphone status is: ${micStateChange.mute} `);
});
```
-### on('ringerModeChange')8+
+## AudioStreamManager9+
-on(type: 'ringerModeChange', callback: Callback\): void
+Implements audio stream management. Before calling any API in **AudioStreamManager**, you must use [getStreamManager](#getstreammanager9) to obtain an **AudioStreamManager** instance.
-Subscribes to ringer mode change events.
+### getCurrentAudioRendererInfoArray9+
-**System API**: This is a system API.
+getCurrentAudioRendererInfoArray(callback: AsyncCallback<AudioRendererChangeInfoArray>): void
-**System capability**: SystemCapability.Multimedia.Audio.Communication
+Obtains the information about the current audio renderer. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
-| type | string | Yes | Event type. The value **ringerModeChange** means the ringer mode change event, which is triggered when a ringer mode change is detected.|
-| callback | Callback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the system volume change event. |
+| Name | Type | Mandatory | Description |
+| -------- | ----------------------------------- | -------- | --------------------------- |
+| callback | AsyncCallback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Yes | Callback used to return the audio renderer information.|
**Example**
```js
-audioManager.on('ringerModeChange', (ringerMode) => {
- console.info(`Updated ringermode: ${ringerMode}`);
+audioStreamManager.getCurrentAudioRendererInfoArray(async (err, AudioRendererChangeInfoArray) => {
+ console.info('getCurrentAudioRendererInfoArray **** Get Callback Called ****');
+ if (err) {
+ console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`);
+ } else {
+ if (AudioRendererChangeInfoArray != null) {
+ for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) {
+ let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i];
+ console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`);
+ console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`);
+ console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`);
+ console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`);
+ console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`);
+ console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`);
+ for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) {
+ console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`);
+ console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`);
+ console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`);
+ console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`);
+ console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`);
+ console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`);
+ console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`);
+ console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`);
+ }
+ }
+ }
+ }
});
```
-### on('deviceChange')
+### getCurrentAudioRendererInfoArray9+
-on(type: 'deviceChange', callback: Callback): void
+getCurrentAudioRendererInfoArray(): Promise<AudioRendererChangeInfoArray>
-Subscribes to device change events. When a device is connected or disconnected, registered clients will receive the callback.
+Obtains the information about the current audio renderer. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Device
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
-**Parameters**
+**Return value**
-| Name | Type | Mandatory| Description |
-| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- |
-| type | string | Yes | Event type. The value **deviceChange** means the device change event, which is triggered when a device connection status change is detected.|
-| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | Yes | Callback used to return the device update details. |
+| Type | Description |
+| ---------------------------------------------------------------------------------| --------------------------------------- |
+| Promise<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Promise used to return the audio renderer information. |
**Example**
```js
-audioManager.on('deviceChange', (deviceChanged) => {
- console.info(`device change type : ${deviceChanged.type} `);
- console.info(`device descriptor size : ${deviceChanged.deviceDescriptors.length} `);
- console.info(`device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceRole} `);
- console.info(`device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceType} `);
-});
+async function getCurrentAudioRendererInfoArray(){
+ await audioStreamManager.getCurrentAudioRendererInfoArray().then( function (AudioRendererChangeInfoArray) {
+ console.info(`getCurrentAudioRendererInfoArray ######### Get Promise is called ##########`);
+ if (AudioRendererChangeInfoArray != null) {
+ for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) {
+ let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i];
+ console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`);
+ console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`);
+ console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`);
+ console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`);
+ console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`);
+ console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`);
+ for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) {
+ console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`);
+ console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`);
+ console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`);
+ console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`);
+ console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`);
+ console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`);
+ console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`);
+ console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`);
+ }
+ }
+ }
+ }).catch((err) => {
+ console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`);
+ });
+}
```
-### off('deviceChange')
+### getCurrentAudioCapturerInfoArray9+
-off(type: 'deviceChange', callback?: Callback): void
+getCurrentAudioCapturerInfoArray(callback: AsyncCallback<AudioCapturerChangeInfoArray>): void
-Unsubscribes from device change events.
+Obtains the information about the current audio capturer. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Device
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | --------------------------------------------------- | ---- | ------------------------------------------ |
-| type | string | Yes | Event type. The value **deviceChange** means the device change event, which is triggered when a device connection status change is detected.|
-| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | No | Callback used to return the device update details. |
+| Name | Type | Mandatory | Description |
+| ---------- | ----------------------------------- | --------- | -------------------------------------------------------- |
+| callback | AsyncCallback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Yes | Callback used to return the audio capturer information.|
**Example**
```js
-audioManager.off('deviceChange', (deviceChanged) => {
- console.info('Should be no callback.');
+audioStreamManager.getCurrentAudioCapturerInfoArray(async (err, AudioCapturerChangeInfoArray) => {
+ console.info('getCurrentAudioCapturerInfoArray **** Get Callback Called ****');
+ if (err) {
+ console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`);
+ } else {
+ if (AudioCapturerChangeInfoArray != null) {
+ for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) {
+ console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`);
+ console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`);
+ console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`);
+ console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`);
+ console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`);
+ for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) {
+ console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`);
+ console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`);
+ console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`);
+ console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`);
+ console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`);
+ console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`);
+ console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`);
+ console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`);
+ }
+ }
+ }
+ }
});
```
-### on('interrupt')
+### getCurrentAudioCapturerInfoArray9+
-on(type: 'interrupt', interrupt: AudioInterrupt, callback: Callback\): void
+getCurrentAudioCapturerInfoArray(): Promise<AudioCapturerChangeInfoArray>
-Subscribes to audio interruption events. When the application's audio is interrupted by another playback event, the application will receive the callback.
+Obtains the information about the current audio capturer. This API uses a promise to return the result.
**System capability**: SystemCapability.Multimedia.Audio.Renderer
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
-| type | string | Yes | Event type. The value **interrupt** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application.|
-| interrupt | AudioInterrupt | Yes | Audio interruption event type. |
-| callback | Callback<[InterruptAction](#interruptaction)> | Yes | Callback invoked for the audio interruption event. |
+**Return value**
-**Example**
+| Type | Description |
+| -----------------------------------------------------------------------------| ----------------------------------- |
+| Promise<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Promise used to return the audio capturer information. |
+
+**Example**
```js
-var interAudioInterrupt = {
- streamUsage:2,
- contentType:0,
- pauseWhenDucked:true
-};
-audioManager.on('interrupt', interAudioInterrupt, (InterruptAction) => {
- if (InterruptAction.actionType === 0) {
- console.info('An event to gain the audio focus starts.');
- console.info(`Focus gain event: ${InterruptAction} `);
- }
- if (InterruptAction.actionType === 1) {
- console.info('An audio interruption event starts.');
- console.info(`Audio interruption event: ${InterruptAction} `);
- }
-});
+async function getCurrentAudioCapturerInfoArray(){
+ await audioStreamManager.getCurrentAudioCapturerInfoArray().then( function (AudioCapturerChangeInfoArray) {
+ console.info('getCurrentAudioCapturerInfoArray **** Get Promise Called ****');
+ if (AudioCapturerChangeInfoArray != null) {
+ for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) {
+ console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`);
+ console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`);
+ console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`);
+ console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`);
+ console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`);
+ for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) {
+ console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`);
+ console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`);
+ console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`);
+ console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`);
+ console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`);
+ console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`);
+ console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`);
+ console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`);
+ }
+ }
+ }
+ }).catch((err) => {
+ console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`);
+ });
+}
```
-### off('interrupt')
+### on('audioRendererChange')9+
-off(type: 'interrupt', interrupt: AudioInterrupt, callback?: Callback\): void
+on(type: "audioRendererChange", callback: Callback<AudioRendererChangeInfoArray>): void
-Unsubscribes from audio interruption events.
+Subscribes to audio renderer change events.
**System capability**: SystemCapability.Multimedia.Audio.Renderer
**Parameters**
-| Name | Type | Mandatory| Description |
-| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
-| type | string | Yes | Event type. The value **interrupt** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application.|
-| interrupt | AudioInterrupt | Yes | Audio interruption event type. |
-| callback | Callback<[InterruptAction](#interruptaction)> | No | Callback invoked for the audio interruption event. |
+| Name | Type | Mandatory | Description |
+| -------- | ---------- | --------- | ------------------------------------------------------------------------ |
+| type | string | Yes | Event type. The event `'audioRendererChange'` is triggered when the audio renderer changes. |
+| callback | Callback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Yes | Callback used to return the result. |
+
+**Error codes**
+
+For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md).
+
+| ID| Error Message|
+| ------- | --------------------------------------------|
+| 6800101 | if input parameter value error. |
**Example**
```js
-var interAudioInterrupt = {
- streamUsage:2,
- contentType:0,
- pauseWhenDucked:true
-};
-audioManager.off('interrupt', interAudioInterrupt, (InterruptAction) => {
- if (InterruptAction.actionType === 0) {
- console.info('An event to release the audio focus starts.');
- console.info(`Focus release event: ${InterruptAction} `);
+audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => {
+ for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) {
+ let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i];
+ console.info(`## RendererChange on is called for ${i} ##`);
+ console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`);
+ console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`);
+ console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`);
+ console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`);
+ console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`);
+ console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`);
+ for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) {
+ console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`);
+ console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`);
+ console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`);
+ console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`);
+ console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`);
+ console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`);
+ console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`);
+ console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`);
+ }
}
});
```
-### setAudioScene8+
+### off('audioRendererChange')9+
-setAudioScene\(scene: AudioScene, callback: AsyncCallback\): void
+off(type: "audioRendererChange"): void
-Sets an audio scene. This API uses an asynchronous callback to return the result.
+Unsubscribes from audio renderer change events.
-**System API**: This is a system API.
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
-**System capability**: SystemCapability.Multimedia.Audio.Communication
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ------- | ---- | ---------------- |
+| type | string | Yes | Event type. The event `'audioRendererChange'` is triggered when the audio renderer changes.|
+
+**Error codes**
+
+For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md).
+
+| ID| Error Message|
+| ------- | --------------------------------------------|
+| 6800101 | if input parameter value error. |
+
+**Example**
+
+```js
+audioStreamManager.off('audioRendererChange');
+console.info('######### RendererChange Off is called #########');
+```
+
+### on('audioCapturerChange')9+
+
+on(type: "audioCapturerChange", callback: Callback<AudioCapturerChangeInfoArray>): void
+
+Subscribes to audio capturer change events.
+
+**System capability**: SystemCapability.Multimedia.Audio.Capturer
**Parameters**
-| Name | Type | Mandatory| Description |
-| :------- | :----------------------------------- | :--- | :------------------- |
-| scene | AudioScene | Yes | Audio scene to set. |
-| callback | AsyncCallback | Yes | Callback used to return the result.|
+| Name | Type | Mandatory | Description |
+| -------- | ------- | --------- | ----------------------------------------------------------------------- |
+| type | string | Yes | Event type. The event `'audioCapturerChange'` is triggered when the audio capturer changes. |
+| callback | Callback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Yes | Callback used to return the result. |
**Example**
```js
-var audioManager = audio.getAudioManager();
-audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL, (err) => {
- if (err) {
- console.error(`Failed to set the audio scene mode. ${err}`);
- return;
+audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => {
+ for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) {
+ console.info(`## CapChange on is called for element ${i} ##`);
+ console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`);
+ console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`);
+ console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`);
+ console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`);
+ console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`);
+ let devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors;
+ for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) {
+ console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`);
+ console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`);
+ console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`);
+ console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`);
+ console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`);
+ console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`);
+ console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`);
+ console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`);
+ }
}
- console.info('Callback invoked to indicate a successful setting of the audio scene mode.');
});
```
-### setAudioScene8+
-
-setAudioScene\(scene: AudioScene\): Promise
+### off('audioCapturerChange')9+
-Sets an audio scene. This API uses a promise to return the result.
+off(type: "audioCapturerChange"): void;
-**System API**: This is a system API.
+Unsubscribes from audio capturer change events.
-**System capability**: SystemCapability.Multimedia.Audio.Communication
+**System capability**: SystemCapability.Multimedia.Audio.Capturer
**Parameters**
-| Name| Type | Mandatory| Description |
-| :----- | :----------------------------------- | :--- | :------------- |
-| scene | AudioScene | Yes | Audio scene to set.|
-
-**Return value**
-
-| Type | Description |
-| :------------- | :------------------- |
-| Promise | Promise used to return the result.|
+| Name | Type | Mandatory| Description |
+| -------- | -------- | --- | ------------------------------------------------------------- |
+| type | string |Yes | Event type. The event `'audioCapturerChange'` is triggered when the audio capturer changes.|
**Example**
```js
-var audioManager = audio.getAudioManager();
-audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL).then(() => {
- console.info('Promise returned to indicate a successful setting of the audio scene mode.');
-}).catch ((err) => {
- console.error(`Failed to set the audio scene mode ${err}`);
-});
+audioStreamManager.off('audioCapturerChange');
+console.info('######### CapturerChange Off is called #########');
+
```
-### getAudioScene8+
+### isActive9+
-getAudioScene\(callback: AsyncCallback\): void
+isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void
-Obtains the audio scene. This API uses an asynchronous callback to return the result.
+Checks whether a stream is active. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Communication
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
**Parameters**
-| Name | Type | Mandatory| Description |
-| :------- | :-------------------------------------------------- | :--- | :--------------------------- |
-| callback | AsyncCallback<AudioScene> | Yes | Callback used to return the audio scene.|
+| Name | Type | Mandatory| Description |
+| ---------- | ----------------------------------- | ---- | ------------------------------------------------- |
+| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
+| callback | AsyncCallback<boolean> | Yes | Callback used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite.|
**Example**
```js
-var audioManager = audio.getAudioManager();
-audioManager.getAudioScene((err, value) => {
+audioStreamManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => {
if (err) {
- console.error(`Failed to obtain the audio scene mode. ${err}`);
+ console.error(`Failed to obtain the active status of the stream. ${err}`);
return;
}
- console.info(`Callback invoked to indicate that the audio scene mode is obtained ${value}.`);
+ console.info(`Callback invoked to indicate that the active status of the stream is obtained ${value}.`);
});
```
+### isActive9+
-### getAudioScene8+
+isActive(volumeType: AudioVolumeType): Promise<boolean>
-getAudioScene\(\): Promise
+Checks whether a stream is active. This API uses a promise to return the result.
-Obtains the audio scene. This API uses a promise to return the result.
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
-**System capability**: SystemCapability.Multimedia.Audio.Communication
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ---------- | ----------------------------------- | ---- | ------------ |
+| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.|
**Return value**
-| Type | Description |
-| :-------------------------------------------- | :--------------------------- |
-| Promise<AudioScene> | Promise used to return the audio scene.|
+| Type | Description |
+| ---------------------- | -------------------------------------------------------- |
+| Promise<boolean> | Promise used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite.|
**Example**
```js
-var audioManager = audio.getAudioManager();
-audioManager.getAudioScene().then((value) => {
- console.info(`Promise returned to indicate that the audio scene mode is obtained ${value}.`);
-}).catch ((err) => {
- console.error(`Failed to obtain the audio scene mode ${err}`);
+audioStreamManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => {
+ console.info(`Promise returned to indicate that the active status of the stream is obtained ${value}.`);
});
```
-### getVolumeGroups9+
+## AudioRoutingManager9+
-getVolumeGroups(networkId: string, callback: AsyncCallback\): void
+Implements audio routing management. Before calling any API in **AudioRoutingManager**, you must use [getRoutingManager](#getroutingmanager9) to obtain an **AudioRoutingManager** instance.
-Obtains the volume groups. This API uses an asynchronous callback to return the result.
+### getDevices9+
-**System API**: This is a system API.
+getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void
-**System capability**: SystemCapability.Multimedia.Audio.Volume
+Obtains the audio devices with a specific flag. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Audio.Device
**Parameters**
| Name | Type | Mandatory| Description |
| ---------- | ------------------------------------------------------------ | ---- | -------------------- |
-| networkId | string | Yes | Network ID of the device. The network ID of the local device is **audio.LOCAL_NETWORK_ID**. You can call **getRoutingManager().getDevices()** to obtain all network IDs. |
-| callback | AsyncCallback<[VolumeGroupInfos](#volumegroupinfos9)> | Yes | Callback used to return the volume group information array.|
+| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. |
+| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the device list.|
**Example**
+
```js
-var audioManager = audio.getAudioManager();
-audioManager.getVolumeGroups(audio.LOCAL_NETWORK_ID, (err, value) => {
+audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => {
if (err) {
- console.error(`Failed to obtain the volume group infos list. ${err}`);
+ console.error(`Failed to obtain the device list. ${err}`);
return;
}
- console.info('Callback invoked to indicate that the volume group infos list is obtained.');
+ console.info('Callback invoked to indicate that the device list is obtained.');
});
```
-### getVolumeGroups9+
-
-getVolumeGroups(networkId: string\): Promise
+### getDevices9+
-Obtains the volume groups. This API uses a promise to return the result.
+getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors>
-**System API**: This is a system API.
+Obtains the audio devices with a specific flag. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Volume
+**System capability**: SystemCapability.Multimedia.Audio.Device
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ------------------------------------------------------------ | ---- | -------------------- |
-| networkId | string | Yes | Network ID of the device. The network ID of the local device is **audio.LOCAL_NETWORK_ID**. You can call **getRoutingManager().getDevices()** to obtain all network IDs. |
+| Name | Type | Mandatory| Description |
+| ---------- | ------------------------- | ---- | ---------------- |
+| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag.|
**Return value**
-| Type | Description |
-| ------------------- | ----------------------------- |
-| Promise<[VolumeGroupInfos](#volumegroupinfos9)> | Volume group information array.|
+| Type | Description |
+| ------------------------------------------------------------ | ------------------------- |
+| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise used to return the device list.|
**Example**
```js
-async function getVolumeGroupInfos(){
- let volumegroupinfos = await audio.getAudioManager().getVolumeGroups(audio.LOCAL_NETWORK_ID);
- console.info('Promise returned to indicate that the volumeGroup list is obtained.'+JSON.stringify(volumegroupinfos))
-}
+audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => {
+ console.info('Promise returned to indicate that the device list is obtained.');
+});
```
-### getGroupManager9+
-
-getGroupManager(groupId: number, callback: AsyncCallback\): void
+### on9+
-Obtains the audio group manager. This API uses an asynchronous callback to return the result.
+on(type: 'deviceChange', deviceFlag: DeviceFlag, callback: Callback): void
-**System API**: This is a system API.
+Subscribes to device change events. When a device is connected or disconnected, registered clients will receive the callback.
-**System capability**: SystemCapability.Multimedia.Audio.Volume
+**System capability**: SystemCapability.Multimedia.Audio.Device
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ------------------------------------------------------------ | ---- | -------------------- |
-| groupId | number | Yes | Volume group ID. |
-| callback | AsyncCallback< [AudioGroupManager](#audiogroupmanager9) > | Yes | Callback used to return the audio group manager.|
-
-**Example**
-
-```js
-var audioManager = audio.getAudioManager();
-var audioGroupManager;
-async function getGroupManager(){
- let value = await audioManager.getVolumeGroups(audio.LOCAL_NETWORK_ID);
- if (value.length > 0) {
- let groupid = value[0].groupId;
- audioManager.getGroupManager(groupid, (err, value) => {
- if (err) {
- console.error(`Failed to obtain the volume group infos list. ${err}`);
- return;
- }
- audioGroupManager = value
- console.info('Callback invoked to indicate that the volume group infos list is obtained.');
- });
- }
-}
-```
-
-### getGroupManager9+
-
-getGroupManager(groupId: number\): Promise
-
-Obtains the audio group manager. This API uses a promise to return the result.
-
-**System API**: This is a system API.
-
-**System capability**: SystemCapability.Multimedia.Audio.Volume
-
-**Parameters**
+| Name | Type | Mandatory| Description |
+| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- |
+| type | string | Yes | Event type. The value **'deviceChange'** means the device change event, which is triggered when a device connection status change is detected.|
+| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. |
+| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | Yes | Callback used to return the device update details. |
-| Name | Type | Mandatory| Description |
-| ---------- | ---------------------------------------- | ---- | ---------------- |
-| groupId | number | Yes | Volume group ID. |
+**Error codes**
-**Return value**
+For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md).
-| Type | Description |
-| ------------------- | ----------------------------- |
-| Promise< [AudioGroupManager](#audiogroupmanager9) > | Promise used to return the audio group manager.|
+| ID| Error Message|
+| ------- | --------------------------------------------|
+| 6800101 | if input parameter value error. |
**Example**
```js
-var audioManager = audio.getAudioManager();
-async function getGroupManager(){
- let value = await audioManager.getVolumeGroups(audio.LOCAL_NETWORK_ID);
- if (value.length > 0) {
- let groupid = value[0].groupId;
- let audioGroupManager = await audioManager.getGroupManager(groupid)
- console.info('Callback invoked to indicate that the volume group infos list is obtained.');
- }
-}
+audioRoutingManager.on('deviceChange', audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (deviceChanged) => {
+ console.info('device change type : ' + deviceChanged.type);
+ console.info('device descriptor size : ' + deviceChanged.deviceDescriptors.length);
+ console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceRole);
+ console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceType);
+});
```
-### getStreamManager9+
+### off9+
-getStreamManager(callback: AsyncCallback\): void
+off(type: 'deviceChange', callback?: Callback): void
-Obtains an **AudioStreamManager** instance. This API uses an asynchronous callback to return the result.
+Unsubscribes from device change events.
-**System capability**: SystemCapability.Multimedia.Audio.Core
+**System capability**: SystemCapability.Multimedia.Audio.Device
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | --------------------------------------------------------- | ---- | ---------------- |
-| callback | AsyncCallback<[AudioStreamManager](#audiostreammanager9)> | Yes | **AudioStreamManager** instance.|
-
-**Example**
-
-```js
-var audioManager = audio.getAudioManager();
-let audioStreamManager;
-audioManager.getStreamManager((err, data) => {
- if (err) {
- console.error(`getStreamManager : Error: ${err}`);
- } else {
- console.info('getStreamManager : Success : SUCCESS');
- audioStreamManager = data;
- }
-});
-```
-
-### getStreamManager9+
-
-getStreamManager(): Promise
-
-Obtains an **AudioStreamManager** instance. This API uses a promise to return the result.
+| Name | Type | Mandatory| Description |
+| -------- | --------------------------------------------------- | ---- | ------------------------------------------ |
+| type | string | Yes | Event type. The value **'deviceChange'** means the device change event, which is triggered when a device connection status change is detected.|
+| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | No | Callback used to return the device update details. |
-**System capability**: SystemCapability.Multimedia.Audio.Core
+**Error codes**
-**Return value**
+For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md).
-| Type | Description |
-| ---------------------------------------------------- | ---------------- |
-| Promise<[AudioStreamManager](#audiostreammanager9)> | **AudioStreamManager** instance.|
+| ID| Error Message|
+| ------- | --------------------------------------------|
+| 6800101 | if input parameter value error. |
**Example**
```js
-var audioManager = audio.getAudioManager();
-var audioStreamManager;
-audioManager.getStreamManager().then((data) => {
- audioStreamManager = data;
- console.info('getStreamManager: Success!');
-}).catch((err) => {
- console.error(`getStreamManager: ERROR : ${err}`);
+audioRoutingManager.off('deviceChange', (deviceChanged) => {
+ console.info('Should be no callback.');
});
-
```
-### requestIndependentInterrupt9+
+### selectInputDevice9+
-requestIndependentInterrupt(focusType: FocusType, callback: AsyncCallback\): void
+selectInputDevice(inputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void
-Requests independent interruption and obtains an interruption session ID. This API uses an asynchronous callback to return the result.
+Selects an audio input device. Currently, only one input device can be selected. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+**System capability**: SystemCapability.Multimedia.Audio.Device
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | ----------------------------- | ---- | ----------------- |
-| focusType | [FocusType](#focustype) | Yes | Focus type. |
-| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.|
+| Name | Type | Mandatory| Description |
+| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- |
+| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Input device. |
+| callback | AsyncCallback<void> | Yes | Callback used to return the result.|
**Example**
-
```js
-async function requestIndependentInterrupt(){
- let value = await audioManager.requestIndependentInterrupt(audio.FocusType.FOCUS_TYPE_RECORDING);
- if (value) {
- console.info('requestIndependentInterrupt interface for result callback: SUCCESS');
- } else {
- console.error('Result ERROR');
- }
+let inputAudioDeviceDescriptor = [{
+ "deviceRole":audio.DeviceRole.INPUT_DEVICE,
+ "networkId":audio.LOCAL_NETWORK_ID,
+ "interruptGroupId":1,
+ "volumeGroupId":1 }];
+
+async function selectInputDevice(){
+ audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor, (err) => {
+ if (err) {
+ console.error(`Result ERROR: ${err}`);
+ } else {
+ console.info('Select input devices result callback: SUCCESS'); }
+ });
}
```
-### requestIndependentInterrupt9+
-requestIndependentInterrupt(focusType: FocusType): Promise
+### selectInputDevice9+
-Requests independent interruption and obtains an interruption session ID. This API uses a promise to return the result.
+selectInputDevice(inputAudioDevices: AudioDeviceDescriptors): Promise<void>
**System API**: This is a system API.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+Selects an audio input device. Currently, only one input device can be selected. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Audio.Device
**Parameters**
-| Name| Type| Mandatory| Description|
-| ------ | ---- | ---- | ---- |
-| focusType | [FocusType](#focustype) | Yes | Focus type. |
+| Name | Type | Mandatory| Description |
+| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- |
+| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Input device. |
**Return value**
-| Type | Description |
-| --------------------------------------------------------- | ------------ |
-| Promise<boolean> | Promise used to return the result.|
+| Type | Description |
+| --------------------- | --------------------------- |
+| Promise<void> | Promise used to return the result.|
**Example**
```js
-async function requestIndependentInterrupt(){
- audioManager.requestIndependentInterrupt(audio.FocusType.FOCUS_TYPE_RECORDING).then((value) => {
- console.info('Promise returned to succeed ');
- }).catch ((err) => {
- console.error('Failed to requestIndependentInterrupt');
- });
+let inputAudioDeviceDescriptor =[{
+ "deviceRole":audio.DeviceRole.INPUT_DEVICE,
+ "networkId":audio.LOCAL_NETWORK_ID,
+ "interruptGroupId":1,
+ "volumeGroupId":1 }];
+
+async function getRoutingManager(){
+ audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor).then(() => {
+ console.info('Select input devices result promise: SUCCESS');
+ }).catch((err) => {
+ console.error(`Result ERROR: ${err}`);
+ });
}
```
-### abandonIndependentInterrupt9+
-abandonIndependentInterrupt(focusType: FocusType, callback: AsyncCallback\): void
+### setCommunicationDevice9+
-Abandons independent interruption. This API uses an asynchronous callback to return the result.
+setCommunicationDevice(deviceType: CommunicationDeviceType, active: boolean, callback: AsyncCallback<void>): void
-**System API**: This is a system API.
+Sets a communication device to the active state. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+**System capability**: SystemCapability.Multimedia.Audio.Communication
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | ----------------------------- | ---- | ----------------- |
-| focusType | [FocusType](#focustype) | Yes | Focus type. |
-| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.|
+| Name | Type | Mandatory| Description |
+| ---------- | ------------------------------------- | ---- | ------------------------ |
+| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type. |
+| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. |
+| callback | AsyncCallback<void> | Yes | Callback used to return the result.|
**Example**
```js
-async function abandonIndependentInterrupt(){
- let value = await audioManager.abandonIndependentInterrupt(audio.FocusType.FOCUS_TYPE_RECORDING);
- if (value) {
- console.info('abandonIndependentInterrupt interface for result callback: SUCCESS');
- } else {
- console.error('Result ERROR');
+audioRoutingManager.setCommunicationDevice(audio.CommunicationDeviceType.SPEAKER, true, (err) => {
+ if (err) {
+ console.error(`Failed to set the active status of the device. ${err}`);
+ return;
}
-}
+ console.info('Callback invoked to indicate that the device is set to the active status.');
+});
```
-### abandonIndependentInterrupt9+
-abandonIndependentInterrupt(focusType: FocusType): Promise
+### setCommunicationDevice9+
-Abandons independent interruption. This API uses a promise to return the result.
+setCommunicationDevice(deviceType: CommunicationDeviceType, active: boolean): Promise<void>
-**System API**: This is a system API.
+Sets a communication device to the active state. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+**System capability**: SystemCapability.Multimedia.Audio.Communication
**Parameters**
-| Name| Type| Mandatory| Description|
-| ------ | ---- | ---- | ---- |
-| focusType | [FocusType](#focustype) | Yes | Focus type. |
+| Name | Type | Mandatory| Description |
+| ---------- | ----------------------------------------------------- | ---- | ------------------ |
+| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type.|
+| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. |
**Return value**
-| Type | Description |
-| --------------------------------------------------------- | ------------ |
-| Promise<boolean> | Promise used to return the result.|
+| Type | Description |
+| ------------------- | ------------------------------- |
+| Promise<void> | Promise used to return the result.|
**Example**
```js
-async function abandonIndependentInterrupt(){
- audioManager.abandonIndependentInterrupt(audio.FocusType.FOCUS_TYPE_RECORDING).then((value) => {
- console.info('Promise returned to succeed');
- }).catch ((err) => {
- console.error('Failed to abandonIndependentInterrupt');
- });
-}
+audioRoutingManager.setCommunicationDevice(audio.CommunicationDeviceType.SPEAKER, true).then(() => {
+ console.info('Promise returned to indicate that the device is set to the active status.');
+});
```
-## AudioGroupManager9+
-Manages the volume of an audio group. Before calling any API in **AudioGroupManager**, you must use [getGroupManager](#getgroupmanager9) to create an **AudioGroupManager** instance.
-
-**System API**: This is a system API.
-
-**System capability**: SystemCapability.Multimedia.Audio.Volume
-
-### setVolume9+
-setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback<void>): void
-
-Sets the volume for a stream. This API uses an asynchronous callback to return the result.
-
-**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY
+### isCommunicationDeviceActive9+
-This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**.
+isCommunicationDeviceActive(deviceType: CommunicationDeviceType, callback: AsyncCallback<boolean>): void
-**System API**: This is a system API.
+Checks whether a communication device is active. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Volume
+**System capability**: SystemCapability.Multimedia.Audio.Communication
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- |
-| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
-| volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**.|
-| callback | AsyncCallback<void> | Yes | Callback used to return the result. |
+| Name | Type | Mandatory| Description |
+| ---------- | ---------------------------------------------------- | ---- | ------------------------ |
+| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type. |
+| callback | AsyncCallback<boolean> | Yes | Callback used to return the active state of the device.|
**Example**
```js
-audioGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => {
+audioRoutingManager.isCommunicationDeviceActive(audio.CommunicationDeviceType.SPEAKER, (err, value) => {
if (err) {
- console.error(`Failed to set the volume. ${err}`);
+ console.error(`Failed to obtain the active status of the device. ${err}`);
return;
}
- console.info('Callback invoked to indicate a successful volume setting.');
+ console.info('Callback invoked to indicate that the active status of the device is obtained.');
});
```
-### setVolume9+
-
-setVolume(volumeType: AudioVolumeType, volume: number): Promise<void>
-
-Sets the volume for a stream. This API uses a promise to return the result.
-
-**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY
+### isCommunicationDeviceActive9+
-This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**.
+isCommunicationDeviceActive(deviceType: CommunicationDeviceType): Promise<boolean>
-**System API**: This is a system API.
+Checks whether a communication device is active. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Volume
+**System capability**: SystemCapability.Multimedia.Audio.Communication
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- |
-| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
-| volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**.|
+| Name | Type | Mandatory| Description |
+| ---------- | ---------------------------------------------------- | ---- | ------------------ |
+| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type.|
**Return value**
-| Type | Description |
-| ------------------- | ----------------------------- |
-| Promise<void> | Promise used to return the result.|
+| Type | Description |
+| ---------------------- | ------------------------------- |
+| Promise<boolean> | Promise used to return the active state of the device.|
**Example**
```js
-audioGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => {
- console.info('Promise returned to indicate a successful volume setting.');
+audioRoutingManager.isCommunicationDeviceActive(audio.CommunicationDeviceType.SPEAKER).then((value) => {
+ console.info(`Promise returned to indicate that the active status of the device is obtained ${value}.`);
});
```
-### getVolume9+
+### selectOutputDevice9+
-getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void
+selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void
-Obtains the volume of a stream. This API uses an asynchronous callback to return the result.
+Selects an audio output device. Currently, only one output device can be selected. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
-**System capability**: SystemCapability.Multimedia.Audio.Volume
+**System capability**: SystemCapability.Multimedia.Audio.Device
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ----------------------------------- | ---- | ------------------ |
-| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
-| callback | AsyncCallback<number> | Yes | Callback used to return the volume.|
+| Name | Type | Mandatory| Description |
+| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- |
+| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. |
+| callback | AsyncCallback<void> | Yes | Callback used to return the result.|
**Example**
-
```js
-audioGroupManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => {
- if (err) {
- console.error(`Failed to obtain the volume. ${err}`);
- return;
- }
- console.info('Callback invoked to indicate that the volume is obtained.');
-});
+let outputAudioDeviceDescriptor = [{
+ "deviceRole":audio.DeviceRole.OUTPUT_DEVICE,
+ "networkId":audio.LOCAL_NETWORK_ID,
+ "interruptGroupId":1,
+ "volumeGroupId":1 }];
+async function selectOutputDevice(){
+ audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor, (err) => {
+ if (err) {
+ console.error(`Result ERROR: ${err}`);
+ } else {
+ console.info('Select output devices result callback: SUCCESS'); }
+ });
+}
```
-### getVolume9+
-
-getVolume(volumeType: AudioVolumeType): Promise<number>
+### selectOutputDevice9+
-Obtains the volume of a stream. This API uses a promise to return the result.
+selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors): Promise<void>
**System API**: This is a system API.
-**System capability**: SystemCapability.Multimedia.Audio.Volume
+Selects an audio output device. Currently, only one output device can be selected. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Audio.Device
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ----------------------------------- | ---- | ------------ |
-| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.|
+| Name | Type | Mandatory| Description |
+| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- |
+| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. |
**Return value**
-| Type | Description |
-| --------------------- | ------------------------- |
-| Promise<number> | Promise used to return the volume.|
+| Type | Description |
+| --------------------- | --------------------------- |
+| Promise<void> | Promise used to return the result.|
**Example**
```js
-audioGroupManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => {
- console.info(`Promise returned to indicate that the volume is obtained ${value}.`);
-});
-```
-
-### getMinVolume9+
+let outputAudioDeviceDescriptor =[{
+ "deviceRole":audio.DeviceRole.OUTPUT_DEVICE,
+ "networkId":audio.LOCAL_NETWORK_ID,
+ "interruptGroupId":1,
+ "volumeGroupId":1 }];
-getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void
+async function selectOutputDevice(){
+ audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor).then(() => {
+ console.info('Select output devices result promise: SUCCESS');
+ }).catch((err) => {
+ console.error(`Result ERROR: ${err}`);
+ });
+}
+```
-Obtains the minimum volume allowed for a stream. This API uses an asynchronous callback to return the result.
+### selectOutputDeviceByFilter9+
+
+selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void
**System API**: This is a system API.
-**System capability**: SystemCapability.Multimedia.Audio.Volume
+Selects an audio output device based on the filter criteria. Currently, only one output device can be selected. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Audio.Device
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ----------------------------------- | ---- | ------------------ |
-| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
-| callback | AsyncCallback<number> | Yes | Callback used to return the minimum volume.|
+| Name | Type | Mandatory| Description |
+| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- |
+| filter | [AudioRendererFilter](#audiorendererfilter9) | Yes | Filter criteria. |
+| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. |
+| callback | AsyncCallback<void> | Yes | Callback used to return the result.|
**Example**
-
```js
-audioGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => {
- if (err) {
- console.error(`Failed to obtain the minimum volume. ${err}`);
- return;
- }
- console.info(`Callback invoked to indicate that the minimum volume is obtained. ${value}`);
-});
-```
+let outputAudioRendererFilter = {
+ "uid":20010041,
+ "rendererInfo": {
+ "contentType":audio.ContentType.CONTENT_TYPE_MUSIC,
+ "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA,
+ "rendererFlags":0 },
+ "rendererId":0 };
+let outputAudioDeviceDescriptor = [{
+ "deviceRole":audio.DeviceRole.OUTPUT_DEVICE,
+ "networkId":audio.LOCAL_NETWORK_ID,
+ "interruptGroupId":1,
+ "volumeGroupId":1 }];
-### getMinVolume9+
+async function selectOutputDeviceByFilter(){
+ audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor, (err) => {
+ if (err) {
+ console.error(`Result ERROR: ${err}`);
+ } else {
+ console.info('Select output devices by filter result callback: SUCCESS'); }
+ });
+}
+```
-getMinVolume(volumeType: AudioVolumeType): Promise<number>
+### selectOutputDeviceByFilter9+
-Obtains the minimum volume allowed for a stream. This API uses a promise to return the result.
+selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors): Promise<void>
**System API**: This is a system API.
-**System capability**: SystemCapability.Multimedia.Audio.Volume
+Selects an audio output device based on the filter criteria. Currently, only one output device can be selected. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Audio.Device
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ----------------------------------- | ---- | ------------ |
-| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.|
+| Name | Type | Mandatory| Description |
+| ----------------------| ------------------------------------------------------------ | ---- | ------------------------- |
+| filter | [AudioRendererFilter](#audiorendererfilter9) | Yes | Filter criteria. |
+| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. |
**Return value**
-| Type | Description |
-| --------------------- | ------------------------- |
-| Promise<number> | Promise used to return the minimum volume.|
+| Type | Description |
+| --------------------- | --------------------------- |
+| Promise<void> | Promise used to return the result.|
**Example**
```js
-audioGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => {
- console.info(`Promised returned to indicate that the minimum volume is obtained ${value}.`);
-});
+let outputAudioRendererFilter = {
+ "uid":20010041,
+ "rendererInfo": {
+ "contentType":audio.ContentType.CONTENT_TYPE_MUSIC,
+ "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA,
+ "rendererFlags":0 },
+ "rendererId":0 };
+let outputAudioDeviceDescriptor = [{
+ "deviceRole":audio.DeviceRole.OUTPUT_DEVICE,
+ "networkId":audio.LOCAL_NETWORK_ID,
+ "interruptGroupId":1,
+ "volumeGroupId":1 }];
+
+async function selectOutputDeviceByFilter(){
+ audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor).then(() => {
+ console.info('Select output devices by filter result promise: SUCCESS');
+ }).catch((err) => {
+ console.error(`Result ERROR: ${err}`);
+ })
+}
```
-### getMaxVolume9+
+## AudioRendererChangeInfoArray9+
-getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void
+Defines an **AudioRenderChangeInfo** array, which is read-only.
-Obtains the maximum volume allowed for a stream. This API uses an asynchronous callback to return the result.
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
-**System API**: This is a system API.
+## AudioRendererChangeInfo9+
-**System capability**: SystemCapability.Multimedia.Audio.Volume
+Describes the audio renderer change event.
-**Parameters**
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
-| Name | Type | Mandatory| Description |
-| ---------- | ----------------------------------- | ---- | ---------------------- |
-| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
-| callback | AsyncCallback<number> | Yes | Callback used to return the maximum volume.|
+| Name | Type | Readable | Writable | Description |
+| ------------- | ---------------------------------------- | -------- | -------- | ---------------------------------------------------------- |
+| streamId | number | Yes | No | Unique ID of an audio stream. |
+| clientUid | number | Yes | No | UID of the audio renderer client.
This is a system API. |
+| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | No | Audio renderer information. |
+| rendererState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API. |
**Example**
```js
-audioGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => {
+import audio from '@ohos.multimedia.audio';
+
+let audioStreamManager;
+let resultFlag = false;
+let audioManager = audio.getAudioManager();
+
+audioManager.getStreamManager((err, data) => {
if (err) {
- console.error(`Failed to obtain the maximum volume. ${err}`);
- return;
+ console.error(`Get AudioStream Manager : ERROR : ${err}`);
+ } else {
+ audioStreamManager = data;
+ console.info('Get AudioStream Manager : Success');
}
- console.info(`Callback invoked to indicate that the maximum volume is obtained. ${value}`);
});
-```
-### getMaxVolume9+
+audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => {
+ for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) {
+ console.info(`## RendererChange on is called for ${i} ##`);
+ console.info(`StreamId for ${i} is: ${AudioRendererChangeInfoArray[i].streamId}`);
+ console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfoArray[i].clientUid}`);
+ console.info(`Content for ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.content}`);
+ console.info(`Stream for ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.usage}`);
+ console.info(`Flag ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.rendererFlags}`);
+ console.info(`State for ${i} is: ${AudioRendererChangeInfoArray[i].rendererState}`);
+ let devDescriptor = AudioRendererChangeInfoArray[i].deviceDescriptors;
+ for (let j = 0; j < AudioRendererChangeInfoArray[i].deviceDescriptors.length; j++) {
+ console.info(`Id: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].id}`);
+ console.info(`Type: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceType}`);
+ console.info(`Role: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceRole}`);
+ console.info(`Name: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].name}`);
+ console.info(`Addr: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].address}`);
+ console.info(`SR: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`);
+ console.info(`C ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`);
+ console.info(`CM: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelMasks}`);
+ }
+ if (AudioRendererChangeInfoArray[i].rendererState == 1 && devDescriptor != null) {
+ resultFlag = true;
+ console.info(`ResultFlag for ${i} is: ${resultFlag}`);
+ }
+ }
+});
+```
-getMaxVolume(volumeType: AudioVolumeType): Promise<number>
-Obtains the maximum volume allowed for a stream. This API uses a promise to return the result.
+## AudioCapturerChangeInfoArray9+
-**System API**: This is a system API.
+Defines an **AudioCapturerChangeInfo** array, which is read-only.
-**System capability**: SystemCapability.Multimedia.Audio.Volume
+**System capability**: SystemCapability.Multimedia.Audio.Capturer
-**Parameters**
+## AudioCapturerChangeInfo9+
-| Name | Type | Mandatory| Description |
-| ---------- | ----------------------------------- | ---- | ------------ |
-| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.|
+Describes the audio capturer change event.
-**Return value**
+**System capability**: SystemCapability.Multimedia.Audio.Capturer
-| Type | Description |
-| --------------------- | ----------------------------- |
-| Promise<number> | Promise used to return the maximum volume.|
+| Name | Type | Readable | Writable | Description |
+| ------------- | ---------------------------------------- | -------- | -------- | ---------------------------------------------------------- |
+| streamId | number | Yes | No | Unique ID of an audio stream. |
+| clientUid | number | Yes | No | UID of the audio capturer client.
This is a system API. |
+| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | No | Audio capturer information. |
+| capturerState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API. |
**Example**
```js
-audioGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => {
- console.info('Promised returned to indicate that the maximum volume is obtained.');
-});
-```
-
-### mute9+
+import audio from '@ohos.multimedia.audio';
-mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void>): void
+const audioManager = audio.getAudioManager();
+let audioStreamManager;
+audioManager.getStreamManager((err, data) => {
+ if (err) {
+ console.error(`getStreamManager : Error: ${err}`);
+ } else {
+ console.info('getStreamManager : Success : SUCCESS');
+ audioStreamManager = data;
+ }
+});
-Mutes or unmutes a stream. This API uses an asynchronous callback to return the result.
+let resultFlag = false;
+audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => {
+ for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) {
+ console.info(`## CapChange on is called for element ${i} ##`);
+ console.info(`StrId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`);
+ console.info(`CUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`);
+ console.info(`Src for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`);
+ console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`);
+ console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`);
+ let devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors;
+ for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) {
+ console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`);
+ console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`);
+ console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`);
+ console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`);
+ console.info(`Addr: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`);
+ console.info(`SR: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`);
+ console.info(`C ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`);
+ console.info(`CM ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`);
+ }
+ if (AudioCapturerChangeInfoArray[i].capturerState == 1 && devDescriptor != null) {
+ resultFlag = true;
+ console.info(`ResultFlag for element ${i} is: ${resultFlag}`);
+ }
+ }
+});
+```
-**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY
+## AudioDeviceDescriptors
-This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**.
+Defines an [AudioDeviceDescriptor](#audiodevicedescriptor) array, which is read-only.
-**System API**: This is a system API.
+## AudioDeviceDescriptor
-**System capability**: SystemCapability.Multimedia.Audio.Volume
+Describes an audio device.
-**Parameters**
+**System capability**: SystemCapability.Multimedia.Audio.Device
-| Name | Type | Mandatory| Description |
-| ---------- | ----------------------------------- | ---- | ------------------------------------- |
-| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
-| mute | boolean | Yes | Mute status to set. The value **true** means to mute the stream, and **false** means the opposite.|
-| callback | AsyncCallback<void> | Yes | Callback used to return the result. |
+| Name | Type | Readable | Writable | Description |
+| ----------------------------- | ------------------------- | -------- | -------- | ------------------------------------------------------------ |
+| deviceRole | [DeviceRole](#devicerole) | Yes | No | Device role. |
+| deviceType | [DeviceType](#devicetype) | Yes | No | Device type. |
+| id9+ | number | Yes | No | Device ID. |
+| name9+ | string | Yes | No | Device name. |
+| address9+ | string | Yes | No | Device address. |
+| sampleRates9+ | Array<number> | Yes | No | Supported sampling rates. |
+| channelCounts9+ | Array<number> | Yes | No | Number of channels supported. |
+| channelMasks9+ | Array<number> | Yes | No | Supported channel masks. |
+| networkId9+ | string | Yes | No | ID of the device network.
This is a system API. |
+| interruptGroupId9+ | number | Yes | No | ID of the interruption group to which the device belongs.
This is a system API. |
+| volumeGroupId9+ | number | Yes | No | ID of the volume group to which the device belongs.
This is a system API. |
**Example**
```js
-audioGroupManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => {
- if (err) {
- console.error(`Failed to mute the stream. ${err}`);
- return;
+import audio from '@ohos.multimedia.audio';
+
+function displayDeviceProp(value) {
+ deviceRoleValue = value.deviceRole;
+ deviceTypeValue = value.deviceType;
+}
+
+let deviceRoleValue = null;
+let deviceTypeValue = null;
+const promise = audio.getAudioManager().getDevices(1);
+promise.then(function (value) {
+ console.info('AudioFrameworkTest: Promise: getDevices OUTPUT_DEVICES_FLAG');
+ value.forEach(displayDeviceProp);
+ if (deviceTypeValue != null && deviceRoleValue != null){
+ console.info('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : PASS');
+ } else {
+ console.error('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : FAIL');
}
- console.info('Callback invoked to indicate that the stream is muted.');
});
```
-### mute9+
-
-mute(volumeType: AudioVolumeType, mute: boolean): Promise<void>
-
-Mutes or unmutes a stream. This API uses a promise to return the result.
-
-**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY
+## AudioRendererFilter9+
-This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**.
+Implements filter criteria. Before calling **selectOutputDeviceByFilter**, you must obtain an **AudioRendererFilter** instance.
**System API**: This is a system API.
-**System capability**: SystemCapability.Multimedia.Audio.Volume
+| Name | Type | Mandatory | Description |
+| ------------ | ---------------------------------------- | --------- | ------------------------------------------------------------ |
+| uid | number | Yes | Application ID.
**System capability**: SystemCapability.Multimedia.Audio.Core |
+| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | No | Audio renderer information.
**System capability**: SystemCapability.Multimedia.Audio.Renderer |
+| rendererId | number | No | Unique ID of an audio stream.
**System capability**: SystemCapability.Multimedia.Audio.Renderer |
-**Parameters**
+**Example**
-| Name | Type | Mandatory| Description |
-| ---------- | ----------------------------------- | ---- | ------------------------------------- |
-| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
-| mute | boolean | Yes | Mute status to set. The value **true** means to mute the stream, and **false** means the opposite.|
+```js
+let outputAudioRendererFilter = {
+ "uid":20010041,
+ "rendererInfo": {
+ "contentType":audio.ContentType.CONTENT_TYPE_MUSIC,
+ "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA,
+ "rendererFlags":0 },
+ "rendererId":0 };
+```
-**Return value**
+## AudioRenderer8+
-| Type | Description |
-| ------------------- | ----------------------------- |
-| Promise<void> | Promise used to return the result.|
+Provides APIs for audio rendering. Before calling any API in **AudioRenderer**, you must use [createAudioRenderer](#audiocreateaudiorenderer8) to create an **AudioRenderer** instance.
+
+### Attributes
+
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
+
+| Name | Type | Readable | Writable | Description |
+| ------------------ | -------------------------- | -------- | -------- | --------------------- |
+| state8+ | [AudioState](#audiostate8) | Yes | No | Audio renderer state. |
**Example**
```js
-audioGroupManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => {
- console.info('Promise returned to indicate that the stream is muted.');
-});
+let state = audioRenderer.state;
```
-### isMute9+
-
-isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void
+### getRendererInfo8+
-Checks whether a stream is muted. This API uses an asynchronous callback to return the result.
+getRendererInfo(callback: AsyncCallback): void
-**System API**: This is a system API.
+Obtains the renderer information of this **AudioRenderer** instance. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Volume
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ----------------------------------- | ---- | ----------------------------------------------- |
-| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
-| callback | AsyncCallback<boolean> | Yes | Callback used to return the mute status of the stream. The value **true** means that the stream is muted, and **false** means the opposite.|
+| Name | Type | Mandatory | Description |
+| :------- | :------------------------------------------------------- | :-------- | :------------------------------------------------ |
+| callback | AsyncCallback<[AudioRendererInfo](#audiorendererinfo8)\> | Yes | Callback used to return the renderer information. |
**Example**
```js
-audioGroupManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => {
- if (err) {
- console.error(`Failed to obtain the mute status. ${err}`);
- return;
- }
- console.info(`Callback invoked to indicate that the mute status of the stream is obtained ${value}.`);
+audioRenderer.getRendererInfo((err, rendererInfo) => {
+ console.info('Renderer GetRendererInfo:');
+ console.info(`Renderer content: ${rendererInfo.content}`);
+ console.info(`Renderer usage: ${rendererInfo.usage}`);
+ console.info(`Renderer flags: ${rendererInfo.rendererFlags}`);
});
```
-### isMute9+
-
-isMute(volumeType: AudioVolumeType): Promise<boolean>
-
-Checks whether a stream is muted. This method uses a promise to return the result.
-
-**System API**: This is a system API.
+### getRendererInfo8+
-**System capability**: SystemCapability.Multimedia.Audio.Volume
+getRendererInfo(): Promise
-**Parameters**
+Obtains the renderer information of this **AudioRenderer** instance. This API uses a promise to return the result.
-| Name | Type | Mandatory| Description |
-| ---------- | ----------------------------------- | ---- | ------------ |
-| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.|
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
**Return value**
-| Type | Description |
-| ---------------------- | ------------------------------------------------------ |
-| Promise<boolean> | Promise used to return the mute status of the stream. The value **true** means that the stream is muted, and **false** means the opposite.|
+| Type | Description |
+| -------------------------------------------------- | ------------------------------------------------ |
+| Promise<[AudioRendererInfo](#audiorendererinfo8)\> | Promise used to return the renderer information. |
**Example**
```js
-audioGroupManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => {
- console.info(`Promise returned to indicate that the mute status of the stream is obtained ${value}.`);
+audioRenderer.getRendererInfo().then((rendererInfo) => {
+ console.info('Renderer GetRendererInfo:');
+ console.info(`Renderer content: ${rendererInfo.content}`);
+ console.info(`Renderer usage: ${rendererInfo.usage}`);
+ console.info(`Renderer flags: ${rendererInfo.rendererFlags}`)
+}).catch((err) => {
+ console.error(`AudioFrameworkRenderLog: RendererInfo :ERROR: ${err}`);
});
```
-## AudioStreamManager9+
-
-Implements audio stream management. Before calling any API in **AudioStreamManager**, you must use [getStreamManager](#getstreammanager9) to obtain an **AudioStreamManager** instance.
-
-### getCurrentAudioRendererInfoArray9+
+### getStreamInfo8+
-getCurrentAudioRendererInfoArray(callback: AsyncCallback<AudioRendererChangeInfoArray>): void
+getStreamInfo(callback: AsyncCallback): void
-Obtains the information about the current audio renderers. This API uses an asynchronous callback to return the result.
+Obtains the stream information of this **AudioRenderer** instance. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Multimedia.Audio.Renderer
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ----------------------------------- | -------- | --------------------------- |
-| callback | AsyncCallback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Yes | Callback used to return the audio renderer information.|
+| Name | Type | Mandatory | Description |
+| :------- | :--------------------------------------------------- | :-------- | :---------------------------------------------- |
+| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information. |
**Example**
```js
-audioStreamManager.getCurrentAudioRendererInfoArray(async (err, AudioRendererChangeInfoArray) => {
- console.info('getCurrentAudioRendererInfoArray **** Get Callback Called ****');
- if (err) {
- console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`);
- } else {
- if (AudioRendererChangeInfoArray != null) {
- for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) {
- let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i];
- console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`);
- console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`);
- console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`);
- console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`);
- console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`);
- console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`);
- for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) {
- console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`);
- console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`);
- console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`);
- console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`);
- console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`);
- console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`);
- console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`);
- console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`);
- }
- }
- }
- }
+audioRenderer.getStreamInfo((err, streamInfo) => {
+ console.info('Renderer GetStreamInfo:');
+ console.info(`Renderer sampling rate: ${streamInfo.samplingRate}`);
+ console.info(`Renderer channel: ${streamInfo.channels}`);
+ console.info(`Renderer format: ${streamInfo.sampleFormat}`);
+ console.info(`Renderer encoding type: ${streamInfo.encodingType}`);
});
```
-### getCurrentAudioRendererInfoArray9+
+### getStreamInfo8+
-getCurrentAudioRendererInfoArray(): Promise<AudioRendererChangeInfoArray>
+getStreamInfo(): Promise
-Obtains the information about the current audio renderers. This API uses a promise to return the result.
+Obtains the stream information of this **AudioRenderer** instance. This API uses a promise to return the result.
**System capability**: SystemCapability.Multimedia.Audio.Renderer
**Return value**
-| Type | Description |
-| ---------------------------------------------------------------------------------| --------------------------------------- |
-| Promise<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Promise used to return the audio renderer information. |
+| Type | Description |
+| :--------------------------------------------- | :--------------------------------------------- |
+| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information. |
**Example**
```js
-async function getCurrentAudioRendererInfoArray(){
- await audioStreamManager.getCurrentAudioRendererInfoArray().then( function (AudioRendererChangeInfoArray) {
- console.info(`getCurrentAudioRendererInfoArray ######### Get Promise is called ##########`);
- if (AudioRendererChangeInfoArray != null) {
- for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) {
- let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i];
- console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`);
- console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`);
- console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`);
- console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`);
- console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`);
- console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`);
- for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) {
- console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`);
- console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`);
- console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`);
- console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`);
- console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`);
- console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`);
- console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`);
- console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`);
- }
- }
- }
- }).catch((err) => {
- console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`);
- });
-}
+audioRenderer.getStreamInfo().then((streamInfo) => {
+ console.info('Renderer GetStreamInfo:');
+ console.info(`Renderer sampling rate: ${streamInfo.samplingRate}`);
+ console.info(`Renderer channel: ${streamInfo.channels}`);
+ console.info(`Renderer format: ${streamInfo.sampleFormat}`);
+ console.info(`Renderer encoding type: ${streamInfo.encodingType}`);
+}).catch((err) => {
+ console.error(`ERROR: ${err}`);
+});
+
```
-### getCurrentAudioCapturerInfoArray9+
+### getAudioStreamId9+
-getCurrentAudioCapturerInfoArray(callback: AsyncCallback<AudioCapturerChangeInfoArray>): void
+getAudioStreamId(callback: AsyncCallback): void
-Obtains the information about the current audio capturers. This API uses an asynchronous callback to return the result.
+Obtains the stream ID of this **AudioRenderer** instance. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Multimedia.Audio.Renderer
**Parameters**
-| Name | Type | Mandatory | Description |
-| ---------- | ----------------------------------- | --------- | -------------------------------------------------------- |
-| callback | AsyncCallback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Yes | Callback used to return the audio capturer information.|
+| Name | Type | Mandatory | Description |
+| :------- | :--------------------- | :-------- | :------------------------------------- |
+| callback | AsyncCallback | Yes | Callback used to return the stream ID. |
**Example**
```js
-audioStreamManager.getCurrentAudioCapturerInfoArray(async (err, AudioCapturerChangeInfoArray) => {
- console.info('getCurrentAudioCapturerInfoArray **** Get Callback Called ****');
- if (err) {
- console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`);
- } else {
- if (AudioCapturerChangeInfoArray != null) {
- for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) {
- console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`);
- console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`);
- console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`);
- console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`);
- console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`);
- for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) {
- console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`);
- console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`);
- console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`);
- console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`);
- console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`);
- console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`);
- console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`);
- console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`);
- }
- }
- }
- }
+audioRenderer.getAudioStreamId((err, streamid) => {
+ console.info(`Renderer GetStreamId: ${streamid}`);
});
+
```
-### getCurrentAudioCapturerInfoArray9+
+### getAudioStreamId9+
-getCurrentAudioCapturerInfoArray(): Promise<AudioCapturerChangeInfoArray>
+getAudioStreamId(): Promise
-Obtains the information about the current audio capturers. This API uses a promise to return the result.
+Obtains the stream ID of this **AudioRenderer** instance. This API uses a promise to return the result.
**System capability**: SystemCapability.Multimedia.Audio.Renderer
**Return value**
-| Type | Description |
-| -----------------------------------------------------------------------------| ----------------------------------- |
-| Promise<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Promise used to return the audio capturer information. |
+| Type | Description |
+| :--------------- | :------------------------------------ |
+| Promise | Promise used to return the stream ID. |
**Example**
```js
-async function getCurrentAudioCapturerInfoArray(){
- await audioStreamManager.getCurrentAudioCapturerInfoArray().then( function (AudioCapturerChangeInfoArray) {
- console.info('getCurrentAudioCapturerInfoArray **** Get Promise Called ****');
- if (AudioCapturerChangeInfoArray != null) {
- for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) {
- console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`);
- console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`);
- console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`);
- console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`);
- console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`);
- for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) {
- console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`);
- console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`);
- console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`);
- console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`);
- console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`);
- console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`);
- console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`);
- console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`);
- }
- }
- }
- }).catch((err) => {
- console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`);
- });
-}
-```
-
-### on('audioRendererChange')9+
+audioRenderer.getAudioStreamId().then((streamid) => {
+ console.info(`Renderer getAudioStreamId: ${streamid}`);
+}).catch((err) => {
+ console.error(`ERROR: ${err}`);
+});
-on(type: "audioRendererChange", callback: Callback<AudioRendererChangeInfoArray>): void
+```
-Subscribes to audio renderer change events.
+### start8+
+
+start(callback: AsyncCallback): void
+
+Starts the renderer. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Multimedia.Audio.Renderer
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ---------- | --------- | ------------------------------------------------------------------------ |
-| type | string | Yes | Event type. The event `'audioRendererChange'` is triggered when the audio renderer changes. |
-| callback | Callback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Yes | Callback used to return the result. |
+| Name | Type | Mandatory | Description |
+| -------- | -------------------- | --------- | ----------------------------------- |
+| callback | AsyncCallback\ | Yes | Callback used to return the result. |
**Example**
```js
-audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => {
- for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) {
- let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i];
- console.info(`## RendererChange on is called for ${i} ##`);
- console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`);
- console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`);
- console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`);
- console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`);
- console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`);
- console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`);
- for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) {
- console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`);
- console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`);
- console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`);
- console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`);
- console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`);
- console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`);
- console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`);
- console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`);
- }
+audioRenderer.start((err) => {
+ if (err) {
+ console.error('Renderer start failed.');
+ } else {
+ console.info('Renderer start success.');
}
});
+
```
-### off('audioRendererChange')9+
+### start8+
-off(type: "audioRendererChange");
+start(): Promise
-Unsubscribes from audio renderer change events.
+Starts the renderer. This API uses a promise to return the result.
**System capability**: SystemCapability.Multimedia.Audio.Renderer
-**Parameters**
+**Return value**
-| Name | Type | Mandatory| Description |
-| -------- | ------- | ---- | ---------------- |
-| type | string | Yes | Event type. The event `'audioRendererChange'` is triggered when the audio renderer changes.|
+| Type | Description |
+| -------------- | ---------------------------------- |
+| Promise\ | Promise used to return the result. |
**Example**
```js
-audioStreamManager.off('audioRendererChange');
-console.info('######### RendererChange Off is called #########');
+audioRenderer.start().then(() => {
+ console.info('Renderer started');
+}).catch((err) => {
+ console.error(`ERROR: ${err}`);
+});
+
```
-### on('audioCapturerChange')9+
+### pause8+
-on(type: "audioCapturerChange", callback: Callback<AudioCapturerChangeInfoArray>): void
+pause(callback: AsyncCallback\): void
-Subscribes to audio capturer change events.
+Pauses rendering. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Capturer
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ------- | --------- | ----------------------------------------------------------------------- |
-| type | string | Yes | Event type. The event `'audioCapturerChange'` is triggered when the audio capturer changes. |
-| callback | Callback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Yes | Callback used to return the result. |
+| Name | Type | Mandatory | Description |
+| -------- | -------------------- | --------- | ----------------------------------- |
+| callback | AsyncCallback\ | Yes | Callback used to return the result. |
**Example**
```js
-audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => {
- for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) {
- console.info(`## CapChange on is called for element ${i} ##`);
- console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`);
- console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`);
- console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`);
- console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`);
- console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`);
- var devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors;
- for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) {
- console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`);
- console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`);
- console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`);
- console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`);
- console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`);
- console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`);
- console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`);
- console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`);
- }
+audioRenderer.pause((err) => {
+ if (err) {
+ console.error('Renderer pause failed');
+ } else {
+ console.info('Renderer paused.');
}
});
+
```
-### off('audioCapturerChange')9+
+### pause8+
-off(type: "audioCapturerChange");
+pause(): Promise\
-Unsubscribes from audio capturer change events.
+Pauses rendering. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Capturer
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
-**Parameters**
+**Return value**
-| Name | Type | Mandatory| Description |
-| -------- | -------- | --- | ------------------------------------------------------------- |
-| type | string |Yes | Event type. The event `'audioCapturerChange'` is triggered when the audio capturer changes.|
+| Type | Description |
+| -------------- | ---------------------------------- |
+| Promise\ | Promise used to return the result. |
**Example**
```js
-audioStreamManager.off('audioCapturerChange');
-console.info('######### CapturerChange Off is called #########');
+audioRenderer.pause().then(() => {
+ console.info('Renderer paused');
+}).catch((err) => {
+ console.error(`ERROR: ${err}`);
+});
```
-## AudioRoutingManager9+
-Implements audio routing management. Before calling any API in **AudioRoutingManager**, you must use [getRoutingManager](#getroutingmanager9) to obtain an **AudioRoutingManager** instance.
-
-### getDevices9+
+### drain8+
-getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void
+drain(callback: AsyncCallback\): void
-Obtains the audio devices with a specific flag. This API uses an asynchronous callback to return the result.
+Drains the playback buffer. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Device
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
**Parameters**
-| Name | Type | Mandatory| Description |
-| ---------- | ------------------------------------------------------------ | ---- | -------------------- |
-| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. |
-| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the device list.|
+| Name | Type | Mandatory | Description |
+| -------- | -------------------- | --------- | ----------------------------------- |
+| callback | AsyncCallback\ | Yes | Callback used to return the result. |
**Example**
```js
-var audioManager = audio.getAudioManager();
-audioManager.getRoutingManager((err,AudioRoutingManager)=>{
+audioRenderer.drain((err) => {
if (err) {
- console.error(`AudioFrameworkTest:Callback:failed to get RoutingManager ${err}`);
+ console.error('Renderer drain failed');
} else {
- AudioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => {
- if (err) {
- console.error(`Failed to obtain the device list. ${err}`);
- return;
- }
- console.info('Callback invoked to indicate that the device list is obtained.');
- });
+ console.info('Renderer drained.');
}
-})
-```
-
-### getDevices9+
+});
-getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors>
+```
-Obtains the audio devices with a specific flag. This API uses a promise to return the result.
+### drain8+
-**System capability**: SystemCapability.Multimedia.Audio.Device
+drain(): Promise\
-**Parameters**
+Drains the playback buffer. This API uses a promise to return the result.
-| Name | Type | Mandatory| Description |
-| ---------- | ------------------------- | ---- | ---------------- |
-| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag.|
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
**Return value**
-| Type | Description |
-| ------------------------------------------------------------ | ------------------------- |
-| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise used to return the device list.|
+| Type | Description |
+| -------------- | ---------------------------------- |
+| Promise\ | Promise used to return the result. |
**Example**
```js
-var audioManager = audio.getAudioManager();
-audioManager.getRoutingManager((err,AudioRoutingManager)=>{
- if (err) {
- console.error(`AudioFrameworkTest:Callback:failed to get RoutingManager ${err}`);
- }
- else {
- AudioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => {
- console.info('Promise returned to indicate that the device list is obtained.');
- });
- }
+audioRenderer.drain().then(() => {
+ console.info('Renderer drained successfully');
+}).catch((err) => {
+ console.error(`ERROR: ${err}`);
});
+
```
-### on9+
+### stop8+
-on(type: 'deviceChange', deviceFlag: DeviceFlag, callback: Callback): void
+stop(callback: AsyncCallback\): void
-Subscribes to device change events. When a device is connected or disconnected, registered clients will receive the callback.
+Stops rendering. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Device
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
**Parameters**
-| Name | Type | Mandatory| Description |
-| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- |
-| type | string | Yes | Event type. The value **deviceChange** means the device change event, which is triggered when a device connection status change is detected.|
-| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. |
-| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | Yes | Callback used to return the device update details. |
+| Name | Type | Mandatory | Description |
+| -------- | -------------------- | --------- | ----------------------------------- |
+| callback | AsyncCallback\ | Yes | Callback used to return the result. |
**Example**
```js
-var audioManager = audio.getAudioManager();
-audioManager.getRoutingManager((err,AudioRoutingManager)=>{
+audioRenderer.stop((err) => {
if (err) {
- console.error(`AudioFrameworkTest:Callback:failed to get RoutingManager ${err}`);
- }
- else {
- AudioRoutingManager.on('deviceChange', audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (deviceChanged) => {
- console.info('device change type : ' + deviceChanged.type);
- console.info('device descriptor size : ' + deviceChanged.deviceDescriptors.length);
- console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceRole);
- console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceType);
- });
+ console.error('Renderer stop failed');
+ } else {
+ console.info('Renderer stopped.');
}
});
+
```
-### off9+
+### stop8+
-off(type: 'deviceChange', callback?: Callback): void
+stop(): Promise\
-Unsubscribes from device change events.
+Stops rendering. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Device
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
-**Parameters**
+**Return value**
-| Name | Type | Mandatory| Description |
-| -------- | --------------------------------------------------- | ---- | ------------------------------------------ |
-| type | string | Yes | Event type. The value **deviceChange** means the device change event, which is triggered when a device connection status change is detected.|
-| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | No | Callback used to return the device update details. |
+| Type | Description |
+| -------------- | ---------------------------------- |
+| Promise\ | Promise used to return the result. |
**Example**
```js
-var audioManager = audio.getAudioManager();
-audioManager.getRoutingManager((err,AudioRoutingManager)=>{
- if (err) {
- console.error(`AudioFrameworkTest:Callback:failed to get RoutingManager ${err}`);
- } else {
- AudioRoutingManager.off('deviceChange', (deviceChanged) => {
- console.info('Should be no callback.');
- });
- }
+audioRenderer.stop().then(() => {
+ console.info('Renderer stopped successfully');
+}).catch((err) => {
+ console.error(`ERROR: ${err}`);
});
-```
-### selectInputDevice9+
+```
-selectInputDevice(inputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void
+### release8+
-Selects an audio input device. Currently, only one input device can be selected. This API uses an asynchronous callback to return the result.
+release(callback: AsyncCallback\): void
-**System API**: This is a system API.
+Releases the renderer. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Device
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
**Parameters**
-| Name | Type | Mandatory| Description |
-| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- |
-| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Input device. |
-| callback | AsyncCallback<void> | Yes | Callback used to return the result.|
+| Name | Type | Mandatory | Description |
+| -------- | -------------------- | --------- | ----------------------------------- |
+| callback | AsyncCallback\ | Yes | Callback used to return the result. |
**Example**
-```js
-var audioManager = audio.getAudioManager();
-let inputAudioDeviceDescriptor = [{
- "deviceRole":audio.DeviceRole.INPUT_DEVICE,
- "networkId":audio.LOCAL_NETWORK_ID,
- "interruptGroupId":1,
- "volumeGroupId":1 }];
-var audioRoutingManager;
-async function getRoutingManager(){
- await audioManager.getRoutingManager().then((value) => {
- audioRoutingManager = value;
- audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor, (err) => {
- if (err) {
- console.error(`Result ERROR: ${err}`);
- } else {
- console.info('Select input devices result callback: SUCCESS'); }
- });
- });
-}
-```
-
-### selectInputDevice9+
-
-selectInputDevice(inputAudioDevices: AudioDeviceDescriptors): Promise<void>
+```js
+audioRenderer.release((err) => {
+ if (err) {
+ console.error('Renderer release failed');
+ } else {
+ console.info('Renderer released.');
+ }
+});
-**System API**: This is a system API.
+```
-Selects an audio input device. Currently, only one input device can be selected. This API uses a promise to return the result.
+### release8+
-**System capability**: SystemCapability.Multimedia.Audio.Device
+release(): Promise\
-**Parameters**
+Releases the renderer. This API uses a promise to return the result.
-| Name | Type | Mandatory| Description |
-| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- |
-| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Input device. |
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
**Return value**
-| Type | Description |
-| --------------------- | --------------------------- |
-| Promise<void> | Promise used to return the result.|
+| Type | Description |
+| -------------- | ---------------------------------- |
+| Promise\ | Promise used to return the result. |
**Example**
```js
-var audioManager = audio.getAudioManager();
-let inputAudioDeviceDescriptor =[{
- "deviceRole":audio.DeviceRole.INPUT_DEVICE,
- "networkId":audio.LOCAL_NETWORK_ID,
- "interruptGroupId":1,
- "volumeGroupId":1 }];
-var audioRoutingManager;
+audioRenderer.release().then(() => {
+ console.info('Renderer released successfully');
+}).catch((err) => {
+ console.error(`ERROR: ${err}`);
+});
-async function getRoutingManager(){
- await audioManager.getRoutingManager().then((value) => {
- audioRoutingManager = value;
- audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor).then(() => {
- console.info('Select input devices result promise: SUCCESS');
- }).catch((err) => {
- console.error(`Result ERROR: ${err}`);
- });
- });
-}
```
-### selectOutputDevice9+
-
-selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void
+### write8+
-Selects an audio output device. Currently, only one output device can be selected. This API uses an asynchronous callback to return the result.
+write(buffer: ArrayBuffer, callback: AsyncCallback\): void
-**System API**: This is a system API.
+Writes the buffer. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Device
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
**Parameters**
-| Name | Type | Mandatory| Description |
-| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- |
-| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. |
-| callback | AsyncCallback<void> | Yes | Callback used to return the result.|
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------- | --------- | ------------------------------------------------------------ |
+| buffer | ArrayBuffer | Yes | Buffer to be written. |
+| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned. |
**Example**
-```js
-var audioManager = audio.getAudioManager();
-let outputAudioDeviceDescriptor = [{
- "deviceRole":audio.DeviceRole.OUTPUT_DEVICE,
- "networkId":audio.LOCAL_NETWORK_ID,
- "interruptGroupId":1,
- "volumeGroupId":1 }];
-var audioRoutingManager;
-async function getRoutingManager(){
- await audioManager.getRoutingManager().then((value) => {
- audioRoutingManager = value;
- audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor, (err) => {
- if (err) {
- console.error(`Result ERROR: ${err}`);
- } else {
- console.info('Select output devices result callback: SUCCESS'); }
- });
+```js
+let bufferSize;
+audioRenderer.getBufferSize().then((data)=> {
+ console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`);
+ bufferSize = data;
+ }).catch((err) => {
+ console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`);
});
+console.info(`Buffer size: ${bufferSize}`);
+let context = featureAbility.getContext();
+let path;
+async function getCacheDir(){
+ path = await context.getCacheDir();
}
-```
-
-### selectOutputDevice9+
-
-selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors): Promise<void>
+let filePath = path + '/StarWars10s-2C-48000-4SW.wav';
+let ss = fileio.createStreamSync(filePath, 'r');
+let buf = new ArrayBuffer(bufferSize);
+ss.readSync(buf);
+audioRenderer.write(buf, (err, writtenbytes) => {
+ if (writtenbytes < 0) {
+ console.error('write failed.');
+ } else {
+ console.info(`Actual written bytes: ${writtenbytes}`);
+ }
+});
-**System API**: This is a system API.
+```
-Selects an audio output device. Currently, only one output device can be selected. This API uses a promise to return the result.
+### write8+
-**System capability**: SystemCapability.Multimedia.Audio.Device
+write(buffer: ArrayBuffer): Promise\
-**Parameters**
+Writes the buffer. This API uses a promise to return the result.
-| Name | Type | Mandatory| Description |
-| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- |
-| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. |
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
**Return value**
-| Type | Description |
-| --------------------- | --------------------------- |
-| Promise<void> | Promise used to return the result.|
+| Type | Description |
+| ---------------- | ------------------------------------------------------------ |
+| Promise\ | Promise used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned. |
**Example**
```js
-var audioManager = audio.getAudioManager();
-let outputAudioDeviceDescriptor =[{
- "deviceRole":audio.DeviceRole.OUTPUT_DEVICE,
- "networkId":audio.LOCAL_NETWORK_ID,
- "interruptGroupId":1,
- "volumeGroupId":1 }];
-var audioRoutingManager;
-
-async function getRoutingManager(){
- await audioManager.getRoutingManager().then((value) => {
- audioRoutingManager = value;
- audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor).then(() => {
- console.info('Select output devices result promise: SUCCESS');
- }).catch((err) => {
- console.error(`Result ERROR: ${err}`);
- });
+let bufferSize;
+audioRenderer.getBufferSize().then((data) => {
+ console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`);
+ bufferSize = data;
+ }).catch((err) => {
+ console.info(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`);
});
+console.info(`BufferSize: ${bufferSize}`);
+let context = featureAbility.getContext();
+let path;
+async function getCacheDir(){
+ path = await context.getCacheDir();
}
-```
+let filePath = path + '/StarWars10s-2C-48000-4SW.wav';
+let ss = fileio.createStreamSync(filePath, 'r');
+let buf = new ArrayBuffer(bufferSize);
+ss.readSync(buf);
+audioRenderer.write(buf).then((writtenbytes) => {
+ if (writtenbytes < 0) {
+ console.error('write failed.');
+ } else {
+ console.info(`Actual written bytes: ${writtenbytes}`);
+ }
+}).catch((err) => {
+ console.error(`ERROR: ${err}`);
+});
-### selectOutputDeviceByFilter9+
+```
-selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void
+### getAudioTime8+
-**System API**: This is a system API.
+getAudioTime(callback: AsyncCallback\): void
-Selects an audio output device based on the filter criteria. Currently, only one output device can be selected. This API uses an asynchronous callback to return the result.
+Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Device
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
**Parameters**
-| Name | Type | Mandatory| Description |
-| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- |
-| filter | [AudioRendererFilter](#audiorendererfilter9) | Yes | Filter criteria. |
-| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. |
-| callback | AsyncCallback<void> | Yes | Callback used to return the result.|
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------- | --------- | -------------------------------------- |
+| callback | AsyncCallback\ | Yes | Callback used to return the timestamp. |
**Example**
+
```js
-var audioManager = audio.getAudioManager();
-let outputAudioRendererFilter = {
- "uid":20010041,
- "rendererInfo": {
- "contentType":audio.ContentType.CONTENT_TYPE_MUSIC,
- "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA,
- "rendererFlags":0 },
- "rendererId":0 };
-let outputAudioDeviceDescriptor = [{
- "deviceRole":audio.DeviceRole.OUTPUT_DEVICE,
- "networkId":audio.LOCAL_NETWORK_ID,
- "interruptGroupId":1,
- "volumeGroupId":1 }];
-var audioRoutingManager;
+audioRenderer.getAudioTime((err, timestamp) => {
+ console.info(`Current timestamp: ${timestamp}`);
+});
-async function getRoutingManager(){
- await audioManager.getRoutingManager().then((value) => {
- audioRoutingManager = value;
- audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor, (err) => {
- if (err) {
- console.error(`Result ERROR: ${err}`);
- } else {
- console.info('Select output devices by filter result callback: SUCCESS'); }
- });
- });
-}
```
-### selectOutputDeviceByFilter9+
-
-selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors): Promise<void>
-
-**System API**: This is a system API.
-
-Selects an audio output device based on the filter criteria. Currently, only one output device can be selected. This API uses a promise to return the result.
+### getAudioTime8+
-**System capability**: SystemCapability.Multimedia.Audio.Device
+getAudioTime(): Promise\
-**Parameters**
+Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses a promise to return the result.
-| Name | Type | Mandatory| Description |
-| ----------------------| ------------------------------------------------------------ | ---- | ------------------------- |
-| filter | [AudioRendererFilter](#audiorendererfilter9) | Yes | Filter criteria. |
-| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. |
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
**Return value**
-| Type | Description |
-| --------------------- | --------------------------- |
-| Promise<void> | Promise used to return the result.|
+| Type | Description |
+| ---------------- | ------------------------------------- |
+| Promise\ | Promise used to return the timestamp. |
**Example**
```js
-var audioManager = audio.getAudioManager();
-let outputAudioRendererFilter = {
- "uid":20010041,
- "rendererInfo": {
- "contentType":audio.ContentType.CONTENT_TYPE_MUSIC,
- "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA,
- "rendererFlags":0 },
- "rendererId":0 };
-let outputAudioDeviceDescriptor = [{
- "deviceRole":audio.DeviceRole.OUTPUT_DEVICE,
- "networkId":audio.LOCAL_NETWORK_ID,
- "interruptGroupId":1,
- "volumeGroupId":1 }];
-var audioRoutingManager;
+audioRenderer.getAudioTime().then((timestamp) => {
+ console.info(`Current timestamp: ${timestamp}`);
+}).catch((err) => {
+ console.error(`ERROR: ${err}`);
+});
-async function getRoutingManager(){
- await audioManager.getRoutingManager().then((value) => {
- audioRoutingManager = value;
- audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor).then(() => {
- console.info('Select output devices by filter result promise: SUCCESS');
- }).catch((err) => {
- console.error(`Result ERROR: ${err}`);
- })
- });
-}
```
-## AudioRendererChangeInfo9+
-
-Describes the audio renderer change event.
+### getBufferSize8+
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+getBufferSize(callback: AsyncCallback\): void
-| Name | Type | Readable | Writable | Description |
-| ------------- | ---------------------------------------- | -------- | -------- | ------------------------------------------------------------ |
-| streamId | number | Yes | No | Unique ID of an audio stream. |
-| clientUid | number | Yes | No | UID of the audio renderer client.
This is a system API and cannot be called by third-party applications. |
-| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | No | Audio renderer information. |
-| rendererState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API and cannot be called by third-party applications. |
+Obtains a reasonable minimum buffer size in bytes for rendering. This API uses an asynchronous callback to return the result.
-## AudioRendererChangeInfoArray9+
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
-Describes the **AudioRenderChangeInfo** array, which is read-only.
+**Parameters**
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------- | --------- | ---------------------------------------- |
+| callback | AsyncCallback\ | Yes | Callback used to return the buffer size. |
**Example**
```js
-import audio from '@ohos.multimedia.audio';
-
-var audioStreamManager;
-var resultFlag = false;
-var audioManager = audio.getAudioManager();
-
-audioManager.getStreamManager((err, data) => {
+let bufferSize = audioRenderer.getBufferSize(async(err, bufferSize) => {
if (err) {
- console.error(`Get AudioStream Manager : ERROR : ${err}`);
- } else {
- audioStreamManager = data;
- console.info('Get AudioStream Manager : Success');
+ console.error('getBufferSize error');
}
});
-audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => {
- for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) {
- console.info(`## RendererChange on is called for ${i} ##`);
- console.info(`StreamId for ${i} is: ${AudioRendererChangeInfoArray[i].streamId}`);
- console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfoArray[i].clientUid}`);
- console.info(`Content for ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.content}`);
- console.info(`Stream for ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.usage}`);
- console.info(`Flag ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.rendererFlags}`);
- console.info(`State for ${i} is: ${AudioRendererChangeInfoArray[i].rendererState}`);
- var devDescriptor = AudioRendererChangeInfoArray[i].deviceDescriptors;
- for (let j = 0; j < AudioRendererChangeInfoArray[i].deviceDescriptors.length; j++) {
- console.info(`Id: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].id}`);
- console.info(`Type: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceType}`);
- console.info(`Role: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceRole}`);
- console.info(`Name: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].name}`);
- console.info(`Addr: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].address}`);
- console.info(`SR: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`);
- console.info(`C ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`);
- console.info(`CM: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelMasks}`);
- }
- if (AudioRendererChangeInfoArray[i].rendererState == 1 && devDescriptor != null) {
- resultFlag = true;
- console.info(`ResultFlag for ${i} is: ${resultFlag}`);
+```
+
+### getBufferSize8+
+
+getBufferSize(): Promise\
+
+Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
+
+**Return value**
+
+| Type | Description |
+| ---------------- | --------------------------------------- |
+| Promise\ | Promise used to return the buffer size. |
+
+**Example**
+
+```js
+let bufferSize;
+audioRenderer.getBufferSize().then((data) => {
+ console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`);
+ bufferSize = data;
+}).catch((err) => {
+ console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`);
+});
+
+```
+
+### setRenderRate8+
+
+setRenderRate(rate: AudioRendererRate, callback: AsyncCallback\): void
+
+Sets the render rate. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------------------------- | --------- | ----------------------------------- |
+| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. |
+| callback | AsyncCallback\ | Yes | Callback used to return the result. |
+
+**Example**
+
+```js
+audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL, (err) => {
+ if (err) {
+ console.error('Failed to set params');
+ } else {
+ console.info('Callback invoked to indicate a successful render rate setting.');
+ }
+});
+
+```
+
+### setRenderRate8+
+
+setRenderRate(rate: AudioRendererRate): Promise\
+
+Sets the render rate. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| ---- | ---------------------------------------- | --------- | ------------------ |
+| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. |
+
+**Return value**
+
+| Type | Description |
+| -------------- | ---------------------------------- |
+| Promise\ | Promise used to return the result. |
+
+**Example**
+
+```js
+audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL).then(() => {
+ console.info('setRenderRate SUCCESS');
+}).catch((err) => {
+ console.error(`ERROR: ${err}`);
+});
+
+```
+
+### getRenderRate8+
+
+getRenderRate(callback: AsyncCallback\): void
+
+Obtains the current render rate. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| -------- | ------------------------------------------------------- | --------- | ---------------------------------------------- |
+| callback | AsyncCallback<[AudioRendererRate](#audiorendererrate8)> | Yes | Callback used to return the audio render rate. |
+
+**Example**
+
+```js
+audioRenderer.getRenderRate((err, renderrate) => {
+ console.info(`getRenderRate: ${renderrate}`);
+});
+
+```
+
+### getRenderRate8+
+
+getRenderRate(): Promise\
+
+Obtains the current render rate. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
+
+**Return value**
+
+| Type | Description |
+| ------------------------------------------------- | --------------------------------------------- |
+| Promise<[AudioRendererRate](#audiorendererrate8)> | Promise used to return the audio render rate. |
+
+**Example**
+
+```js
+audioRenderer.getRenderRate().then((renderRate) => {
+ console.info(`getRenderRate: ${renderRate}`);
+}).catch((err) => {
+ console.error(`ERROR: ${err}`);
+});
+
+```
+
+### setInterruptMode9+
+
+setInterruptMode(mode: InterruptMode): Promise<void>
+
+Sets the audio interruption mode for the application. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Audio.Interrupt
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| ---- | -------------------------------- | --------- | ------------------------ |
+| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. |
+
+**Return value**
+
+| Type | Description |
+| ------------------- | ------------------------------------------------------------ |
+| Promise<void> | Promise used to return the result. If the operation is successful, **undefined** is returned. Otherwise, **error** is returned. |
+
+**Example**
+
+```js
+let mode = 0;
+audioRenderer.setInterruptMode(mode).then(data=>{
+ console.info('setInterruptMode Success!');
+}).catch((err) => {
+ console.error(`setInterruptMode Fail: ${err}`);
+});
+
+```
+
+### setInterruptMode9+
+
+setInterruptMode(mode: InterruptMode, callback: AsyncCallback\): void
+
+Sets the audio interruption mode for the application. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Audio.Interrupt
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| -------- | -------------------------------- | --------- | ----------------------------------- |
+| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. |
+| callback | AsyncCallback\ | Yes | Callback used to return the result. |
+
+**Example**
+
+```js
+let mode = 1;
+audioRenderer.setInterruptMode(mode, (err, data)=>{
+ if(err){
+ console.error(`setInterruptMode Fail: ${err}`);
+ }
+ console.info('setInterruptMode Success!');
+});
+
+```
+
+### setVolume9+
+
+setVolume(volume: number): Promise<void>
+
+Sets the volume for the application. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| ------ | ------ | --------- | -------------- |
+| volume | number | Yes | Volume to set. |
+
+**Return value**
+
+| Type | Description |
+| ------------------- | ------------------------------------------------------------ |
+| Promise<void> | Promise used to return the result. If the operation is successful, **undefined** is returned. Otherwise, **error** is returned. |
+
+**Example**
+
+```js
+audioRenderer.setVolume(10).then(data=>{
+ console.info('setVolume Success!');
+}).catch((err) => {
+ console.error(`setVolume Fail: ${err}`);
+});
+
+```
+
+### setVolume9+
+
+setVolume(volume: number, callback: AsyncCallback\): void
+
+Sets the volume for the application. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| -------- | -------------------- | --------- | ----------------------------------- |
+| volume | number | Yes | Volume to set. |
+| callback | AsyncCallback\ | Yes | Callback used to return the result. |
+
+**Example**
+
+```js
+audioRenderer.setVolume(10, (err, data)=>{
+ if(err){
+ console.error(`setVolume Fail: ${err}`);
+ }
+ console.info('setVolume Success!');
+});
+
+```
+
+### on('audioInterrupt')9+
+
+on(type: 'audioInterrupt', callback: Callback\): void
+
+Subscribes to audio interruption events. This API uses a callback to get interrupt events.
+
+Same as [on('interrupt')](#oninterruptdeprecated), this API has obtained the focus before **start**, **pause**, or **stop** of **AudioRenderer** is called. Therefore, you do not need to request the focus.
+
+**System capability**: SystemCapability.Multimedia.Audio.Interrupt
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| -------- | -------------------------------------------- | --------- | ------------------------------------------------------------ |
+| type | string | Yes | Event type. The value **'audioInterrupt'** means the audio interruption event, which is triggered when audio playback is interrupted. |
+| callback | Callback<[InterruptEvent](#interruptevent9)> | Yes | Callback used to return the audio interruption event. |
+
+**Error codes**
+
+For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md).
+
+| ID | Error Message |
+| ------- | ------------------------------- |
+| 6800101 | if input parameter value error. |
+
+**Example**
+
+```js
+let isPlay;
+let started;
+audioRenderer.on('audioInterrupt', async(interruptEvent) => {
+ if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) {
+ switch (interruptEvent.hintType) {
+ case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
+ console.info('Force paused. Stop writing');
+ isPlay = false;
+ break;
+ case audio.InterruptHint.INTERRUPT_HINT_STOP:
+ console.info('Force stopped. Stop writing');
+ isPlay = false;
+ break;
}
+ } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) {
+ switch (interruptEvent.hintType) {
+ case audio.InterruptHint.INTERRUPT_HINT_RESUME:
+ console.info('Resume force paused renderer or ignore');
+ await audioRenderer.start().then(async function () {
+ console.info('AudioInterruptMusic: renderInstant started :SUCCESS ');
+ started = true;
+ }).catch((err) => {
+ console.error(`AudioInterruptMusic: renderInstant start :ERROR : ${err}`);
+ started = false;
+ });
+ if (started) {
+ isPlay = true;
+ console.info(`AudioInterruptMusic Renderer started : isPlay : ${isPlay}`);
+ } else {
+ console.error('AudioInterruptMusic Renderer start failed');
+ }
+ break;
+ case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
+ console.info('Choose to pause or ignore');
+ if (isPlay == true) {
+ isPlay == false;
+ console.info('AudioInterruptMusic: Media PAUSE : TRUE');
+ } else {
+ isPlay = true;
+ console.info('AudioInterruptMusic: Media PLAY : TRUE');
+ }
+ break;
+ }
+ }
+});
+
+```
+
+### on('markReach')8+
+
+on(type: "markReach", frame: number, callback: Callback<number>): void
+
+Subscribes to mark reached events. When the number of frames rendered reaches the value of the **frame** parameter, a callback is invoked.
+
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| :------- | :---------------- | :-------- | :----------------------------------------------------------- |
+| type | string | Yes | Event type. The value is fixed at **'markReach'**. |
+| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. |
+| callback | Callback\ | Yes | Callback invoked when the event is triggered. |
+
+**Example**
+
+```js
+audioRenderer.on('markReach', 1000, (position) => {
+ if (position == 1000) {
+ console.info('ON Triggered successfully');
+ }
+});
+
+```
+
+
+### off('markReach') 8+
+
+off(type: 'markReach'): void
+
+Unsubscribes from mark reached events.
+
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| :--- | :----- | :-------- | :------------------------------------------------- |
+| type | string | Yes | Event type. The value is fixed at **'markReach'**. |
+
+**Example**
+
+```js
+audioRenderer.off('markReach');
+
+```
+
+### on('periodReach') 8+
+
+on(type: "periodReach", frame: number, callback: Callback<number>): void
+
+Subscribes to period reached events. When the number of frames rendered reaches the value of the **frame** parameter, a callback is triggered and the specified value is returned.
+
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| :------- | :---------------- | :-------- | :----------------------------------------------------------- |
+| type | string | Yes | Event type. The value is fixed at **'periodReach'**. |
+| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. |
+| callback | Callback\ | Yes | Callback invoked when the event is triggered. |
+
+**Example**
+
+```js
+audioRenderer.on('periodReach', 1000, (position) => {
+ if (position == 1000) {
+ console.info('ON Triggered successfully');
+ }
+});
+
+```
+
+### off('periodReach') 8+
+
+off(type: 'periodReach'): void
+
+Unsubscribes from period reached events.
+
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| :--- | :----- | :-------- | :--------------------------------------------------- |
+| type | string | Yes | Event type. The value is fixed at **'periodReach'**. |
+
+**Example**
+
+```js
+audioRenderer.off('periodReach')
+
+```
+
+### on('stateChange')8+
+
+on(type: 'stateChange', callback: Callback): void
+
+Subscribes to state change events.
+
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| :------- | :------------------------- | :-------- | :----------------------------------------------------------- |
+| type | string | Yes | Event type. The value **stateChange** means the state change event. |
+| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. |
+
+**Example**
+
+```js
+audioRenderer.on('stateChange', (state) => {
+ if (state == 1) {
+ console.info('audio renderer state is: STATE_PREPARED');
+ }
+ if (state == 2) {
+ console.info('audio renderer state is: STATE_RUNNING');
}
});
+
```
-## AudioCapturerChangeInfo9+
+## AudioCapturer8+
-Describes the audio capturer change event.
+Provides APIs for audio capture. Before calling any API in **AudioCapturer**, you must use [createAudioCapturer](#audiocreateaudiocapturer8) to create an **AudioCapturer** instance.
+
+### Attributes
**System capability**: SystemCapability.Multimedia.Audio.Capturer
-| Name | Type | Readable | Writable | Description |
-| ------------- | ---------------------------------------- | -------- | -------- | ------------------------------------------------------------ |
-| streamId | number | Yes | No | Unique ID of an audio stream. |
-| clientUid | number | Yes | No | UID of the audio capturer client.
This is a system API and cannot be called by third-party applications. |
-| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | No | Audio capturer information. |
-| capturerState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API and cannot be called by third-party applications. |
+| Name | Type | Readable | Writable | Description |
+| :----------------- | :------------------------- | :------- | :------- | :-------------------- |
+| state8+ | [AudioState](#audiostate8) | Yes | No | Audio capturer state. |
+
+**Example**
+
+```js
+let state = audioCapturer.state;
-## AudioCapturerChangeInfoArray9+
+```
-Describes the **AudioCapturerChangeInfo** array, which is read-only.
+### getCapturerInfo8+
+
+getCapturerInfo(callback: AsyncCallback): void
+
+Obtains the capturer information of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Multimedia.Audio.Capturer
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| :------- | :-------------------------------- | :-------- | :------------------------------------------------ |
+| callback | AsyncCallback | Yes | Callback used to return the capturer information. |
+
**Example**
```js
-import audio from '@ohos.multimedia.audio';
-
-const audioManager = audio.getAudioManager();
-let audioStreamManager;
-audioManager.getStreamManager((err, data) => {
+audioCapturer.getCapturerInfo((err, capturerInfo) => {
if (err) {
- console.error(`getStreamManager : Error: ${err}`);
+ console.error('Failed to get capture info');
} else {
- console.info('getStreamManager : Success : SUCCESS');
- audioStreamManager = data;
+ console.info('Capturer getCapturerInfo:');
+ console.info(`Capturer source: ${capturerInfo.source}`);
+ console.info(`Capturer flags: ${capturerInfo.capturerFlags}`);
}
});
-var resultFlag = false;
-audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => {
- for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) {
- console.info(`## CapChange on is called for element ${i} ##`);
- console.info(`StrId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`);
- console.info(`CUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`);
- console.info(`Src for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`);
- console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`);
- console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`);
- var devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors;
- for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) {
- console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`);
- console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`);
- console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`);
- console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`);
- console.info(`Addr: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`);
- console.info(`SR: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`);
- console.info(`C ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`);
- console.info(`CM ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`);
- }
- if (AudioCapturerChangeInfoArray[i].capturerState == 1 && devDescriptor != null) {
- resultFlag = true;
- console.info(`ResultFlag for element ${i} is: ${resultFlag}`);
- }
- }
-});
```
-## AudioDeviceDescriptor
-Describes an audio device.
+### getCapturerInfo8+
-**System capability**: SystemCapability.Multimedia.Audio.Device
+getCapturerInfo(): Promise
-| Name | Type | Readable | Writable | Description |
-| ----------------------------- | ------------------------- | -------- | -------- | ------------------------------------------------------------ |
-| deviceRole | [DeviceRole](#devicerole) | Yes | No | Device role. |
-| deviceType | [DeviceType](#devicetype) | Yes | No | Device type. |
-| id9+ | number | Yes | No | Device ID. |
-| name9+ | string | Yes | No | Device name. |
-| address9+ | string | Yes | No | Device address. |
-| sampleRates9+ | Array<number> | Yes | No | Supported sampling rates. |
-| channelCounts9+ | Array<number> | Yes | No | Number of channels supported. |
-| channelMasks9+ | Array<number> | Yes | No | Supported channel masks. |
-| networkId9+ | string | Yes | No | ID of the device network.
This is a system API and cannot be called by third-party applications. |
-| interruptGroupId9+ | number | Yes | No | ID of the interruption group to which the device belongs.
This is a system API and cannot be called by third-party applications. |
-| volumeGroupId9+ | number | Yes | No | ID of the volume group to which the device belongs.
This is a system API and cannot be called by third-party applications. |
+Obtains the capturer information of this **AudioCapturer** instance. This API uses a promise to return the result.
-## AudioDeviceDescriptors
+**System capability**: SystemCapability.Multimedia.Audio.Capturer
+
+**Return value**
-Array of [AudioDeviceDescriptor](#audiodevicedescriptor), which is read-only.
+| Type | Description |
+| :------------------------------------------------ | :----------------------------------------------- |
+| Promise<[AudioCapturerInfo](#audiocapturerinfo)\> | Promise used to return the capturer information. |
**Example**
```js
-import audio from '@ohos.multimedia.audio';
+audioCapturer.getCapturerInfo().then((audioParamsGet) => {
+ if (audioParamsGet != undefined) {
+ console.info('AudioFrameworkRecLog: Capturer CapturerInfo:');
+ console.info(`AudioFrameworkRecLog: Capturer SourceType: ${audioParamsGet.source}`);
+ console.info(`AudioFrameworkRecLog: Capturer capturerFlags: ${audioParamsGet.capturerFlags}`);
+ } else {
+ console.info(`AudioFrameworkRecLog: audioParamsGet is : ${audioParamsGet}`);
+ console.info('AudioFrameworkRecLog: audioParams getCapturerInfo are incorrect');
+ }
+}).catch((err) => {
+ console.error(`AudioFrameworkRecLog: CapturerInfo :ERROR: ${err}`);
+});
-function displayDeviceProp(value) {
- deviceRoleValue = value.deviceRole;
- deviceTypeValue = value.deviceType;
-}
+```
-var deviceRoleValue = null;
-var deviceTypeValue = null;
-const promise = audio.getAudioManager().getDevices(1);
-promise.then(function (value) {
- console.info('AudioFrameworkTest: Promise: getDevices OUTPUT_DEVICES_FLAG');
- value.forEach(displayDeviceProp);
- if (deviceTypeValue != null && deviceRoleValue != null){
- console.info('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : PASS');
+### getStreamInfo8+
+
+getStreamInfo(callback: AsyncCallback): void
+
+Obtains the stream information of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Audio.Capturer
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| :------- | :--------------------------------------------------- | :-------- | :---------------------------------------------- |
+| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information. |
+
+**Example**
+
+```js
+audioCapturer.getStreamInfo((err, streamInfo) => {
+ if (err) {
+ console.error('Failed to get stream info');
} else {
- console.error('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : FAIL');
+ console.info('Capturer GetStreamInfo:');
+ console.info(`Capturer sampling rate: ${streamInfo.samplingRate}`);
+ console.info(`Capturer channel: ${streamInfo.channels}`);
+ console.info(`Capturer format: ${streamInfo.sampleFormat}`);
+ console.info(`Capturer encoding type: ${streamInfo.encodingType}`);
}
});
+
```
-## AudioRendererFilter9+
+### getStreamInfo8+
-Implements filter criteria. Before calling **selectOutputDeviceByFilter**, you must obtain an **AudioRendererFilter** instance.
+getStreamInfo(): Promise
-**System API**: This is a system API.
+Obtains the stream information of this **AudioCapturer** instance. This API uses a promise to return the result.
-| Name | Type | Mandatory | Description |
-| ------------ | ---------------------------------------- | --------- | ------------------------------------------------------------ |
-| uid | number | Yes | Application ID.
**System capability**: SystemCapability.Multimedia.Audio.Core |
-| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | No | Audio renderer information.
**System capability**: SystemCapability.Multimedia.Audio.Renderer |
-| rendererId | number | No | Unique ID of an audio stream.
**System capability**: SystemCapability.Multimedia.Audio.Renderer |
+**System capability**: SystemCapability.Multimedia.Audio.Capturer
+
+**Return value**
+
+| Type | Description |
+| :--------------------------------------------- | :--------------------------------------------- |
+| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information. |
**Example**
```js
-let outputAudioRendererFilter = {
- "uid":20010041,
- "rendererInfo": {
- "contentType":audio.ContentType.CONTENT_TYPE_MUSIC,
- "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA,
- "rendererFlags":0 },
- "rendererId":0 };
+audioCapturer.getStreamInfo().then((audioParamsGet) => {
+ console.info('getStreamInfo:');
+ console.info(`sampleFormat: ${audioParamsGet.sampleFormat}`);
+ console.info(`samplingRate: ${audioParamsGet.samplingRate}`);
+ console.info(`channels: ${audioParamsGet.channels}`);
+ console.info(`encodingType: ${audioParamsGet.encodingType}`);
+}).catch((err) => {
+ console.error(`getStreamInfo :ERROR: ${err}`);
+});
+
+```
+
+### getAudioStreamId9+
+
+getAudioStreamId(callback: AsyncCallback): void
+
+Obtains the stream ID of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Audio.Capturer
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| :------- | :--------------------- | :-------- | :------------------------------------- |
+| callback | AsyncCallback | Yes | Callback used to return the stream ID. |
+
+**Example**
+
+```js
+audioCapturer.getAudioStreamId((err, streamid) => {
+ console.info(`audioCapturer GetStreamId: ${streamid}`);
+});
+
+```
+
+### getAudioStreamId9+
+
+getAudioStreamId(): Promise
+
+Obtains the stream ID of this **AudioCapturer** instance. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Audio.Capturer
+
+**Return value**
+
+| Type | Description |
+| :--------------- | :------------------------------------ |
+| Promise | Promise used to return the stream ID. |
+
+**Example**
+
+```js
+audioCapturer.getAudioStreamId().then((streamid) => {
+ console.info(`audioCapturer getAudioStreamId: ${streamid}`);
+}).catch((err) => {
+ console.error(`ERROR: ${err}`);
+});
+
+```
+
+### start8+
+
+start(callback: AsyncCallback): void
+
+Starts capturing. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Multimedia.Audio.Capturer
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| :------- | :------------------- | :-------- | :---------------------------------- |
+| callback | AsyncCallback | Yes | Callback used to return the result. |
+
+**Example**
+
+```js
+audioCapturer.start((err) => {
+ if (err) {
+ console.error('Capturer start failed.');
+ } else {
+ console.info('Capturer start success.');
+ }
+});
+
```
-## AudioRenderer8+
-Provides APIs for audio rendering. Before calling any API in **AudioRenderer**, you must use [createAudioRenderer](#audiocreateaudiorenderer8) to create an **AudioRenderer** instance.
+### start8+
-### Attributes
+start(): Promise
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+Starts capturing. This API uses a promise to return the result.
-| Name | Type | Readable | Writable | Description |
-| ------------------ | -------------------------- | -------- | -------- | --------------------- |
-| state8+ | [AudioState](#audiostate8) | Yes | No | Audio renderer state. |
+**System capability**: SystemCapability.Multimedia.Audio.Capturer
+
+**Return value**
+
+| Type | Description |
+| :------------- | :--------------------------------- |
+| Promise | Promise used to return the result. |
**Example**
```js
-var state = audioRenderer.state;
+audioCapturer.start().then(() => {
+ console.info('AudioFrameworkRecLog: ---------START---------');
+ console.info('AudioFrameworkRecLog: Capturer started: SUCCESS');
+ console.info(`AudioFrameworkRecLog: AudioCapturer: STATE: ${audioCapturer.state}`);
+ console.info('AudioFrameworkRecLog: Capturer started: SUCCESS');
+ if ((audioCapturer.state == audio.AudioState.STATE_RUNNING)) {
+ console.info('AudioFrameworkRecLog: AudioCapturer is in Running State');
+ }
+}).catch((err) => {
+ console.info(`AudioFrameworkRecLog: Capturer start :ERROR : ${err}`);
+});
+
```
-### getRendererInfo8+
+### stop8+
-getRendererInfo(callback: AsyncCallback): void
+stop(callback: AsyncCallback): void
-Obtains the renderer information of this **AudioRenderer** instance. This API uses an asynchronous callback to return the result.
+Stops capturing. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+**System capability**: SystemCapability.Multimedia.Audio.Capturer
**Parameters**
-| Name | Type | Mandatory | Description |
-| :------- | :------------------------------------------------------- | :-------- | :------------------------------------------------ |
-| callback | AsyncCallback<[AudioRendererInfo](#audiorendererinfo8)\> | Yes | Callback used to return the renderer information. |
+| Name | Type | Mandatory | Description |
+| :------- | :------------------- | :-------- | :---------------------------------- |
+| callback | AsyncCallback | Yes | Callback used to return the result. |
**Example**
```js
-audioRenderer.getRendererInfo((err, rendererInfo) => {
- console.info('Renderer GetRendererInfo:');
- console.info(`Renderer content: ${rendererInfo.content}`);
- console.info(`Renderer usage: ${rendererInfo.usage}`);
- console.info(`Renderer flags: ${rendererInfo.rendererFlags}`);
+audioCapturer.stop((err) => {
+ if (err) {
+ console.error('Capturer stop failed');
+ } else {
+ console.info('Capturer stopped.');
+ }
});
+
```
-### getRendererInfo8+
-getRendererInfo(): Promise
+### stop8+
-Obtains the renderer information of this **AudioRenderer** instance. This API uses a promise to return the result.
+stop(): Promise
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+Stops capturing. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Audio.Capturer
**Return value**
-| Type | Description |
-| -------------------------------------------------- | ------------------------------------------------ |
-| Promise<[AudioRendererInfo](#audiorendererinfo8)\> | Promise used to return the renderer information. |
+| Type | Description |
+| :------------- | :--------------------------------- |
+| Promise | Promise used to return the result. |
**Example**
```js
-audioRenderer.getRendererInfo().then((rendererInfo) => {
- console.info('Renderer GetRendererInfo:');
- console.info(`Renderer content: ${rendererInfo.content}`);
- console.info(`Renderer usage: ${rendererInfo.usage}`);
- console.info(`Renderer flags: ${rendererInfo.rendererFlags}`)
+audioCapturer.stop().then(() => {
+ console.info('AudioFrameworkRecLog: ---------STOP RECORD---------');
+ console.info('AudioFrameworkRecLog: Capturer stopped: SUCCESS');
+ if ((audioCapturer.state == audio.AudioState.STATE_STOPPED)){
+ console.info('AudioFrameworkRecLog: State is Stopped:');
+ }
}).catch((err) => {
- console.error(`AudioFrameworkRenderLog: RendererInfo :ERROR: ${err}`);
+ console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`);
});
+
```
-### getStreamInfo8+
+### release8+
-getStreamInfo(callback: AsyncCallback): void
+release(callback: AsyncCallback): void
-Obtains the stream information of this **AudioRenderer** instance. This API uses an asynchronous callback to return the result.
+Releases this **AudioCapturer** instance. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+**System capability**: SystemCapability.Multimedia.Audio.Capturer
**Parameters**
-| Name | Type | Mandatory | Description |
-| :------- | :--------------------------------------------------- | :-------- | :---------------------------------------------- |
-| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information. |
+| Name | Type | Mandatory | Description |
+| :------- | :------------------- | :-------- | :---------------------------------- |
+| callback | AsyncCallback | Yes | Callback used to return the result. |
**Example**
```js
-audioRenderer.getStreamInfo((err, streamInfo) => {
- console.info('Renderer GetStreamInfo:');
- console.info(`Renderer sampling rate: ${streamInfo.samplingRate}`);
- console.info(`Renderer channel: ${streamInfo.channels}`);
- console.info(`Renderer format: ${streamInfo.sampleFormat}`);
- console.info(`Renderer encoding type: ${streamInfo.encodingType}`);
+audioCapturer.release((err) => {
+ if (err) {
+ console.error('capturer release failed');
+ } else {
+ console.info('capturer released.');
+ }
});
+
```
-### getStreamInfo8+
-getStreamInfo(): Promise
+### release8+
-Obtains the stream information of this **AudioRenderer** instance. This API uses a promise to return the result.
+release(): Promise
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+Releases this **AudioCapturer** instance. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Audio.Capturer
**Return value**
-| Type | Description |
-| :--------------------------------------------- | :--------------------------------------------- |
-| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information. |
+| Type | Description |
+| :------------- | :--------------------------------- |
+| Promise | Promise used to return the result. |
**Example**
```js
-audioRenderer.getStreamInfo().then((streamInfo) => {
- console.info('Renderer GetStreamInfo:');
- console.info(`Renderer sampling rate: ${streamInfo.samplingRate}`);
- console.info(`Renderer channel: ${streamInfo.channels}`);
- console.info(`Renderer format: ${streamInfo.sampleFormat}`);
- console.info(`Renderer encoding type: ${streamInfo.encodingType}`);
+let stateFlag;
+audioCapturer.release().then(() => {
+ console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------');
+ console.info('AudioFrameworkRecLog: Capturer release : SUCCESS');
+ console.info(`AudioFrameworkRecLog: AudioCapturer : STATE : ${audioCapturer.state}`);
+ console.info(`AudioFrameworkRecLog: stateFlag : ${stateFlag}`);
}).catch((err) => {
- console.error(`ERROR: ${err}`);
+ console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`);
});
```
-### start8+
+### read8+
-start(callback: AsyncCallback): void
+read(size: number, isBlockingRead: boolean, callback: AsyncCallback): void
-Starts the renderer. This API uses an asynchronous callback to return the result.
+Reads the buffer. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+**System capability**: SystemCapability.Multimedia.Audio.Capturer
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | -------------------- | --------- | ----------------------------------- |
-| callback | AsyncCallback\ | Yes | Callback used to return the result. |
+| Name | Type | Mandatory | Description |
+| :------------- | :-------------------------- | :-------- | :----------------------------------- |
+| size | number | Yes | Number of bytes to read. |
+| isBlockingRead | boolean | Yes | Whether to block the read operation. |
+| callback | AsyncCallback | Yes | Callback used to return the buffer. |
**Example**
```js
-audioRenderer.start((err) => {
- if (err) {
- console.error('Renderer start failed.');
- } else {
- console.info('Renderer start success.');
+let bufferSize;
+audioCapturer.getBufferSize().then((data) => {
+ console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`);
+ bufferSize = data;
+ }).catch((err) => {
+ console.error(`AudioFrameworkRecLog: getBufferSize: ERROR: ${err}`);
+ });
+audioCapturer.read(bufferSize, true, async(err, buffer) => {
+ if (!err) {
+ console.info('Success in reading the buffer data');
}
});
```
-### start8+
+### read8+
-start(): Promise
+read(size: number, isBlockingRead: boolean): Promise
-Starts the renderer. This API uses a promise to return the result.
+Reads the buffer. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+**System capability**: SystemCapability.Multimedia.Audio.Capturer
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| :------------- | :------ | :-------- | :----------------------------------- |
+| size | number | Yes | Number of bytes to read. |
+| isBlockingRead | boolean | Yes | Whether to block the read operation. |
**Return value**
-| Type | Description |
-| -------------- | ---------------------------------- |
-| Promise\ | Promise used to return the result. |
+| Type | Description |
+| :-------------------- | :----------------------------------------------------------- |
+| Promise | Promise used to return the result. If the operation is successful, the buffer data read is returned; otherwise, an error code is returned. |
**Example**
```js
-audioRenderer.start().then(() => {
- console.info('Renderer started');
+let bufferSize;
+audioCapturer.getBufferSize().then((data) => {
+ console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`);
+ bufferSize = data;
+ }).catch((err) => {
+ console.info(`AudioFrameworkRecLog: getBufferSize: ERROR ${err}`);
+ });
+console.info(`Buffer size: ${bufferSize}`);
+audioCapturer.read(bufferSize, true).then((buffer) => {
+ console.info('buffer read successfully');
}).catch((err) => {
- console.error(`ERROR: ${err}`);
+ console.info(`ERROR : ${err}`);
});
```
-### pause8+
+### getAudioTime8+
-pause(callback: AsyncCallback\): void
+getAudioTime(callback: AsyncCallback): void
-Pauses rendering. This API uses an asynchronous callback to return the result.
+Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+**System capability**: SystemCapability.Multimedia.Audio.Capturer
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | -------------------- | --------- | ----------------------------------- |
-| callback | AsyncCallback\ | Yes | Callback used to return the result. |
+| Name | Type | Mandatory | Description |
+| :------- | :--------------------- | :-------- | :---------------------------------- |
+| callback | AsyncCallback | Yes | Callback used to return the result. |
**Example**
```js
-audioRenderer.pause((err) => {
- if (err) {
- console.error('Renderer pause failed');
- } else {
- console.info('Renderer paused.');
- }
+audioCapturer.getAudioTime((err, timestamp) => {
+ console.info(`Current timestamp: ${timestamp}`);
});
```
-### pause8+
+### getAudioTime8+
-pause(): Promise\
+getAudioTime(): Promise
-Pauses rendering. This API uses a promise to return the result.
+Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+**System capability**: SystemCapability.Multimedia.Audio.Capturer
**Return value**
-| Type | Description |
-| -------------- | ---------------------------------- |
-| Promise\ | Promise used to return the result. |
+| Type | Description |
+| :--------------- | :------------------------------------ |
+| Promise | Promise used to return the timestamp. |
**Example**
```js
-audioRenderer.pause().then(() => {
- console.info('Renderer paused');
+audioCapturer.getAudioTime().then((audioTime) => {
+ console.info(`AudioFrameworkRecLog: AudioCapturer getAudioTime : Success ${audioTime}`);
}).catch((err) => {
- console.error(`ERROR: ${err}`);
+ console.info(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`);
});
```
-### drain8+
+### getBufferSize8+
-drain(callback: AsyncCallback\): void
+getBufferSize(callback: AsyncCallback): void
-Drains the playback buffer. This API uses an asynchronous callback to return the result.
+Obtains a reasonable minimum buffer size in bytes for capturing. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+**System capability**: SystemCapability.Multimedia.Audio.Capturer
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | -------------------- | --------- | ----------------------------------- |
-| callback | AsyncCallback\ | Yes | Callback used to return the result. |
+| Name | Type | Mandatory | Description |
+| :------- | :--------------------- | :-------- | :--------------------------------------- |
+| callback | AsyncCallback | Yes | Callback used to return the buffer size. |
**Example**
```js
-audioRenderer.drain((err) => {
- if (err) {
- console.error('Renderer drain failed');
- } else {
- console.info('Renderer drained.');
+audioCapturer.getBufferSize((err, bufferSize) => {
+ if (!err) {
+ console.info(`BufferSize : ${bufferSize}`);
+ audioCapturer.read(bufferSize, true).then((buffer) => {
+ console.info(`Buffer read is ${buffer}`);
+ }).catch((err) => {
+ console.error(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`);
+ });
}
});
```
-### drain8+
+### getBufferSize8+
-drain(): Promise\
+getBufferSize(): Promise
-Drains the playback buffer. This API uses a promise to return the result.
+Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+**System capability**: SystemCapability.Multimedia.Audio.Capturer
**Return value**
-| Type | Description |
-| -------------- | ---------------------------------- |
-| Promise\ | Promise used to return the result. |
+| Type | Description |
+| :--------------- | :-------------------------------------- |
+| Promise | Promise used to return the buffer size. |
**Example**
```js
-audioRenderer.drain().then(() => {
- console.info('Renderer drained successfully');
+let bufferSize;
+audioCapturer.getBufferSize().then((data) => {
+ console.info(`AudioFrameworkRecLog: getBufferSize :SUCCESS ${data}`);
+ bufferSize = data;
}).catch((err) => {
- console.error(`ERROR: ${err}`);
+ console.info(`AudioFrameworkRecLog: getBufferSize :ERROR : ${err}`);
});
```
-### stop8+
+### on('markReach')8+
-stop(callback: AsyncCallback\): void
+on(type: "markReach", frame: number, callback: Callback<number>): void
-Stops rendering. This API uses an asynchronous callback to return the result.
+Subscribes to mark reached events. When the number of frames captured reaches the value of the **frame** parameter, a callback is invoked.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+**System capability**: SystemCapability.Multimedia.Audio.Capturer
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | -------------------- | --------- | ----------------------------------- |
-| callback | AsyncCallback\ | Yes | Callback used to return the result. |
+| Name | Type | Mandatory | Description |
+| :------- | :---------------- | :-------- | :----------------------------------------------------------- |
+| type | string | Yes | Event type. The value is fixed at **'markReach'**. |
+| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. |
+| callback | Callback\ | Yes | Callback invoked when the event is triggered. |
**Example**
```js
-audioRenderer.stop((err) => {
- if (err) {
- console.error('Renderer stop failed');
- } else {
- console.info('Renderer stopped.');
+audioCapturer.on('markReach', 1000, (position) => {
+ if (position == 1000) {
+ console.info('ON Triggered successfully');
}
});
```
-### stop8+
+### off('markReach')8+
-stop(): Promise\
+off(type: 'markReach'): void
-Stops rendering. This API uses a promise to return the result.
+Unsubscribes from mark reached events.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+**System capability**: SystemCapability.Multimedia.Audio.Capturer
-**Return value**
+**Parameters**
-| Type | Description |
-| -------------- | ---------------------------------- |
-| Promise\ | Promise used to return the result. |
+| Name | Type | Mandatory | Description |
+| :--- | :----- | :-------- | :------------------------------------------------- |
+| type | string | Yes | Event type. The value is fixed at **'markReach'**. |
**Example**
```js
-audioRenderer.stop().then(() => {
- console.info('Renderer stopped successfully');
-}).catch((err) => {
- console.error(`ERROR: ${err}`);
-});
+audioCapturer.off('markReach');
```
-### release8+
+### on('periodReach')8+
-release(callback: AsyncCallback\): void
+on(type: "periodReach", frame: number, callback: Callback<number>): void
-Releases the renderer. This API uses an asynchronous callback to return the result.
+Subscribes to period reached events. When the number of frames captured reaches the value of the **frame** parameter, a callback is triggered and the specified value is returned.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+**System capability**: SystemCapability.Multimedia.Audio.Capturer
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | -------------------- | --------- | ----------------------------------- |
-| callback | AsyncCallback\ | Yes | Callback used to return the result. |
+| Name | Type | Mandatory | Description |
+| :------- | :---------------- | :-------- | :----------------------------------------------------------- |
+| type | string | Yes | Event type. The value is fixed at **'periodReach'**. |
+| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. |
+| callback | Callback\ | Yes | Callback invoked when the event is triggered. |
**Example**
```js
-audioRenderer.release((err) => {
- if (err) {
- console.error('Renderer release failed');
- } else {
- console.info('Renderer released.');
+audioCapturer.on('periodReach', 1000, (position) => {
+ if (position == 1000) {
+ console.info('ON Triggered successfully');
}
});
```
-### release8+
+### off('periodReach')8+
-release(): Promise\
+off(type: 'periodReach'): void
-Releases the renderer. This API uses a promise to return the result.
+Unsubscribes from period reached events.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+**System capability**: SystemCapability.Multimedia.Audio.Capturer
-**Return value**
+**Parameters**
-| Type | Description |
-| -------------- | ---------------------------------- |
-| Promise\ | Promise used to return the result. |
+| Name | Type | Mandatory | Description |
+| :--- | :----- | :-------- | :--------------------------------------------------- |
+| type | string | Yes | Event type. The value is fixed at **'periodReach'**. |
**Example**
```js
-audioRenderer.release().then(() => {
- console.info('Renderer released successfully');
-}).catch((err) => {
- console.error(`ERROR: ${err}`);
-});
+audioCapturer.off('periodReach')
```
-### write8+
+### on('stateChange')8+
-write(buffer: ArrayBuffer, callback: AsyncCallback\): void
+on(type: 'stateChange', callback: Callback): void
-Writes the buffer. This API uses an asynchronous callback to return the result.
+Subscribes to state change events.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+**System capability**: SystemCapability.Multimedia.Audio.Capturer
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ---------------------- | --------- | ------------------------------------------------------------ |
-| buffer | ArrayBuffer | Yes | Buffer to be written. |
-| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned. |
+| Name | Type | Mandatory | Description |
+| :------- | :------------------------- | :-------- | :----------------------------------------------------------- |
+| type | string | Yes | Event type. The value **stateChange** means the state change event. |
+| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. |
**Example**
```js
-var bufferSize;
-audioRenderer.getBufferSize().then((data)=> {
- console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`);
- bufferSize = data;
- }).catch((err) => {
- console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`);
- });
-console.info(`Buffer size: ${bufferSize}`);
-var context = featureAbility.getContext();
-var path;
-async function getCacheDir(){
- path = await context.getCacheDir();
-}
-var filePath = path + '/StarWars10s-2C-48000-4SW.wav';
-let ss = fileio.createStreamSync(filePath, 'r');
-let buf = new ArrayBuffer(bufferSize);
-ss.readSync(buf);
-audioRenderer.write(buf, (err, writtenbytes) => {
- if (writtenbytes < 0) {
- console.error('write failed.');
- } else {
- console.info(`Actual written bytes: ${writtenbytes}`);
+audioCapturer.on('stateChange', (state) => {
+ if (state == 1) {
+ console.info('audio capturer state is: STATE_PREPARED');
+ }
+ if (state == 2) {
+ console.info('audio capturer state is: STATE_RUNNING');
}
});
```
-### write8+
-
-write(buffer: ArrayBuffer): Promise\
+## ToneType9+
-Writes the buffer. This API uses a promise to return the result.
+Enumerates the tone types of the player.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+**System API**: This is a system API.
-**Return value**
+**System capability**: SystemCapability.Multimedia.Audio.Tone
-| Type | Description |
-| ---------------- | ------------------------------------------------------------ |
-| Promise\ | Promise used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned. |
+| Name | Default Value | Description |
+| :----------------------------------------------- | :------------ | :-------------------------------------------- |
+| TONE_TYPE_DIAL_0 | 0 | DTMF tone of key 0. |
+| TONE_TYPE_DIAL_1 | 1 | DTMF tone of key 1. |
+| TONE_TYPE_DIAL_2 | 2 | DTMF tone of key 2. |
+| TONE_TYPE_DIAL_3 | 3 | DTMF tone of key 3. |
+| TONE_TYPE_DIAL_4 | 4 | DTMF tone of key 4. |
+| TONE_TYPE_DIAL_5 | 5 | DTMF tone of key 5. |
+| TONE_TYPE_DIAL_6 | 6 | DTMF tone of key 6. |
+| TONE_TYPE_DIAL_7 | 7 | DTMF tone of key 7. |
+| TONE_TYPE_DIAL_8 | 8 | DTMF tone of key 8. |
+| TONE_TYPE_DIAL_9 | 9 | DTMF tone of key 9. |
+| TONE_TYPE_DIAL_S | 10 | DTMF tone of the star key (*). |
+| TONE_TYPE_DIAL_P | 11 | DTMF tone of the pound key (#). |
+| TONE_TYPE_DIAL_A | 12 | DTMF tone of key A. |
+| TONE_TYPE_DIAL_B | 13 | DTMF tone of key B. |
+| TONE_TYPE_DIAL_C | 14 | DTMF tone of key C. |
+| TONE_TYPE_DIAL_D | 15 | DTMF tone of key D. |
+| TONE_TYPE_COMMON_SUPERVISORY_DIAL | 100 | Supervisory tone - dial tone. |
+| TONE_TYPE_COMMON_SUPERVISORY_BUSY | 101 | Supervisory tone - busy. |
+| TONE_TYPE_COMMON_SUPERVISORY_CONGESTION | 102 | Supervisory tone - congestion. |
+| TONE_TYPE_COMMON_SUPERVISORY_RADIO_ACK | 103 | Supervisory tone - radio path acknowledgment. |
+| TONE_TYPE_COMMON_SUPERVISORY_RADIO_NOT_AVAILABLE | 104 | Supervisory tone - radio path not available. |
+| TONE_TYPE_COMMON_SUPERVISORY_CALL_WAITING | 106 | Supervisory tone - call waiting tone. |
+| TONE_TYPE_COMMON_SUPERVISORY_RINGTONE | 107 | Supervisory tone - ringing tone. |
+| TONE_TYPE_COMMON_PROPRIETARY_BEEP | 200 | Proprietary tone - beep tone. |
+| TONE_TYPE_COMMON_PROPRIETARY_ACK | 201 | Proprietary tone - ACK. |
+| TONE_TYPE_COMMON_PROPRIETARY_PROMPT | 203 | Proprietary tone - PROMPT. |
+| TONE_TYPE_COMMON_PROPRIETARY_DOUBLE_BEEP | 204 | Proprietary tone - double beep tone. |
-**Example**
+## TonePlayer9+
-```js
-var bufferSize;
-audioRenderer.getBufferSize().then((data) => {
- console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`);
- bufferSize = data;
- }).catch((err) => {
- console.info(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`);
- });
-console.info(`BufferSize: ${bufferSize}`);
-var context = featureAbility.getContext();
-var path;
-async function getCacheDir(){
- path = await context.getCacheDir();
-}
-var filePath = path + '/StarWars10s-2C-48000-4SW.wav';
-let ss = fileio.createStreamSync(filePath, 'r');
-let buf = new ArrayBuffer(bufferSize);
-ss.readSync(buf);
-audioRenderer.write(buf).then((writtenbytes) => {
- if (writtenbytes < 0) {
- console.error('write failed.');
- } else {
- console.info(`Actual written bytes: ${writtenbytes}`);
- }
-}).catch((err) => {
- console.error(`ERROR: ${err}`);
-});
+Provides APIs for playing and managing DTMF tones, such as dial tones, ringback tones, supervisory tones, and proprietary tones.
-```
+**System API**: This is a system API.
-### getAudioTime8+
+### load9+
-getAudioTime(callback: AsyncCallback\): void
+load(type: ToneType, callback: AsyncCallback<void>): void
-Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses an asynchronous callback to return the result.
+Loads the DTMF tone configuration. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+**System capability**: SystemCapability.Multimedia.Audio.Tone
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ---------------------- | --------- | -------------------------------------- |
-| callback | AsyncCallback\ | Yes | Callback used to return the timestamp. |
+| Name | Type | Mandatory | Description |
+| :------- | :--------------------- | :-------- | :---------------------------------- |
+| type | [ToneType](#tonetype9) | Yes | Tone type. |
+| callback | AsyncCallback | Yes | Callback used to return the result. |
**Example**
```js
-audioRenderer.getAudioTime((err, timestamp) => {
- console.info(`Current timestamp: ${timestamp}`);
+tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_5, (err) => {
+ if (err) {
+ console.error(`callback call load failed error: ${err.message}`);
+ return;
+ } else {
+ console.info('callback call load success');
+ }
});
```
-### getAudioTime8+
+### load9+
-getAudioTime(): Promise\
+load(type: ToneType): Promise<void>
-Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses a promise to return the result.
+Loads the DTMF tone configuration. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+**System capability**: SystemCapability.Multimedia.Audio.Tone
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| :--- | :--------------------- | :-------- | ----------- |
+| type | [ToneType](#tonetype9) | Yes | Tone type. |
**Return value**
-| Type | Description |
-| ---------------- | ------------------------------------- |
-| Promise\ | Promise used to return the timestamp. |
+| Type | Description |
+| :------------- | :--------------------------------- |
+| Promise | Promise used to return the result. |
**Example**
```js
-audioRenderer.getAudioTime().then((timestamp) => {
- console.info(`Current timestamp: ${timestamp}`);
-}).catch((err) => {
- console.error(`ERROR: ${err}`);
+tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_1).then(() => {
+ console.info('promise call load ');
+}).catch(() => {
+ console.error('promise call load fail');
});
```
-### getBufferSize8+
+### start9+
-getBufferSize(callback: AsyncCallback\): void
+start(callback: AsyncCallback<void>): void
-Obtains a reasonable minimum buffer size in bytes for rendering. This API uses an asynchronous callback to return the result.
+Starts DTMF tone playing. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+**System capability**: SystemCapability.Multimedia.Audio.Tone
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ---------------------- | --------- | ---------------------------------------- |
-| callback | AsyncCallback\ | Yes | Callback used to return the buffer size. |
+| Name | Type | Mandatory | Description |
+| :------- | :------------------- | :-------- | :---------------------------------- |
+| callback | AsyncCallback | Yes | Callback used to return the result. |
**Example**
```js
-var bufferSize = audioRenderer.getBufferSize(async(err, bufferSize) => {
+tonePlayer.start((err) => {
if (err) {
- console.error('getBufferSize error');
+ console.error(`callback call start failed error: ${err.message}`);
+ return;
+ } else {
+ console.info('callback call start success');
}
});
```
-### getBufferSize8+
+### start9+
-getBufferSize(): Promise\
+start(): Promise<void>
-Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a promise to return the result.
+Starts DTMF tone playing. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+**System capability**: SystemCapability.Multimedia.Audio.Tone
**Return value**
-| Type | Description |
-| ---------------- | --------------------------------------- |
-| Promise\ | Promise used to return the buffer size. |
+| Type | Description |
+| :------------- | :--------------------------------- |
+| Promise | Promise used to return the result. |
**Example**
```js
-var bufferSize;
-audioRenderer.getBufferSize().then((data) => {
- console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`);
- bufferSize = data;
-}).catch((err) => {
- console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`);
+tonePlayer.start().then(() => {
+ console.info('promise call start');
+}).catch(() => {
+ console.error('promise call start fail');
});
```
-### setRenderRate8+
+### stop9+
-setRenderRate(rate: AudioRendererRate, callback: AsyncCallback\): void
+stop(callback: AsyncCallback<void>): void
-Sets the render rate. This API uses an asynchronous callback to return the result.
+Stops the tone that is being played. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+**System capability**: SystemCapability.Multimedia.Audio.Tone
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ---------------------------------------- | --------- | ----------------------------------- |
-| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. |
-| callback | AsyncCallback\ | Yes | Callback used to return the result. |
+| Name | Type | Mandatory | Description |
+| :------- | :------------------- | :-------- | :---------------------------------- |
+| callback | AsyncCallback | Yes | Callback used to return the result. |
**Example**
```js
-audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL, (err) => {
+tonePlayer.stop((err) => {
if (err) {
- console.error('Failed to set params');
+ console.error(`callback call stop error: ${err.message}`);
+ return;
} else {
- console.info('Callback invoked to indicate a successful render rate setting.');
+ console.error('callback call stop success ');
}
});
```
-### setRenderRate8+
-
-setRenderRate(rate: AudioRendererRate): Promise\
-
-Sets the render rate. This API uses a promise to return the result.
+### stop9+
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+stop(): Promise<void>
-**Parameters**
+Stops the tone that is being played. This API uses a promise to return the result.
-| Name | Type | Mandatory | Description |
-| ---- | ---------------------------------------- | --------- | ------------------ |
-| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. |
+**System capability**: SystemCapability.Multimedia.Audio.Tone
**Return value**
| Type | Description |
-| -------------- | ---------------------------------- |
-| Promise\ | Promise used to return the result. |
+| :------------- | :--------------------------------- |
+| Promise | Promise used to return the result. |
**Example**
```js
-audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL).then(() => {
- console.info('setRenderRate SUCCESS');
-}).catch((err) => {
- console.error(`ERROR: ${err}`);
+tonePlayer.stop().then(() => {
+ console.info('promise call stop finish');
+}).catch(() => {
+ console.error('promise call stop fail');
});
```
-### getRenderRate8+
+### release9+
-getRenderRate(callback: AsyncCallback\): void
+release(callback: AsyncCallback<void>): void
-Obtains the current render rate. This API uses an asynchronous callback to return the result.
+Releases the resources associated with the **TonePlayer** instance. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+**System capability**: SystemCapability.Multimedia.Audio.Tone
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ------------------------------------------------------- | --------- | ---------------------------------------------- |
-| callback | AsyncCallback<[AudioRendererRate](#audiorendererrate8)> | Yes | Callback used to return the audio render rate. |
+| Name | Type | Mandatory | Description |
+| :------- | :------------------- | :-------- | :---------------------------------- |
+| callback | AsyncCallback | Yes | Callback used to return the result. |
**Example**
```js
-audioRenderer.getRenderRate((err, renderrate) => {
- console.info(`getRenderRate: ${renderrate}`);
+tonePlayer.release((err) => {
+ if (err) {
+ console.error(`callback call release failed error: ${err.message}`);
+ return;
+ } else {
+ console.info('callback call release success ');
+ }
});
```
-### getRenderRate8+
+### release9+
-getRenderRate(): Promise\
+release(): Promise<void>
-Obtains the current render rate. This API uses a promise to return the result.
+Releases the resources associated with the **TonePlayer** instance. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+**System capability**: SystemCapability.Multimedia.Audio.Tone
**Return value**
-| Type | Description |
-| ------------------------------------------------- | --------------------------------------------- |
-| Promise<[AudioRendererRate](#audiorendererrate8)> | Promise used to return the audio render rate. |
+| Type | Description |
+| :------------- | :--------------------------------- |
+| Promise | Promise used to return the result. |
**Example**
```js
-audioRenderer.getRenderRate().then((renderRate) => {
- console.info(`getRenderRate: ${renderRate}`);
-}).catch((err) => {
- console.error(`ERROR: ${err}`);
+tonePlayer.release().then(() => {
+ console.info('promise call release');
+}).catch(() => {
+ console.error('promise call release fail');
});
```
-### setInterruptMode9+
-
-setInterruptMode(mode: InterruptMode): Promise<void>
+## ActiveDeviceType(deprecated)
-Sets the audio interruption mode for the application. This API uses a promise to return the result.
+Enumerates the active device types.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+> **NOTE**
+>
+> This API is deprecated since API version 9. You are advised to use [CommunicationDeviceType](#communicationdevicetype9) instead.
-**Parameters**
+**System capability**: SystemCapability.Multimedia.Audio.Device
-| Name | Type | Mandatory | Description |
-| ---- | -------------------------------- | --------- | ------------------------ |
-| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. |
+| Name | Default Value | Description |
+| ------------- | ------------- | ------------------------------------------------------------ |
+| SPEAKER | 2 | Speaker. |
+| BLUETOOTH_SCO | 7 | Bluetooth device using Synchronous Connection Oriented (SCO) links. |
-**Return value**
+## InterruptActionType(deprecated)
-| Type | Description |
-| ------------------- | ------------------------------------------------------------ |
-| Promise<void> | Promise used to return the result. If the operation is successful, **undefined** is returned. Otherwise, **error** is returned. |
+Enumerates the returned event types for audio interruption events.
-**Example**
+> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9.
-```js
-let mode = 0;
-audioRenderer.setInterruptMode(mode).then(data=>{
- console.info('setInterruptMode Success!');
-}).catch((err) => {
- console.error(`setInterruptMode Fail: ${err}`);
-});
+**System capability**: SystemCapability.Multimedia.Audio.Renderer
-```
+| Name | Default Value | Description |
+| -------------- | ------------- | ------------------------- |
+| TYPE_ACTIVATED | 0 | Focus gain event. |
+| TYPE_INTERRUPT | 1 | Audio interruption event. |
-### setInterruptMode9+
+## AudioInterrupt(deprecated)
-setInterruptMode(mode: InterruptMode, callback: AsyncCallback\): void
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9.
-Sets the audio interruption mode for the application. This API uses a callback to return the result.
+Describes input parameters of audio interruption events.
**System capability**: SystemCapability.Multimedia.Audio.Renderer
-**Parameters**
-
-| Name | Type | Mandatory | Description |
-| -------- | -------------------------------- | --------- | ----------------------------------- |
-| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. |
-| callback | AsyncCallback\ | Yes | Callback used to return the result. |
-
-**Example**
-
-```js
-let mode = 1;
-audioRenderer.setInterruptMode(mode, (err, data)=>{
- if(err){
- console.error(`setInterruptMode Fail: ${err}`);
- }
- console.info('setInterruptMode Success!');
-});
-
-```
+| Name | Type | Mandatory | Description |
+| --------------- | --------------------------- | --------- | ------------------------------------------------------------ |
+| streamUsage | [StreamUsage](#streamusage) | Yes | Audio stream usage. |
+| contentType | [ContentType](#contenttype) | Yes | Audio content type. |
+| pauseWhenDucked | boolean | Yes | Whether audio playback can be paused during audio interruption. The value **true** means that audio playback can be paused during audio interruption, and **false** means the opposite. |
-### on('interrupt')9+
+## InterruptAction(deprecated)
-on(type: 'interrupt', callback: Callback\): void
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9.
-Subscribes to audio interruption events. This API uses a callback to get interrupt events.
+Describes the callback invoked for audio interruption or focus gain events.
**System capability**: SystemCapability.Multimedia.Audio.Renderer
-**Parameters**
-
-| Name | Type | Mandatory | Description |
-| -------- | -------------------------------------------- | --------- | ------------------------------------------------------------ |
-| type | string | Yes | Event type. The value **interrupt** means the audio interruption event, which is triggered when audio playback is interrupted. |
-| callback | Callback<[InterruptEvent](#interruptevent9)> | Yes | Callback used to return the audio interruption event. |
+| Name | Type | Mandatory | Description |
+| ---------- | ------------------------------------------- | --------- | ------------------------------------------------------------ |
+| actionType | [InterruptActionType](#interruptactiontype) | Yes | Returned event type. The value **TYPE_ACTIVATED** means the focus gain event, and **TYPE_INTERRUPT** means the audio interruption event. |
+| type | [InterruptType](#interrupttype) | No | Type of the audio interruption event. |
+| hint | [InterruptHint](#interrupthint) | No | Hint provided along with the audio interruption event. |
+| activated | boolean | No | Whether the focus is gained or released. The value **true** means that the focus is gained or released, and **false** means that the focus fails to be gained or released. |
-**Example**
+### setVolume(deprecated)
-```js
-var isPlay;
-var started;
-audioRenderer.on('interrupt', async(interruptEvent) => {
- if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) {
- switch (interruptEvent.hintType) {
- case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
- console.info('Force paused. Stop writing');
- isPlay = false;
- break;
- case audio.InterruptHint.INTERRUPT_HINT_STOP:
- console.info('Force stopped. Stop writing');
- isPlay = false;
- break;
- }
- } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) {
- switch (interruptEvent.hintType) {
- case audio.InterruptHint.INTERRUPT_HINT_RESUME:
- console.info('Resume force paused renderer or ignore');
- await audioRenderer.start().then(async function () {
- console.info('AudioInterruptMusic: renderInstant started :SUCCESS ');
- started = true;
- }).catch((err) => {
- console.error(`AudioInterruptMusic: renderInstant start :ERROR : ${err}`);
- started = false;
- });
- if (started) {
- isPlay = true;
- console.info(`AudioInterruptMusic Renderer started : isPlay : ${isPlay}`);
- } else {
- console.error('AudioInterruptMusic Renderer start failed');
- }
- break;
- case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
- console.info('Choose to pause or ignore');
- if (isPlay == true) {
- isPlay == false;
- console.info('AudioInterruptMusic: Media PAUSE : TRUE');
- } else {
- isPlay = true;
- console.info('AudioInterruptMusic: Media PLAY : TRUE');
- }
- break;
- }
- }
-});
+setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback<void>): void
-```
+Sets the volume for a stream. This API uses an asynchronous callback to return the result.
-### on('markReach')8+
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setVolume](#setvolume9) in **AudioVolumeGroupManager**.
-on(type: "markReach", frame: number, callback: Callback<number>): void
+**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY
-Subscribes to mark reached events. When the number of frames rendered reaches the value of the **frame** parameter, the callback is invoked.
+This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
-| Name | Type | Mandatory | Description |
-| :------- | :--------------- | :-------- | :----------------------------------------------------------- |
-| type | string | Yes | Event type. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter. |
-| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. |
-| callback | Callback | Yes | Callback invoked when the event is triggered. |
+| Name | Type | Mandatory | Description |
+| ---------- | ----------------------------------- | --------- | ------------------------------------------------------------ |
+| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
+| volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**. |
+| callback | AsyncCallback<void> | Yes | Callback used to return the result. |
**Example**
```js
-audioRenderer.on('markReach', 1000, (position) => {
- if (position == 1000) {
- console.info('ON Triggered successfully');
+audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => {
+ if (err) {
+ console.error(`Failed to set the volume. ${err}`);
+ return;
}
+ console.info('Callback invoked to indicate a successful volume setting.');
});
```
+### setVolume(deprecated)
-### off('markReach') 8+
+setVolume(volumeType: AudioVolumeType, volume: number): Promise<void>
-off(type: 'markReach'): void
+Sets the volume for a stream. This API uses a promise to return the result.
-Unsubscribes from mark reached events.
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setVolume](#setvolume9) in **AudioVolumeGroupManager**.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY
+
+This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**.
+
+**System capability**: SystemCapability.Multimedia.Audio.Volume
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| ---------- | ----------------------------------- | --------- | ------------------------------------------------------------ |
+| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
+| volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**. |
-**Parameters**
+**Return value**
-| Name | Type | Mandatory | Description |
-| :--- | :----- | :-------- | :----------------------------------------------- |
-| type | string | Yes | Event type. The value is fixed at **markReach**. |
+| Type | Description |
+| ------------------- | ---------------------------------- |
+| Promise<void> | Promise used to return the result. |
**Example**
```js
-audioRenderer.off('markReach');
+audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => {
+ console.info('Promise returned to indicate a successful volume setting.');
+});
```
-### on('periodReach') 8+
+### getVolume(deprecated)
-on(type: "periodReach", frame: number, callback: Callback<number>): void
+getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void
-Subscribes to period reached events. When the period of frame rendering reaches the value of the **frame** parameter, the callback is invoked.
+Obtains the volume of a stream. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getVolume](#getvolume9) in **AudioVolumeGroupManager**.
+
+**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
-| Name | Type | Mandatory | Description |
-| :------- | :--------------- | :-------- | :----------------------------------------------------------- |
-| type | string | Yes | Event type. The value **periodReach** means the period reached event, which is triggered when the period of frame rendering reaches the value of the **frame** parameter. |
-| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. |
-| callback | Callback | Yes | Callback invoked when the event is triggered. |
+| Name | Type | Mandatory | Description |
+| ---------- | ----------------------------------- | --------- | ----------------------------------- |
+| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
+| callback | AsyncCallback<number> | Yes | Callback used to return the volume. |
**Example**
```js
-audioRenderer.on('periodReach', 1000, (position) => {
- if (position == 1000) {
- console.info('ON Triggered successfully');
+audioManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => {
+ if (err) {
+ console.error(`Failed to obtain the volume. ${err}`);
+ return;
}
+ console.info('Callback invoked to indicate that the volume is obtained.');
});
```
-### off('periodReach') 8+
+### getVolume(deprecated)
-off(type: 'periodReach'): void
+getVolume(volumeType: AudioVolumeType): Promise<number>
-Unsubscribes from period reached events.
+Obtains the volume of a stream. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getVolume](#getvolume9) in **AudioVolumeGroupManager**.
+
+**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
-| Name | Type | Mandatory | Description |
-| :--- | :----- | :-------- | :------------------------------------------------- |
-| type | string | Yes | Event type. The value is fixed at **periodReach**. |
+| Name | Type | Mandatory | Description |
+| ---------- | ----------------------------------- | --------- | ------------------ |
+| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
+
+**Return value**
+
+| Type | Description |
+| --------------------- | ---------------------------------- |
+| Promise<number> | Promise used to return the volume. |
**Example**
```js
-audioRenderer.off('periodReach')
+audioManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => {
+ console.info(`Promise returned to indicate that the volume is obtained ${value} .`);
+});
```
-### on('stateChange')8+
+### getMinVolume(deprecated)
-on(type: 'stateChange', callback: Callback): void
+getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void
-Subscribes to state change events.
+Obtains the minimum volume allowed for a stream. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Renderer
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getMinVolume](#getminvolume9) in **AudioVolumeGroupManager**.
+
+**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
-| Name | Type | Mandatory | Description |
-| :------- | :------------------------- | :-------- | :----------------------------------------------------------- |
-| type | string | Yes | Event type. The value **stateChange** means the state change event. |
-| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. |
+| Name | Type | Mandatory | Description |
+| ---------- | ----------------------------------- | --------- | ------------------------------------------- |
+| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
+| callback | AsyncCallback<number> | Yes | Callback used to return the minimum volume. |
**Example**
```js
-audioRenderer.on('stateChange', (state) => {
- if (state == 1) {
- console.info('audio renderer state is: STATE_PREPARED');
- }
- if (state == 2) {
- console.info('audio renderer state is: STATE_RUNNING');
+audioManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => {
+ if (err) {
+ console.error(`Failed to obtain the minimum volume. ${err}`);
+ return;
}
+ console.info(`Callback invoked to indicate that the minimum volume is obtained. ${value}`);
});
```
-## AudioCapturer8+
+### getMinVolume(deprecated)
-Provides APIs for audio capture. Before calling any API in **AudioCapturer**, you must use [createAudioCapturer](#audiocreateaudiocapturer8) to create an **AudioCapturer** instance.
+getMinVolume(volumeType: AudioVolumeType): Promise<number>
-### Attributes
+Obtains the minimum volume allowed for a stream. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Capturer
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getMinVolume](#getminvolume9) in **AudioVolumeGroupManager**.
-| Name | Type | Readable | Writable | Description |
-| :----------------- | :------------------------- | :------- | :------- | :-------------------- |
-| state8+ | [AudioState](#audiostate8) | Yes | No | Audio capturer state. |
+**System capability**: SystemCapability.Multimedia.Audio.Volume
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| ---------- | ----------------------------------- | --------- | ------------------ |
+| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
+
+**Return value**
+
+| Type | Description |
+| --------------------- | ------------------------------------------ |
+| Promise<number> | Promise used to return the minimum volume. |
**Example**
```js
-var state = audioCapturer.state;
+audioManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => {
+ console.info(`Promised returned to indicate that the minimum volume is obtained. ${value}`);
+});
```
-### getCapturerInfo8+
+### getMaxVolume(deprecated)
-getCapturerInfo(callback: AsyncCallback): void
+getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void
-Obtains the capturer information of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result.
+Obtains the maximum volume allowed for a stream. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Capturer
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getMaxVolume](#getmaxvolume9) in **AudioVolumeGroupManager**.
+
+**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
-| Name | Type | Mandatory | Description |
-| :------- | :-------------------------------- | :-------- | :------------------------------------------------ |
-| callback | AsyncCallback | Yes | Callback used to return the capturer information. |
+| Name | Type | Mandatory | Description |
+| ---------- | ----------------------------------- | --------- | ------------------------------------------- |
+| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
+| callback | AsyncCallback<number> | Yes | Callback used to return the maximum volume. |
**Example**
```js
-audioCapturer.getCapturerInfo((err, capturerInfo) => {
+audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => {
if (err) {
- console.error('Failed to get capture info');
- } else {
- console.info('Capturer getCapturerInfo:');
- console.info(`Capturer source: ${capturerInfo.source}`);
- console.info(`Capturer flags: ${capturerInfo.capturerFlags}`);
+ console.error(`Failed to obtain the maximum volume. ${err}`);
+ return;
}
+ console.info(`Callback invoked to indicate that the maximum volume is obtained. ${value}`);
});
```
+### getMaxVolume(deprecated)
-### getCapturerInfo8+
+getMaxVolume(volumeType: AudioVolumeType): Promise<number>
-getCapturerInfo(): Promise
+Obtains the maximum volume allowed for a stream. This API uses a promise to return the result.
-Obtains the capturer information of this **AudioCapturer** instance. This API uses a promise to return the result.
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getMaxVolume](#getmaxvolume9) in **AudioVolumeGroupManager**.
-**System capability**: SystemCapability.Multimedia.Audio.Capturer
+**System capability**: SystemCapability.Multimedia.Audio.Volume
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| ---------- | ----------------------------------- | --------- | ------------------ |
+| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
**Return value**
-| Type | Description |
-| :------------------------------------------------ | :----------------------------------------------- |
-| Promise<[AudioCapturerInfo](#audiocapturerinfo)\> | Promise used to return the capturer information. |
+| Type | Description |
+| --------------------- | ------------------------------------------ |
+| Promise<number> | Promise used to return the maximum volume. |
**Example**
```js
-audioCapturer.getCapturerInfo().then((audioParamsGet) => {
- if (audioParamsGet != undefined) {
- console.info('AudioFrameworkRecLog: Capturer CapturerInfo:');
- console.info(`AudioFrameworkRecLog: Capturer SourceType: ${audioParamsGet.source}`);
- console.info(`AudioFrameworkRecLog: Capturer capturerFlags: ${audioParamsGet.capturerFlags}`);
- } else {
- console.info(`AudioFrameworkRecLog: audioParamsGet is : ${audioParamsGet}`);
- console.info('AudioFrameworkRecLog: audioParams getCapturerInfo are incorrect');
- }
-}).catch((err) => {
- console.error(`AudioFrameworkRecLog: CapturerInfo :ERROR: ${err}`);
+audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => {
+ console.info('Promised returned to indicate that the maximum volume is obtained.');
});
```
-### getStreamInfo8+
+### mute(deprecated)
-getStreamInfo(callback: AsyncCallback): void
+mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void>): void
-Obtains the stream information of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result.
+Mutes or unmutes a stream. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Capturer
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [mute](#mute9) in **AudioVolumeGroupManager**.
+
+**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY
+
+This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**.
+
+**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
-| Name | Type | Mandatory | Description |
-| :------- | :--------------------------------------------------- | :-------- | :---------------------------------------------- |
-| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information. |
+| Name | Type | Mandatory | Description |
+| ---------- | ----------------------------------- | --------- | ------------------------------------------------------------ |
+| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
+| mute | boolean | Yes | Mute status to set. The value **true** means to mute the stream, and **false** means the opposite. |
+| callback | AsyncCallback<void> | Yes | Callback used to return the result. |
**Example**
```js
-audioCapturer.getStreamInfo((err, streamInfo) => {
+audioManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => {
if (err) {
- console.error('Failed to get stream info');
- } else {
- console.info('Capturer GetStreamInfo:');
- console.info(`Capturer sampling rate: ${streamInfo.samplingRate}`);
- console.info(`Capturer channel: ${streamInfo.channels}`);
- console.info(`Capturer format: ${streamInfo.sampleFormat}`);
- console.info(`Capturer encoding type: ${streamInfo.encodingType}`);
+ console.error(`Failed to mute the stream. ${err}`);
+ return;
}
+ console.info('Callback invoked to indicate that the stream is muted.');
});
```
-### getStreamInfo8+
+### mute(deprecated)
-getStreamInfo(): Promise
+mute(volumeType: AudioVolumeType, mute: boolean): Promise<void>
-Obtains the stream information of this **AudioCapturer** instance. This API uses a promise to return the result.
+Mutes or unmutes a stream. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Capturer
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [mute](#mute9) in **AudioVolumeGroupManager**.
+
+**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY
+
+This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**.
+
+**System capability**: SystemCapability.Multimedia.Audio.Volume
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| ---------- | ----------------------------------- | --------- | ------------------------------------------------------------ |
+| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
+| mute | boolean | Yes | Mute status to set. The value **true** means to mute the stream, and **false** means the opposite. |
**Return value**
-| Type | Description |
-| :--------------------------------------------- | :--------------------------------------------- |
-| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information. |
+| Type | Description |
+| ------------------- | ---------------------------------- |
+| Promise<void> | Promise used to return the result. |
**Example**
+
```js
-audioCapturer.getStreamInfo().then((audioParamsGet) => {
- console.info('getStreamInfo:');
- console.info(`sampleFormat: ${audioParamsGet.sampleFormat}`);
- console.info(`samplingRate: ${audioParamsGet.samplingRate}`);
- console.info(`channels: ${audioParamsGet.channels}`);
- console.info(`encodingType: ${audioParamsGet.encodingType}`);
-}).catch((err) => {
- console.error(`getStreamInfo :ERROR: ${err}`);
+audioManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => {
+ console.info('Promise returned to indicate that the stream is muted.');
});
```
-### start8+
+### isMute(deprecated)
-start(callback: AsyncCallback): void
+isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void
-Starts capturing. This API uses an asynchronous callback to return the result.
+Checks whether a stream is muted. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Capturer
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMute](#ismute9) in **AudioVolumeGroupManager**.
+
+**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
-| Name | Type | Mandatory | Description |
-| :------- | :------------------- | :-------- | :---------------------------------- |
-| callback | AsyncCallback | Yes | Callback used to return the result. |
+| Name | Type | Mandatory | Description |
+| ---------- | ----------------------------------- | --------- | ------------------------------------------------------------ |
+| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
+| callback | AsyncCallback<boolean> | Yes | Callback used to return the mute status of the stream. The value **true** means that the stream is muted, and **false** means the opposite. |
**Example**
```js
-audioCapturer.start((err) => {
+audioManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => {
if (err) {
- console.error('Capturer start failed.');
- } else {
- console.info('Capturer start success.');
+ console.error(`Failed to obtain the mute status. ${err}`);
+ return;
}
+ console.info(`Callback invoked to indicate that the mute status of the stream is obtained. ${value}`);
});
```
+### isMute(deprecated)
-### start8+
+isMute(volumeType: AudioVolumeType): Promise<boolean>
-start(): Promise
+Checks whether a stream is muted. This API uses a promise to return the result.
-Starts capturing. This API uses a promise to return the result.
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMute](#ismute9) in **AudioVolumeGroupManager**.
-**System capability**: SystemCapability.Multimedia.Audio.Capturer
+**System capability**: SystemCapability.Multimedia.Audio.Volume
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| ---------- | ----------------------------------- | --------- | ------------------ |
+| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
**Return value**
-| Type | Description |
-| :------------- | :--------------------------------- |
-| Promise | Promise used to return the result. |
+| Type | Description |
+| ---------------------- | ------------------------------------------------------------ |
+| Promise<boolean> | Promise used to return the mute status of the stream. The value **true** means that the stream is muted, and **false** means the opposite. |
**Example**
```js
-audioCapturer.start().then(() => {
- console.info('AudioFrameworkRecLog: ---------START---------');
- console.info('AudioFrameworkRecLog: Capturer started: SUCCESS');
- console.info(`AudioFrameworkRecLog: AudioCapturer: STATE: ${audioCapturer.state}`);
- console.info('AudioFrameworkRecLog: Capturer started: SUCCESS');
- if ((audioCapturer.state == audio.AudioState.STATE_RUNNING)) {
- console.info('AudioFrameworkRecLog: AudioCapturer is in Running State');
- }
-}).catch((err) => {
- console.info(`AudioFrameworkRecLog: Capturer start :ERROR : ${err}`);
+audioManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => {
+ console.info(`Promise returned to indicate that the mute status of the stream is obtained ${value}.`);
});
```
-### stop8+
+### isActive(deprecated)
-stop(callback: AsyncCallback): void
+isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void
-Stops capturing. This API uses an asynchronous callback to return the result.
+Checks whether a stream is active. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Capturer
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isActive](#isactive9) in **AudioStreamManager**.
+
+**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
-| Name | Type | Mandatory | Description |
-| :------- | :------------------- | :-------- | :---------------------------------- |
-| callback | AsyncCallback | Yes | Callback used to return the result. |
+| Name | Type | Mandatory | Description |
+| ---------- | ----------------------------------- | --------- | ------------------------------------------------------------ |
+| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
+| callback | AsyncCallback<boolean> | Yes | Callback used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite. |
**Example**
```js
-audioCapturer.stop((err) => {
+audioManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => {
if (err) {
- console.error('Capturer stop failed');
- } else {
- console.info('Capturer stopped.');
+ console.error(`Failed to obtain the active status of the stream. ${err}`);
+ return;
}
+ console.info(`Callback invoked to indicate that the active status of the stream is obtained ${value}.`);
});
```
+### isActive(deprecated)
-### stop8+
+isActive(volumeType: AudioVolumeType): Promise<boolean>
-stop(): Promise
+Checks whether a stream is active. This API uses a promise to return the result.
-Stops capturing. This API uses a promise to return the result.
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isActive](#isactive9) in **AudioStreamManager**.
-**System capability**: SystemCapability.Multimedia.Audio.Capturer
+**System capability**: SystemCapability.Multimedia.Audio.Volume
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| ---------- | ----------------------------------- | --------- | ------------------ |
+| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. |
**Return value**
-| Type | Description |
-| :------------- | :--------------------------------- |
-| Promise | Promise used to return the result. |
+| Type | Description |
+| ---------------------- | ------------------------------------------------------------ |
+| Promise<boolean> | Promise used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite. |
**Example**
```js
-audioCapturer.stop().then(() => {
- console.info('AudioFrameworkRecLog: ---------STOP RECORD---------');
- console.info('AudioFrameworkRecLog: Capturer stopped: SUCCESS');
- if ((audioCapturer.state == audio.AudioState.STATE_STOPPED)){
- console.info('AudioFrameworkRecLog: State is Stopped:');
- }
-}).catch((err) => {
- console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`);
+audioManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => {
+ console.info(`Promise returned to indicate that the active status of the stream is obtained ${value}.`);
});
```
-### release8+
+### setRingerMode(deprecated)
-release(callback: AsyncCallback): void
+setRingerMode(mode: AudioRingMode, callback: AsyncCallback<void>): void
-Releases this **AudioCapturer** instance. This API uses an asynchronous callback to return the result.
+Sets the ringer mode. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Capturer
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setRingerMode](#setringermode9) in **AudioVolumeGroupManager**.
+
+**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY
+
+This permission is required only for muting or unmuting the ringer.
+
+**System capability**: SystemCapability.Multimedia.Audio.Communication
**Parameters**
-| Name | Type | Mandatory | Description |
-| :------- | :------------------- | :-------- | :---------------------------------- |
-| callback | AsyncCallback | Yes | Callback used to return the result. |
+| Name | Type | Mandatory | Description |
+| -------- | ------------------------------- | --------- | ----------------------------------- |
+| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode. |
+| callback | AsyncCallback<void> | Yes | Callback used to return the result. |
**Example**
```js
-audioCapturer.release((err) => {
+audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => {
if (err) {
- console.error('capturer release failed');
- } else {
- console.info('capturer released.');
+ console.error(`Failed to set the ringer mode. ${err}`);
+ return;
}
+ console.info('Callback invoked to indicate a successful setting of the ringer mode.');
});
```
+### setRingerMode(deprecated)
-### release8+
+setRingerMode(mode: AudioRingMode): Promise<void>
-release(): Promise
+Sets the ringer mode. This API uses a promise to return the result.
-Releases this **AudioCapturer** instance. This API uses a promise to return the result.
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setRingerMode](#setringermode9) in **AudioVolumeGroupManager**.
-**System capability**: SystemCapability.Multimedia.Audio.Capturer
+**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY
+
+This permission is required only for muting or unmuting the ringer.
+
+**System capability**: SystemCapability.Multimedia.Audio.Communication
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| ---- | ------------------------------- | --------- | ------------ |
+| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode. |
**Return value**
-| Type | Description |
-| :------------- | :--------------------------------- |
-| Promise | Promise used to return the result. |
+| Type | Description |
+| ------------------- | ---------------------------------- |
+| Promise<void> | Promise used to return the result. |
**Example**
```js
-var stateFlag;
-audioCapturer.release().then(() => {
- console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------');
- console.info('AudioFrameworkRecLog: Capturer release : SUCCESS');
- console.info(`AudioFrameworkRecLog: AudioCapturer : STATE : ${audioCapturer.state}`);
- console.info(`AudioFrameworkRecLog: stateFlag : ${stateFlag}`);
-}).catch((err) => {
- console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`);
+audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => {
+ console.info('Promise returned to indicate a successful setting of the ringer mode.');
});
```
+### getRingerMode(deprecated)
-### read8+
+getRingerMode(callback: AsyncCallback<AudioRingMode>): void
-read(size: number, isBlockingRead: boolean, callback: AsyncCallback): void
+Obtains the ringer mode. This API uses an asynchronous callback to return the result.
-Reads the buffer. This API uses an asynchronous callback to return the result.
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getRingerMode](#getringermode9) in **AudioVolumeGroupManager**.
-**System capability**: SystemCapability.Multimedia.Audio.Capturer
+**System capability**: SystemCapability.Multimedia.Audio.Communication
**Parameters**
-| Name | Type | Mandatory | Description |
-| :------------- | :-------------------------- | :-------- | :----------------------------------- |
-| size | number | Yes | Number of bytes to read. |
-| isBlockingRead | boolean | Yes | Whether to block the read operation. |
-| callback | AsyncCallback | Yes | Callback used to return the buffer. |
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------------------------------------- | --------- | ---------------------------------------- |
+| callback | AsyncCallback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the ringer mode. |
**Example**
```js
-var bufferSize;
-audioCapturer.getBufferSize().then((data) => {
- console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`);
- bufferSize = data;
- }).catch((err) => {
- console.error(`AudioFrameworkRecLog: getBufferSize: ERROR: ${err}`);
- });
-audioCapturer.read(bufferSize, true, async(err, buffer) => {
- if (!err) {
- console.info('Success in reading the buffer data');
+audioManager.getRingerMode((err, value) => {
+ if (err) {
+ console.error(`Failed to obtain the ringer mode. ${err}`);
+ return;
}
+ console.info(`Callback invoked to indicate that the ringer mode is obtained ${value}.`);
});
```
+### getRingerMode(deprecated)
-### read8+
-
-read(size: number, isBlockingRead: boolean): Promise
-
-Reads the buffer. This API uses a promise to return the result.
+getRingerMode(): Promise<AudioRingMode>
-**System capability**: SystemCapability.Multimedia.Audio.Capturer
+Obtains the ringer mode. This API uses a promise to return the result.
-**Parameters**
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getRingerMode](#getringermode9) in **AudioVolumeGroupManager**.
-| Name | Type | Mandatory | Description |
-| :------------- | :------ | :-------- | :----------------------------------- |
-| size | number | Yes | Number of bytes to read. |
-| isBlockingRead | boolean | Yes | Whether to block the read operation. |
+**System capability**: SystemCapability.Multimedia.Audio.Communication
**Return value**
-| Type | Description |
-| :-------------------- | :----------------------------------------------------------- |
-| Promise | Promise used to return the result. If the operation is successful, the buffer data read is returned; otherwise, an error code is returned. |
+| Type | Description |
+| ---------------------------------------------- | --------------------------------------- |
+| Promise<[AudioRingMode](#audioringmode)> | Promise used to return the ringer mode. |
**Example**
```js
-var bufferSize;
-audioCapturer.getBufferSize().then((data) => {
- console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`);
- bufferSize = data;
- }).catch((err) => {
- console.info(`AudioFrameworkRecLog: getBufferSize: ERROR ${err}`);
- });
-console.info(`Buffer size: ${bufferSize}`);
-audioCapturer.read(bufferSize, true).then((buffer) => {
- console.info('buffer read successfully');
-}).catch((err) => {
- console.info(`ERROR : ${err}`);
+audioManager.getRingerMode().then((value) => {
+ console.info(`Promise returned to indicate that the ringer mode is obtained ${value}.`);
});
```
+### getDevices(deprecated)
-### getAudioTime8+
+getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void
-getAudioTime(callback: AsyncCallback): void
+Obtains the audio devices with a specific flag. This API uses an asynchronous callback to return the result.
-Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses an asynchronous callback to return the result.
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getDevices](#getdevices9) in **AudioRoutingManager**.
-**System capability**: SystemCapability.Multimedia.Audio.Capturer
+**System capability**: SystemCapability.Multimedia.Audio.Device
**Parameters**
-| Name | Type | Mandatory | Description |
-| :------- | :--------------------- | :-------- | :---------------------------------- |
-| callback | AsyncCallback | Yes | Callback used to return the result. |
+| Name | Type | Mandatory | Description |
+| ---------- | ------------------------------------------------------------ | --------- | ---------------------------------------- |
+| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. |
+| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the device list. |
**Example**
```js
-audioCapturer.getAudioTime((err, timestamp) => {
- console.info(`Current timestamp: ${timestamp}`);
+audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => {
+ if (err) {
+ console.error(`Failed to obtain the device list. ${err}`);
+ return;
+ }
+ console.info('Callback invoked to indicate that the device list is obtained.');
});
```
+### getDevices(deprecated)
-### getAudioTime8+
+getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors>
-getAudioTime(): Promise
+Obtains the audio devices with a specific flag. This API uses a promise to return the result.
-Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses a promise to return the result.
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getDevices](#getdevices9) in **AudioRoutingManager**.
-**System capability**: SystemCapability.Multimedia.Audio.Capturer
+**System capability**: SystemCapability.Multimedia.Audio.Device
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| ---------- | ------------------------- | --------- | ------------------ |
+| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. |
**Return value**
-| Type | Description |
-| :--------------- | :------------------------------------ |
-| Promise | Promise used to return the timestamp. |
+| Type | Description |
+| ------------------------------------------------------------ | --------------------------------------- |
+| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise used to return the device list. |
**Example**
```js
-audioCapturer.getAudioTime().then((audioTime) => {
- console.info(`AudioFrameworkRecLog: AudioCapturer getAudioTime : Success ${audioTime}`);
-}).catch((err) => {
- console.info(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`);
+audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => {
+ console.info('Promise returned to indicate that the device list is obtained.');
});
```
+### setDeviceActive(deprecated)
-### getBufferSize8+
+setDeviceActive(deviceType: ActiveDeviceType, active: boolean, callback: AsyncCallback<void>): void
-getBufferSize(callback: AsyncCallback): void
+Sets a device to the active state. This API uses an asynchronous callback to return the result.
-Obtains a reasonable minimum buffer size in bytes for capturing. This API uses an asynchronous callback to return the result.
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setCommunicationDevice](#setcommunicationdevice9) in **AudioRoutingManager**.
-**System capability**: SystemCapability.Multimedia.Audio.Capturer
+**System capability**: SystemCapability.Multimedia.Audio.Device
**Parameters**
-| Name | Type | Mandatory | Description |
-| :------- | :--------------------- | :-------- | :--------------------------------------- |
-| callback | AsyncCallback | Yes | Callback used to return the buffer size. |
+| Name | Type | Mandatory | Description |
+| ---------- | ------------------------------------- | --------- | ------------------------------------------------------------ |
+| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. |
+| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. |
+| callback | AsyncCallback<void> | Yes | Callback used to return the result. |
**Example**
```js
-audioCapturer.getBufferSize((err, bufferSize) => {
- if (!err) {
- console.info(`BufferSize : ${bufferSize}`);
- audioCapturer.read(bufferSize, true).then((buffer) => {
- console.info(`Buffer read is ${buffer}`);
- }).catch((err) => {
- console.error(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`);
- });
+audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true, (err) => {
+ if (err) {
+ console.error(`Failed to set the active status of the device. ${err}`);
+ return;
}
+ console.info('Callback invoked to indicate that the device is set to the active status.');
});
```
+### setDeviceActive(deprecated)
-### getBufferSize8+
+setDeviceActive(deviceType: ActiveDeviceType, active: boolean): Promise<void>
-getBufferSize(): Promise
+Sets a device to the active state. This API uses a promise to return the result.
-Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a promise to return the result.
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setCommunicationDevice](#setcommunicationdevice9) in **AudioRoutingManager**.
-**System capability**: SystemCapability.Multimedia.Audio.Capturer
+**System capability**: SystemCapability.Multimedia.Audio.Device
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| ---------- | ------------------------------------- | --------- | ------------------------------------------------------------ |
+| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. |
+| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. |
**Return value**
-| Type | Description |
-| :--------------- | :-------------------------------------- |
-| Promise | Promise used to return the buffer size. |
+| Type | Description |
+| ------------------- | ---------------------------------- |
+| Promise<void> | Promise used to return the result. |
**Example**
+
```js
-var bufferSize;
-audioCapturer.getBufferSize().then((data) => {
- console.info(`AudioFrameworkRecLog: getBufferSize :SUCCESS ${data}`);
- bufferSize = data;
-}).catch((err) => {
- console.info(`AudioFrameworkRecLog: getBufferSize :ERROR : ${err}`);
+audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true).then(() => {
+ console.info('Promise returned to indicate that the device is set to the active status.');
});
```
+### isDeviceActive(deprecated)
-### on('markReach')8+
+isDeviceActive(deviceType: ActiveDeviceType, callback: AsyncCallback<boolean>): void
-on(type: "markReach", frame: number, callback: Callback<number>): void
+Checks whether a device is active. This API uses an asynchronous callback to return the result.
-Subscribes to mark reached events. When the number of frames captured reaches the value of the **frame** parameter, the callback is invoked.
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isCommunicationDeviceActive](#iscommunicationdeviceactive9) in **AudioRoutingManager**.
-**System capability**: SystemCapability.Multimedia.Audio.Capturer
+**System capability**: SystemCapability.Multimedia.Audio.Device
**Parameters**
-| Name | Type | Mandatory | Description |
-| :------- | :--------------- | :-------- | :----------------------------------------------------------- |
-| type | string | Yes | Event type. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter. |
-| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. |
-| callback | Callback | Yes | Callback invoked when the event is triggered. |
+| Name | Type | Mandatory | Description |
+| ---------- | ------------------------------------- | --------- | ------------------------------------------------------- |
+| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. |
+| callback | AsyncCallback<boolean> | Yes | Callback used to return the active state of the device. |
**Example**
```js
-audioCapturer.on('markReach', 1000, (position) => {
- if (position == 1000) {
- console.info('ON Triggered successfully');
+audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER, (err, value) => {
+ if (err) {
+ console.error(`Failed to obtain the active status of the device. ${err}`);
+ return;
}
+ console.info('Callback invoked to indicate that the active status of the device is obtained.');
});
```
-### off('markReach')8+
-
-off(type: 'markReach'): void
-
-Unsubscribes from mark reached events.
-
-**System capability**: SystemCapability.Multimedia.Audio.Capturer
-
-**Parameters**
-
-| Name | Type | Mandatory | Description |
-| :--- | :----- | :-------- | :----------------------------------------------------------- |
-| type | string | Yes | Event type. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter. |
-
-**Example**
-
-```js
-audioCapturer.off('markReach');
-
-```
+### isDeviceActive(deprecated)
-### on('periodReach')8+
+isDeviceActive(deviceType: ActiveDeviceType): Promise<boolean>
-on(type: "periodReach", frame: number, callback: Callback<number>): void
+Checks whether a device is active. This API uses a promise to return the result.
-Subscribes to mark reached events. When the period of frame capturing reaches the value of the **frame** parameter, the callback is invoked.
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isCommunicationDeviceActive](#iscommunicationdeviceactive9) in **AudioRoutingManager**.
-**System capability**: SystemCapability.Multimedia.Audio.Capturer
+**System capability**: SystemCapability.Multimedia.Audio.Device
**Parameters**
-| Name | Type | Mandatory | Description |
-| :------- | :--------------- | :-------- | :----------------------------------------------------------- |
-| type | string | Yes | Event type. The value **periodReach** means the period reached event, which is triggered when the period of frame rendering reaches the value of the **frame** parameter. |
-| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. |
-| callback | Callback | Yes | Callback invoked when the event is triggered. |
+| Name | Type | Mandatory | Description |
+| ---------- | ------------------------------------- | --------- | ------------------ |
+| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. |
+
+**Return value**
+
+| Type | Description |
+| ---------------------- | ------------------------------------------------------ |
+| Promise<boolean> | Promise used to return the active state of the device. |
**Example**
```js
-audioCapturer.on('periodReach', 1000, (position) => {
- if (position == 1000) {
- console.info('ON Triggered successfully');
- }
+audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER).then((value) => {
+ console.info(`Promise returned to indicate that the active status of the device is obtained ${value}.`);
});
```
-### off('periodReach')8+
+### setMicrophoneMute(deprecated)
-off(type: 'periodReach'): void
+setMicrophoneMute(mute: boolean, callback: AsyncCallback<void>): void
-Unsubscribes from period reached events.
+Mutes or unmutes the microphone. This API uses an asynchronous callback to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Capturer
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setMicrophoneMute](#setmicrophonemute9) in **AudioVolumeGroupManager**.
+
+**Required permissions**: ohos.permission.MICROPHONE
+
+**System capability**: SystemCapability.Multimedia.Audio.Device
**Parameters**
-| Name | Type | Mandatory | Description |
-| :--- | :----- | :-------- | :----------------------------------------------------------- |
-| type | string | Yes | Event type. The value **periodReach** means the period reached event, which is triggered when the period of frame capturing reaches the value of the **frame** parameter. |
+| Name | Type | Mandatory | Description |
+| -------- | ------------------------- | --------- | ------------------------------------------------------------ |
+| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite. |
+| callback | AsyncCallback<void> | Yes | Callback used to return the result. |
**Example**
```js
-audioCapturer.off('periodReach')
+audioManager.setMicrophoneMute(true, (err) => {
+ if (err) {
+ console.error(`Failed to mute the microphone. ${err}`);
+ return;
+ }
+ console.info('Callback invoked to indicate that the microphone is muted.');
+});
```
-### on('stateChange')8+
+### setMicrophoneMute(deprecated)
-on(type: 'stateChange', callback: Callback): void
+setMicrophoneMute(mute: boolean): Promise<void>
-Subscribes to state change events.
+Mutes or unmutes the microphone. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Capturer
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setMicrophoneMute](#setmicrophonemute9) in **AudioVolumeGroupManager**.
+
+**Required permissions**: ohos.permission.MICROPHONE
+
+**System capability**: SystemCapability.Multimedia.Audio.Device
**Parameters**
-| Name | Type | Mandatory | Description |
-| :------- | :------------------------- | :-------- | :----------------------------------------------------------- |
-| type | string | Yes | Event type. The value **stateChange** means the state change event. |
-| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. |
+| Name | Type | Mandatory | Description |
+| ---- | ------- | --------- | ------------------------------------------------------------ |
+| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite. |
+
+**Return value**
+
+| Type | Description |
+| ------------------- | ---------------------------------- |
+| Promise<void> | Promise used to return the result. |
**Example**
```js
-audioCapturer.on('stateChange', (state) => {
- if (state == 1) {
- console.info('audio capturer state is: STATE_PREPARED');
- }
- if (state == 2) {
- console.info('audio capturer state is: STATE_RUNNING');
- }
+audioManager.setMicrophoneMute(true).then(() => {
+ console.info('Promise returned to indicate that the microphone is muted.');
});
```
-## ToneType 9+
-
-Enumerates the tone types of the player.
-
-**System capability**: SystemCapability.Multimedia.Audio.Tone
-
-| Name | Default Value | Description |
-| :----------------------------------------------- | :------------ | :------------------------------------------- |
-| TONE_TYPE_DIAL_0 | 0 | DTMF tone of key 0. |
-| TONE_TYPE_DIAL_1 | 1 | DTMF tone of key 1. |
-| TONE_TYPE_DIAL_2 | 2 | DTMF tone of key 2. |
-| TONE_TYPE_DIAL_3 | 3 | DTMF tone of key 3. |
-| TONE_TYPE_DIAL_4 | 4 | DTMF tone of key 4. |
-| TONE_TYPE_DIAL_5 | 5 | DTMF tone of key 5. |
-| TONE_TYPE_DIAL_6 | 6 | DTMF tone of key 6. |
-| TONE_TYPE_DIAL_7 | 7 | DTMF tone of key 7. |
-| TONE_TYPE_DIAL_8 | 8 | DTMF tone of key 8. |
-| TONE_TYPE_DIAL_9 | 9 | DTMF tone of key 9. |
-| TONE_TYPE_DIAL_S | 10 | DTMF tone of the star key (*). |
-| TONE_TYPE_DIAL_P | 11 | DTMF tone of the pound key (#). |
-| TONE_TYPE_DIAL_A | 12 | DTMF tone of key A. |
-| TONE_TYPE_DIAL_B | 13 | DTMF tone of key B. |
-| TONE_TYPE_DIAL_C | 14 | DTMF tone of key C. |
-| TONE_TYPE_DIAL_D | 15 | DTMF tone of key D. |
-| TONE_TYPE_COMMON_SUPERVISORY_DIAL | 100 | Supervisory tone - dial tone. |
-| TONE_TYPE_COMMON_SUPERVISORY_BUSY | 101 | Supervisory tone - busy. |
-| TONE_TYPE_COMMON_SUPERVISORY_CONGESTION | 102 | Supervisory tone - congestion. |
-| TONE_TYPE_COMMON_SUPERVISORY_RADIO_ACK | 103 | Supervisory tone - radio path acknowledgment |
-| TONE_TYPE_COMMON_SUPERVISORY_RADIO_NOT_AVAILABLE | 104 | Supervisory tone - radio path not available |
-| TONE_TYPE_COMMON_SUPERVISORY_CALL_WAITING | 106 | Supervisory tone - call waiting tone |
-| TONE_TYPE_COMMON_SUPERVISORY_RINGTONE | 107 | Supervisory tone - ringing tone |
-| TONE_TYPE_COMMON_PROPRIETARY_BEEP | 200 | Proprietary tone - beep tone. |
-| TONE_TYPE_COMMON_PROPRIETARY_ACK | 201 | Proprietary tone - ACK. |
-| TONE_TYPE_COMMON_PROPRIETARY_PROMPT | 203 | Proprietary tone - PROMPT. |
-| TONE_TYPE_COMMON_PROPRIETARY_DOUBLE_BEEP | 204 | Proprietary tone - double beep tone. |
-
-## TonePlayer9+
+### isMicrophoneMute(deprecated)
-Provides APIs for playing and managing DTMF tones, such as dial tones, ringback tones, supervisory tones, and proprietary tones.
+isMicrophoneMute(callback: AsyncCallback<boolean>): void
-### load9+
+Checks whether the microphone is muted. This API uses an asynchronous callback to return the result.
-load(type: ToneType, callback: AsyncCallback<void>): void
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMicrophoneMute](#ismicrophonemute9) in **AudioVolumeGroupManager**.
-Loads the DTMF tone configuration. This API uses an asynchronous callback to return the result.
+**Required permissions**: ohos.permission.MICROPHONE
-**System capability**: SystemCapability.Multimedia.Audio.Tone
+**System capability**: SystemCapability.Multimedia.Audio.Device
**Parameters**
-| Name | Type | Mandatory | Description |
-| :------- | :------------------- | :-------- | :---------------------------------- |
-| type | ToneType(#tonetype9) | Yes | Tone type. |
-| callback | AsyncCallback | Yes | Callback used to return the result. |
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------------- | --------- | ------------------------------------------------------------ |
+| callback | AsyncCallback<boolean> | Yes | Callback used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite. |
**Example**
```js
-tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_5, (err) => {
+audioManager.isMicrophoneMute((err, value) => {
if (err) {
- console.error(`callback call load failed error: ${err.message}`);
+ console.error(`Failed to obtain the mute status of the microphone. ${err}`);
return;
- } else {
- console.info('callback call load success');
}
+ console.info(`Callback invoked to indicate that the mute status of the microphone is obtained ${value}.`);
});
```
-### load9+
+### isMicrophoneMute(deprecated)
-load(type: ToneType): Promise<void>
+isMicrophoneMute(): Promise<boolean>
-Loads the DTMF tone configuration. This API uses a promise to return the result.
+Checks whether the microphone is muted. This API uses a promise to return the result.
-**System capability**: SystemCapability.Multimedia.Audio.Tone
+> **NOTE**
+>
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMicrophoneMute](#ismicrophonemute9) in **AudioVolumeGroupManager**.
-**Parameters**
+**Required permissions**: ohos.permission.MICROPHONE
-| Name | Type | Mandatory | Description |
-| :--- | :------------------- | :-------- | ----------- |
-| type | ToneType(#tonetype9) | Yes | Tone type. |
+**System capability**: SystemCapability.Multimedia.Audio.Device
**Return value**
-| Type | Description |
-| :------------- | :--------------------------------- |
-| Promise | Promise used to return the result. |
+| Type | Description |
+| ---------------------- | ------------------------------------------------------------ |
+| Promise<boolean> | Promise used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite. |
**Example**
```js
-tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_1).then(() => {
- console.info('promise call load ');
-}).catch(() => {
- console.error('promise call load fail');
+audioManager.isMicrophoneMute().then((value) => {
+ console.info(`Promise returned to indicate that the mute status of the microphone is obtained ${value}.`);
});
```
-### start9+
+### on('volumeChange')(deprecated)
-start(callback: AsyncCallback<void>): void
+on(type: 'volumeChange', callback: Callback\): void
-Starts DTMF tone playing. This API uses an asynchronous callback to return the result.
+> **NOTE**
+>
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [on](#on9) in **AudioVolumeManager**.
-**System capability**: SystemCapability.Multimedia.Audio.Tone
+Subscribes to system volume change events.
+
+**System API**: This is a system API.
+
+Currently, when multiple **AudioManager** instances are used in a single process, only the subscription of the last instance takes effect, and the subscription of other instances is overwritten (even if the last instance does not initiate a subscription). Therefore, you are advised to use a single **AudioManager** instance.
+
+**System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters**
-| Name | Type | Mandatory | Description |
-| :------- | :------------------- | :-------- | :---------------------------------- |
-| callback | AsyncCallback