未验证 提交 56f506b8 编写于 作者: O openharmony_ci 提交者: Gitee

!3957 翻译完成:3345 add sample+codelab

Merge pull request !3957 from wusongqing/TR3345
...@@ -13,9 +13,9 @@ ...@@ -13,9 +13,9 @@
- Data provided by the Hall effect sensor implements the smart cover mode of your device. - Data provided by the Hall effect sensor implements the smart cover mode of your device.
- Data provided by the heart rate sensor helps your application track the health of a user. - Data provided by the heart rate sensor helps your application track the heart health of a user.
- Data provided by the pedometer sensor helps your application obtain the number steps a user has walked. - Data provided by the pedometer sensor helps your application obtain the number of steps a user has walked.
- Data provided by the wear detection sensor helps your application detect whether a user is wearing a wearable device. - Data provided by the wear detection sensor helps your application detect whether a user is wearing a wearable device.
...@@ -31,7 +31,7 @@ ...@@ -31,7 +31,7 @@
## How to Develop ## How to Develop
1. To obtain data from a type of sensor, configure the request permissions in the **config.json** file. 1. To obtain data from a type of sensor, configure the requested permissions in the **config.json** file.
``` ```
"reqPermissions":[ "reqPermissions":[
...@@ -75,7 +75,7 @@ ...@@ -75,7 +75,7 @@
``` ```
import sensor from "@ohos.sensor" import sensor from "@ohos.sensor"
sensor.on(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data){ sensor.on(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data){
console.info("Subscription succeeded. data = "+ data);// The call is successful, and the obtained sensor data is printed. console.info("Subscription succeeded. data = "+ data); // The call is successful, and the obtained sensor data is printed.
} }
); );
``` ```
...@@ -89,7 +89,7 @@ ...@@ -89,7 +89,7 @@
``` ```
import sensor from "@ohos.sensor" import sensor from "@ohos.sensor"
sensor.off(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function() { sensor.off(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function() {
console.info("Succeeded in unsubscribing from acceleration sensor data.");// The unsubscription is successful, and the result is printed. console.info("Succeeded in unsubscribing from acceleration sensor data."); // The unsubscription is successful, and the result is printed.
} }
); );
``` ```
...@@ -103,7 +103,7 @@ ...@@ -103,7 +103,7 @@
``` ```
import sensor from "@ohos.sensor" import sensor from "@ohos.sensor"
sensor.once(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data) { sensor.once(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data) {
console.info("Data obtained successfully. data=" + data);// The call is successful, and the obtained sensor data is printed. console.info("Data obtained successfully. data=" + data); // The call is successful, and the obtained sensor data is printed.
} }
); );
``` ```
...@@ -117,9 +117,14 @@ ...@@ -117,9 +117,14 @@
``` ```
try { try {
sensor.once(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data) { sensor.once(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data) {
console.info("Data obtained successfully. data=" + data);// The call is successful, and the obtained sensor data is printed. console.info("Data obtained successfully. data=" + data); // The call is successful, and the obtained sensor data is printed.
}); });
} catch (error) { } catch (error) {
console.error(error); console.error(error);
} }
``` ```
## Samples
The following sample is provided to help you better understand how to develop sensors:
- [`Sensor`: sensor (eTS, API 8)](https://gitee.com/openharmony/app_samples/tree/master/device/Sensor)
# Sensor Overview # Sensor Overview
Sensors in OpenHarmony are an abstraction of underlying hardware-based sensors. Your application can access the underlying sensors via the sensors. Using the APIs provided by sensors, you can query sensors on your device, subscribe to sensor data, customize algorithms based on sensor data, and develop various sensor-based applications, such as compass, fitness and health, and games applications. Sensors in OpenHarmony are an abstraction of underlying sensor hardware. Your application can access the underlying sensor hardware via the sensors. Using the APIs provided by sensors, you can query sensors on your device, subscribe to sensor data, customize algorithms based on sensor data, and develop various sensor-based applications, such as compass, motion-controlled games, and fitness and health applications.
A sensor is a device to detect events or changes in an environment and send messages about the events or changes to another device (for example, a CPU). Generally, a sensor is composed of sensitive components and conversion components. Sensors are the cornerstone of the IoT. A unified sensor management framework is required to achieve data sensing at a low latency and low power consumption, thereby keeping up with requirements of "1+8+N" products or business in the Seamless AI Life Strategy. The sensor list is as follows: A sensor is a device to detect events or changes in an environment and send messages about the events or changes to another device (for example, a CPU). Generally, a sensor is composed of sensitive components and conversion components. Sensors are the cornerstone of the IoT. A unified sensor management framework is required to achieve data sensing at a low latency and low power consumption, thereby keeping up with requirements of "1+8+N" products or business in the Seamless AI Life Strategy. The sensor list is as follows:
| Sensor Type | Sensor Name | Description | Usage | | Type | Name | Description | Usage |
| --------------------------------------- | ---------------------------------- | ---------------------------------------- | ---------------------------------------- | | --------------------------------------- | ------------------ | ------------------------------------------------------------ | ---------------------------------------- |
| SENSOR_TYPE_ACCELEROMETER | Acceleration sensor | Measures the acceleration (including the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>. | Detecting the motion status | | SENSOR_TYPE_ACCELEROMETER | Acceleration sensor | Measures the acceleration (including the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Detecting the motion status |
| SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED | Uncalibrated acceleration sensor | Measures the uncalibrated acceleration (including the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>. | Measuring the acceleration bias estimation | | SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED | Uncalibrated acceleration sensor| Measures the uncalibrated acceleration (including the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Measuring the acceleration bias estimation |
| SENSOR_TYPE_LINEAR_ACCELERATION | Linear acceleration sensor | Measures the linear acceleration (excluding the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>. | Detecting the linear acceleration in each axis | | SENSOR_TYPE_LINEAR_ACCELERATION | Linear acceleration sensor | Measures the linear acceleration (excluding the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Detecting the linear acceleration in each axis |
| SENSOR_TYPE_GRAVITY | Gravity sensor | Measures the gravity acceleration applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>. | Measuring the gravity | | SENSOR_TYPE_GRAVITY | Gravity sensor | Measures the gravity acceleration applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Measuring the gravity |
| SENSOR_TYPE_GYROSCOPE | Gyroscope sensor | Measures the rotation angular velocity of a device on three physical axes (X, Y, and Z), in the unit of rad/s. | Measuring the rotation angular velocity | | SENSOR_TYPE_GYROSCOPE | Gyroscope sensor | Measures the rotation angular velocity of a device on three physical axes (X, Y, and Z), in the unit of rad/s.| Measuring the rotation angular velocity |
| SENSOR_TYPE_GYROSCOPE_UNCALIBRATED | Uncalibrated gyroscope sensor | Measures the uncalibrated rotation angular velocity of a device on three physical axes (X, Y, and Z), in the unit of rad/s. | Measuring the bias estimation of the rotation angular velocity | | SENSOR_TYPE_GYROSCOPE_UNCALIBRATED | Uncalibrated gyroscope sensor| Measures the uncalibrated rotation angular velocity of a device on three physical axes (X, Y, and Z), in the unit of rad/s.| Measuring the bias estimation of the rotation angular velocity |
| SENSOR_TYPE_SIGNIFICANT_MOTION | Significant motion sensor | Checks whether a device has a significant motion on three physical axes (X, Y, and Z). The value **0** means that the device does not have a significant motion, and **1** means the opposite. | Detecting significant motions of a device | | SENSOR_TYPE_SIGNIFICANT_MOTION | Significant motion sensor | Checks whether a device has a significant motion on three physical axes (X, Y, and Z). The value **0** means that the device does not have a significant motion, and **1** means the opposite.| Detecting significant motions of a device |
| SENSOR_TYPE_PEDOMETER_DETECTION | Pedometer detection sensor | Detects whether a user takes a step. The value can be **0** (the user does not take a step) or **1** (the user takes a step). | Detecting whether a user takes a step | | SENSOR_TYPE_PEDOMETER_DETECTION | Pedometer detection sensor | Detects whether a user takes a step. The value can be **0** (the user does not take a step) or **1** (the user takes a step).| Detecting whether a user takes a step |
| SENSOR_TYPE_PEDOMETER | Pedometer sensor | Records the number of steps a user has walked. | Providing the number of steps a user has walked | | SENSOR_TYPE_PEDOMETER | Pedometer sensor | Records the number of steps a user has walked. | Providing the number of steps a user has walked |
| SENSOR_TYPE_AMBIENT_TEMPERATURE | Ambient temperature sensor | Measures the ambient temperature, in the unit of degree Celsius (°C). | Measuring the ambient temperature | | SENSOR_TYPE_AMBIENT_TEMPERATURE | Ambient temperature sensor | Measures the ambient temperature, in the unit of degree Celsius (°C). | Measuring the ambient temperature |
| SENSOR_TYPE_MAGNETIC_FIELD | Magnetic field sensor | Measures the magnetic field on three physical axes (X, Y, and Z), in the unit of μT. | Creating a compass | | SENSOR_TYPE_MAGNETIC_FIELD | Magnetic field sensor | Measures the magnetic field on three physical axes (X, Y, and Z), in the unit of μT.| Creating a compass |
| SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED | Uncalibrated magnetic field sensor | Measures the uncalibrated magnetic field on three physical axes (X, Y, and Z), in the unit of μT. | Measuring the magnetic field bias estimation | | SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED | Uncalibrated magnetic field sensor | Measures the uncalibrated magnetic field on three physical axes (X, Y, and Z), in the unit of μT.| Measuring the magnetic field bias estimation |
| SENSOR_TYPE_HUMIDITY | Humidity sensor | Measures the ambient relative humidity, in a percentage (%). | Monitoring the dew point, absolute humidity, and relative humidity | | SENSOR_TYPE_HUMIDITY | Humidity sensor | Measures the ambient relative humidity, in a percentage (%). | Monitoring the dew point, absolute humidity, and relative humidity |
| SENSOR_TYPE_BAROMETER | Barometer sensor | Measures the barometric pressure, in the unit of hPa or mbar. | Measuring the barometric pressure | | SENSOR_TYPE_BAROMETER | Barometer sensor | Measures the barometric pressure, in the unit of hPa or mbar. | Measuring the barometric pressure |
| SENSOR_TYPE_ORIENTATION | Orientation sensor | Measures the rotation angles of a device on three physical axes (X, Y, and Z), in the unit of rad. | Providing the three orientation angles of the screen | | SENSOR_TYPE_ORIENTATION | Orientation sensor | Measures the rotation angles of a device on three physical axes (X, Y, and Z), in the unit of rad.| Providing the three orientation angles of the screen |
| SENSOR_TYPE_ROTATION_VECTOR | Rotation vector sensor | Measures the rotation vector of a device. It is a composite sensor that generates data from the acceleration sensor, magnetic field sensor, and gyroscope sensor. | Detecting the orientation of a device in the East, North, Up (ENU) Cartesian coordinate system | | SENSOR_TYPE_ROTATION_VECTOR | Rotation vector sensor | Measures the rotation vector of a device. It is a composite sensor that generates data from the acceleration sensor, magnetic field sensor, and gyroscope sensor.| Detecting the orientation of a device in the East, North, Up (ENU) Cartesian coordinate system |
| SENSOR_TYPE_PROXIMITY | Proximity sensor | Measures the distance between a visible object and the device screen. | Measuring the distance between a person and the device during a call | | SENSOR_TYPE_PROXIMITY | Proximity sensor | Measures the distance between a visible object and the device screen. | Measuring the distance between a person and the device during a call |
| SENSOR_TYPE_AMBIENT_LIGHT | Ambient light sensor | Measures the ambient light intensity of a device, in the unit of lux. | Automatically adjusting the screen brightness and checking whether the screen is covered on the top | | SENSOR_TYPE_AMBIENT_LIGHT | Ambient light sensor | Measures the ambient light intensity of a device, in the unit of lux. | Automatically adjusting the screen brightness and checking whether the screen is covered on the top|
| SENSOR_TYPE_HEART_RATE | Heart rate sensor | Measures the heart rate of a user. | Providing users' heart rate data | | SENSOR_TYPE_HEART_RATE | Heart rate sensor | Measures the heart rate of a user. | Providing users' heart rate data |
| SENSOR_TYPE_WEAR_DETECTION | Wear detection sensor | Checks whether a user is wearing a wearable device. | Detecting wearables | | SENSOR_TYPE_WEAR_DETECTION | Wear detection sensor | Checks whether a user is wearing a wearable device. | Detecting wearables |
| SENSOR_TYPE_HALL | Hall effect sensor | Detects a magnetic field around a device. | Smart cover mode of the device | | SENSOR_TYPE_HALL | Hall effect sensor | Detects a magnetic field around a device. | Smart cover mode of the device |
...@@ -54,12 +54,12 @@ The following modules work cooperatively to implement OpenHarmony sensors: Senso ...@@ -54,12 +54,12 @@ The following modules work cooperatively to implement OpenHarmony sensors: Senso
Table 7 Sensor data permissions Table 7 Sensor data permissions
| Sensor | Permission | Sensitivity | Permission Description | | Sensor | Permission | Sensitivity | Permission Description |
| ---------------------------------------- | -------------------------------- | ------------ | ---------------------------------------- | | ------------------------- | -------------------------------- | ------------ | ----------------------- |
| Acceleration sensor, uncalibrated acceleration sensor, and linear acceleration sensor | ohos.permission.ACCELEROMETER | system_grant | Allows your application to subscribe to data of these acceleration-related sensors in the motion category. | | Acceleration sensor, uncalibrated acceleration sensor, and linear acceleration sensor| ohos.permission.ACCELEROMETER | system_grant | Allows an application to subscribe to data of these acceleration-related sensors in the motion category.|
| Gyroscope sensor and uncalibrated gyroscope sensor | ohos.permission.GYROSCOPE | system_grant | Allows an application to subscribe to data of the gyroscope-related sensors in the motion category. | | Gyroscope sensor and uncalibrated gyroscope sensor | ohos.permission.GYROSCOPE | system_grant | Allows an application to subscribe to data of the gyroscope-related sensors in the motion category.|
| Pedometer sensor | ohos.permission.ACTIVITY_MOTION | user_grant | Allows an application to subscribe to the motion status. | | Pedometer sensor | ohos.permission.ACTIVITY_MOTION | user_grant | Allows an application to subscribe to the motion status. |
| Heart rate sensor | ohos.permission.READ_HEALTH_DATA | user_grant | Allows an application to read health data. | | Heart rate sensor | ohos.permission.READ_HEALTH_DATA | user_grant | Allows an application to read health data. |
......
...@@ -3,12 +3,12 @@ ...@@ -3,12 +3,12 @@
## When to Use ## When to Use
You can set different vibration effects as needed, for example, customizing vibration effects with different intensities and durations for buttons on the device, and customizing one-shot or periodic vibration effects with different intensities and durations for alarm clocks and incoming calls. You can set different vibration effects as needed, for example, customizing the vibration intensity, frequency, and duration for button touches, alarm clocks, and incoming calls.
## Available APIs ## Available APIs
| Module| API| Description| | Module| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| ohos.vibrator | vibrate(duration:&nbsp;number):&nbsp;Promise&lt;void&gt; | Triggers vibration with the specified duration. This API uses a promise to return the result.| | ohos.vibrator | vibrate(duration:&nbsp;number):&nbsp;Promise&lt;void&gt; | Triggers vibration with the specified duration. This API uses a promise to return the result.|
| ohos.vibrator | vibrate(duration:&nbsp;number,&nbsp;callback?:&nbsp;AsyncCallback&lt;void&gt;):&nbsp;void | Triggers vibration with the specified duration. This API uses a callback to return the result.| | ohos.vibrator | vibrate(duration:&nbsp;number,&nbsp;callback?:&nbsp;AsyncCallback&lt;void&gt;):&nbsp;void | Triggers vibration with the specified duration. This API uses a callback to return the result.|
...@@ -62,10 +62,10 @@ You can set different vibration effects as needed, for example, customizing vibr ...@@ -62,10 +62,10 @@ You can set different vibration effects as needed, for example, customizing vibr
``` ```
import vibrator from "@ohos.vibrator" import vibrator from "@ohos.vibrator"
vibrator.vibrate(1000).then((error)=>{ vibrator.vibrate(1000).then((error)=>{
if (error) {// The call fails, and error.code and error.message are printed. if (error){ // The call fails, and error.code and error.message are printed.
Console.log("Promise return failed.error.code"+error.code+"error.message"+error.message); console.log("Promise return failed.error.code"+error.code+"error.message"+error.message);
}else{// The call is successful, and the device starts to vibrate. }else{ // The call is successful, and the device starts to vibrate.
Console.log("Promise returned to indicate a successful vibration.") console.log("Promise returned to indicate a successful vibration.")
}; };
}) })
``` ```
...@@ -75,10 +75,16 @@ You can set different vibration effects as needed, for example, customizing vibr ...@@ -75,10 +75,16 @@ You can set different vibration effects as needed, for example, customizing vibr
``` ```
import vibrator from "@ohos.vibrator" import vibrator from "@ohos.vibrator"
vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then((error)=>{ vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then((error)=>{
if (error) {// The call fails, and error.code and error.message are printed. if(error){ // The call fails, and error.code and error.message are printed.
Console.log("Promise return failed.error.code"+error.code+"error.message"+error.message); console.log("Promise return failed.error.code"+error.code+"error.message"+error.message);
}else{// The call is successful, and the device stops vibration. }else{ // The call is successful, and the device stops vibrating.
Console.log("Promise returned to indicate a successful stop."); Console.log("Promise returned to indicate a successful stop.");
}; };
}) })
``` ```
## Samples
The following sample is provided to help you better understand how to develop vibrators:
- [`Vibrator`: vibrator (eTS, API 8)](https://gitee.com/openharmony/app_samples/tree/master/device/Vibrator)
# Vibrator Overview # Vibrator Overview
The vibrator service opens up the latest capabilities of the vibrator hardware to the maximum extent. By expanding the native vibrator service to implement integrated vibration and interaction design, the service delivers an exquisite integrated vibration experience and differentiated experience, and improves user interaction efficiency and usability. The vibrator service is built on the native vibrator service, bolstered by the latest capabilities of the vibrator hardware. By innovatively integrating vibration and interaction, the service takes user interaction efficiency and usability to the next level.
## Working Principles ## Working Principles
...@@ -12,7 +12,7 @@ The vibrator is a Misc device that consists of four modules: Vibrator API, Vibra ...@@ -12,7 +12,7 @@ The vibrator is a Misc device that consists of four modules: Vibrator API, Vibra
![en-us_image_0000001180249428.png](figures/en-us_image_0000001180249428.png) ![en-us_image_0000001180249428.png](figures/en-us_image_0000001180249428.png)
- Vibrator API: provides basic vibrator APIs, including the APIs for querying the vibrator list, querying the vibrator by effect, and triggering and stopping vibration. - Vibrator API: provides basic vibrator APIs, including the APIs for obtaining the vibrator list, querying the vibrator by effect, and triggering and stopping vibration.
- Vibrator Framework: manages the framework layer of the vibrator and communicates with the Misc Device Service. - Vibrator Framework: manages the framework layer of the vibrator and communicates with the Misc Device Service.
......
...@@ -16,38 +16,49 @@ You can use audio playback APIs to convert audio data into audible analog signal ...@@ -16,38 +16,49 @@ You can use audio playback APIs to convert audio data into audible analog signal
## How to Develop ## How to Develop
For details about the APIs used for audio playback, see [AudioPlayer in the Media API](../reference/apis/js-apis-media.md). For details about the APIs, see [AudioPlayer in the Media API](../reference/apis/js-apis-media.md).
### Full-Process Scenario ### 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. 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.
For details about the **src** media source input types supported by **AudioPlayer**, see the [src attribute](../reference/apis/js-apis-media.md#audioplayer_attributes). For details about the **src** types supported by **AudioPlayer**, see the [src attribute](../reference/apis/js-apis-media.md#audioplayer_attributes).
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fileIO from '@ohos.fileio'
function SetCallBack(audioPlayer) { // Print the stream track information.
function printfDescription(obj) {
for (let item in obj) {
let property = obj[item];
console.info('audio key is ' + item);
console.info('audio value is ' + property);
}
}
// Set the player callbacks.
function setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success'); console.info('audio set source success');
// The playback page is ready. You can click the Play button to start the playback. audioPlayer.play(); // The play() API can be invoked only after the 'dataLoad' event callback is complete. The 'play' event callback is then triggered.
}); });
audioPlayer.on('play', () => { // Set the 'play' event callback. audioPlayer.on('play', () => { // Set the 'play' event callback.
console.info('audio play success'); console.info('audio play success');
// The Play button is changed to the pausable state. audioPlayer.pause(); // Trigger the 'pause' event callback and pause the playback.
}); });
audioPlayer.on('pause', () => { // Set the 'pause' event callback. audioPlayer.on('pause', () => { // Set the 'pause' event callback.
console.info('audio pause success'); console.info('audio pause success');
// The Play button is changed to the playable state. audioPlayer.seek(5000); // Trigger the 'timeUpdate' event callback, and seek to 5000 ms for playback.
}); });
audioPlayer.on('stop', () => { // Set the 'stop' event callback. audioPlayer.on('stop', () => { // Set the 'stop' event callback.
console.info('audio stop success'); console.info('audio stop success');
// The playback stops, the playback progress bar returns to 0, and the Play button is changed to the playable state. audioPlayer.reset(); // Trigger the 'reset' event callback, and reconfigure the src attribute to switch to the next song.
}); });
audioPlayer.on('reset', () => { // Set the 'reset' event callback. audioPlayer.on('reset', () => { // Set the 'reset' event callback.
console.info('audio reset success'); console.info('audio reset success');
// You can reconfigure the src attribute to play another audio file. audioPlayer.release(); // Release the AudioPlayer resources.
audioPlayer = undefined;
}); });
audioPlayer.on('timeUpdate', (seekDoneTime) => {// Set the 'timeUpdate' event callback. audioPlayer.on('timeUpdate', (seekDoneTime) => {// Set the 'timeUpdate' event callback.
if (typeof(seekDoneTime) == 'undefined') { if (typeof(seekDoneTime) == 'undefined') {
...@@ -55,11 +66,20 @@ function SetCallBack(audioPlayer) { ...@@ -55,11 +66,20 @@ function SetCallBack(audioPlayer) {
return; return;
} }
console.info('audio seek success, and seek time is ' + seekDoneTime); console.info('audio seek success, and seek time is ' + seekDoneTime);
// The playback progress bar is updated to the seek position. audioPlayer.setVolume(0.5); // Trigger the 'volumeChange' event callback.
}); });
audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback.
console.info('audio volumeChange success'); console.info('audio volumeChange success');
// Display the updated volume. audioPlayer.getTrackDescription((error, arrlist) => { // Obtain the audio track information in callback mode.
if (typeof (arrlist) != 'undefined') {
for (let i = 0; i < arrlist.length; i++) {
printfDescription(arrlist[i]);
}
} else {
console.log(`audio getTrackDescription fail, error:${error.message}`);
}
audioPlayer.stop(); // Trigger the 'stop' event callback to stop the playback.
});
}); });
audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
console.info('audio play finish'); console.info('audio play finish');
...@@ -71,55 +91,24 @@ function SetCallBack(audioPlayer) { ...@@ -71,55 +91,24 @@ function SetCallBack(audioPlayer) {
}); });
} }
function printfDescription(obj) { async function audioPlayerDemo() {
for (let item in obj) { // 1. Create an audioPlayer instance.
let property = obj[item]; let audioPlayer = media.createAudioPlayer();
console.info('audio key is ' + item); setCallBack(audioPlayer); // Set the event callbacks.
console.info('audio value is ' + property); // 2. Set the URI of the audio file selected by the user.
} 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';
// 1. Create an audioPlayer instance. await fileIO.open(path).then((fdNumber) => {
let audioPlayer = media.createAudioPlayer();
SetCallBack(audioPlayer); // Set the event callbacks.
// 2. Set the URI of the audio file selected by the user.
let fdPath = 'fd://'
let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3';
await fileIO.open(path).then(fdNumber) => {
fdPath = fdPath + '' + fdNumber; fdPath = fdPath + '' + fdNumber;
console.info('open fd sucess fd is' + fdPath); console.info('open fd sucess fd is' + fdPath);
}, (err) => { }, (err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}),catch((err) => { }).catch((err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}); });
audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. }
// 3. Play the audio file.
audioPlayer.play(); // The play() API can be invoked only after the 'dataLoad' event callback is complete. The 'play' event callback is triggered.
// 4. Seek to the playback position.
audioPlayer.seek(30000); // Trigger the 'timeUpdate' event callback, and seek to 30000 ms for playback.
// 5. Set the volume.
audioPlayer.setVolume(0.5); // Trigger the 'volumeChange' event callback.
// 6. Pause the playback.
audioPlayer.pause(); // Trigger the 'pause' event callback and pause the playback.
// 7. Obtain the track information.
audioPlayer.getTrackDescription((error, arrlist) => { // Obtain the audio track information in callback mode.
if (typeof (arrlist) != 'undefined') {
for (let i = 0; i < arrlist.length; i++) {
printfDescription(arrlist[i]);
}
} else {
console.log(`audio getTrackDescription fail, error:${error.message}`);
}
});
// 8. Stop the playback.
audioPlayer.stop(); // Trigger the 'stop' event callback.
// 9. Reset the player.
audioPlayer.reset(); // Trigger the 'reset' event callback, and reconfigure the src attribute to switch to the next song.
// 10. Release the resource.
audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer = undefined;
``` ```
### Normal Playback Scenario ### Normal Playback Scenario
...@@ -127,8 +116,9 @@ audioPlayer = undefined; ...@@ -127,8 +116,9 @@ audioPlayer = undefined;
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fileIO from '@ohos.fileio'
export class AudioDemo {
function SetCallBack(audioPlayer) { // Set the player callbacks.
setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success'); console.info('audio set source success');
audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback.
...@@ -138,26 +128,28 @@ function SetCallBack(audioPlayer) { ...@@ -138,26 +128,28 @@ function SetCallBack(audioPlayer) {
}); });
audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
console.info('audio play finish'); console.info('audio play finish');
audioPlayer.release(); // Release the AudioPlayer instance. audioPlayer.release(); // Release the AudioPlayer resources.
audioPlayer = undefined; audioPlayer = undefined;
}); });
} }
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. async audioPlayerDemo() {
SetCallBack(audioPlayer); // Set the event callbacks. let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
/* Set the FD (local playback) of the audio file selected by the user. */ this.setCallBack(audioPlayer); // Set the event callbacks.
let fdPath = 'fd://' let fdPath = 'fd://'
let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; // 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.
await fileIO.open(path).then(fdNumber) => { let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3';
await fileIO.open(path).then((fdNumber) => {
fdPath = fdPath + '' + fdNumber; fdPath = fdPath + '' + fdNumber;
console.info('open fd sucess fd is' + fdPath); console.info('open fd sucess fd is' + fdPath);
}, (err) => { }, (err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}),catch((err) => { }).catch((err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}); });
audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. }
}
``` ```
### Switching to the Next Song ### Switching to the Next Song
...@@ -165,52 +157,62 @@ audioPlayer.src = fdPath; // Set the src attribute and ...@@ -165,52 +157,62 @@ audioPlayer.src = fdPath; // Set the src attribute and
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fileIO from '@ohos.fileio'
export class AudioDemo {
function SetCallBack(audioPlayer) { // Set the player callbacks.
private isNextMusic = false;
setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success'); console.info('audio set source success');
audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback.
}); });
audioPlayer.on('play', () => { // Set the 'play' event callback. audioPlayer.on('play', () => { // Set the 'play' event callback.
console.info('audio play success'); console.info('audio play success');
audioPlayer.reset(); // Call the reset() API and trigger the 'reset' event callback.
}); });
audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. audioPlayer.on('reset', () => { // Set the 'reset' event callback.
console.info('audio play finish'); console.info('audio play success');
if (!this.isNextMusic) { // When isNextMusic is false, changing songs is implemented.
this.nextMusic(audioPlayer); // Changing songs is implemented.
} else {
audioPlayer.release(); // Release the AudioPlayer instance. audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer = undefined; audioPlayer = undefined;
}
}); });
} }
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. async nextMusic(audioPlayer) {
SetCallBack(audioPlayer); // Set the event callbacks. this.isNextMusic = true;
/* Set the FD (local playback) of the audio file selected by the user. */ let nextFdPath = 'fd://'
let fdPath = '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 path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; let nextpath = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/02.mp3';
await fileIO.open(path).then(fdNumber) => { await fileIO.open(nextpath).then((fdNumber) => {
fdPath = fdPath + '' + fdNumber; nextFdPath = nextFdPath + '' + fdNumber;
console.info('open fd sucess fd is' + fdPath); console.info('open fd sucess fd is' + nextFdPath);
}, (err) => { }, (err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}),catch((err) => { }).catch((err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}); });
audioPlayer.src = nextFdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. }
/* Send the instruction to switch to the next song after a period of time. */
audioPlayer.reset(); async audioPlayerDemo() {
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
/* Set the FD (local playback) of the audio file selected by the user. */ this.setCallBack(audioPlayer); // Set the event callbacks.
let fdNextPath = 'fd://' let fdPath = 'fd://'
let nextPath = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; // 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.
await fileIO.open(nextPath).then(fdNumber) => { let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3';
fdNextPath = fdNextPath + '' + fdNumber; await fileIO.open(path).then((fdNumber) => {
console.info('open fd sucess fd is' + fdNextPath); fdPath = fdPath + '' + fdNumber;
}, (err) => { console.info('open fd sucess fd is' + fdPath);
}, (err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}),catch((err) => { }).catch((err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}); });
audioPlayer.src = fdNextPath; audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
}
}
``` ```
### Looping a Song ### Looping a Song
...@@ -218,37 +220,43 @@ audioPlayer.src = fdNextPath; ...@@ -218,37 +220,43 @@ audioPlayer.src = fdNextPath;
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import fileIO from '@ohos.fileio' import fileIO from '@ohos.fileio'
export class AudioDemo {
function SetCallBack(audioPlayer) { // Set the player callbacks.
setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success'); console.info('audio set source success');
audioPlayer.loop = true; // Set the loop playback attribute.
audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback.
}); });
audioPlayer.on('play', () => { // Set the 'play' event callback. audioPlayer.on('play', () => { // Sets the 'play' event callback to start loop playback.
console.info('audio play success'); console.info('audio play success');
}); });
audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. }
console.info('audio play finish');
audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer = undefined;
});
}
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
SetCallBack(audioPlayer); // Set the event callbacks.
/* Set the FD (local playback) of the audio file selected by the user. */ async audioPlayerDemo() {
let fdPath = 'fd://' let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
let path = 'data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; this.setCallBack(audioPlayer); // Set the event callbacks.
await fileIO.open(path).then(fdNumber) => { 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';
await fileIO.open(path).then((fdNumber) => {
fdPath = fdPath + '' + fdNumber; fdPath = fdPath + '' + fdNumber;
console.info('open fd sucess fd is' + fdPath); console.info('open fd sucess fd is' + fdPath);
}, (err) => { }, (err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}),catch((err) => { }).catch((err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}); });
audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. }
audioPlayer.loop = true; // Set the loop playback attribute. }
``` ```
## Samples
The following samples are provided to help you better understand how to develop audio playback:
- [`JsDistributedMusicPlayer`: Distributed Music Player (JS) (API7)](https://gitee.com/openharmony/app_samples/tree/master/ability/JsDistributedMusicPlayer)
- [`JsAudioPlayer`: Audio Playback and Management (JS, API 7)](https://gitee.com/openharmony/app_samples/tree/master/media/JsAudioPlayer)
- [`eTsAudioPlayer`: Audio Player (eTS)](https://gitee.com/openharmony/app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets)
- [Audio Player](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS)
...@@ -25,46 +25,49 @@ The full audio recording process includes creating an instance, setting recordin ...@@ -25,46 +25,49 @@ The full audio recording process includes creating an instance, setting recordin
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import mediaLibrary from '@ohos.multimedia.mediaLibrary' import mediaLibrary from '@ohos.multimedia.mediaLibrary'
export class AudioRecorderDemo {
private testFdNumber; // Used to save the FD address.
let testFdNumber; // Set the callbacks related to audio recording.
setCallBack(audioRecorder) {
function SetCallBack(audioRecorder) {
audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. audioRecorder.on('prepare', () => { // Set the 'prepare' event callback.
console.log('prepare success'); console.log('prepare success');
// The recording page is ready. You can click the Record button to start recording. audioRecorder.start(); // Call the start API to start recording and trigger the 'start' event callback.
}); });
audioRecorder.on('start', () => { // Set the 'start' event callback. audioRecorder.on('start', () => { // Set the 'start' event callback.
console.log('audio recorder start success'); console.log('audio recorder start success');
// The Record button is changed to the pausable state. audioRecorder.pause(); // Call the pause API to pause recording and trigger the 'pause' event callback.
}); });
audioRecorder.on('pause', () => { // Set the 'pause' event callback. audioRecorder.on('pause', () => { // Set the 'pause' event callback.
console.log('audio recorder pause success'); console.log('audio recorder pause success');
// The Record button is changed to the recordable state. audioRecorder.resume(); // Call the resume API to resume recording and trigger the 'resume' event callback.
}); });
audioRecorder.on('resume', () => { // Set the 'resume' event callback. audioRecorder.on('resume', () => { // Set the 'resume' event callback.
console.log('audio recorder resume success'); console.log('audio recorder resume success');
// The Record button is changed to the pausable state. audioRecorder.stop(); // Call the stop API to stop recording and trigger the 'stop' event callback.
}); });
audioRecorder.on('stop', () => { // Set the 'stop' event callback. audioRecorder.on('stop', () => { // Set the 'stop' event callback.
console.log('audio recorder stop success'); console.log('audio recorder stop success');
}); audioRecorder.reset(); // Call the reset API to reset the recorder and trigger the 'reset' event callback.
audioRecorder.on('release', () => { // Set the 'release' event callback.
console.log('audio recorder release success');
}); });
audioRecorder.on('reset', () => { // Set the 'reset' event callback. audioRecorder.on('reset', () => { // Set the 'reset' event callback.
console.log('audio recorder reset success'); console.log('audio recorder reset success');
// You need to reset the recording parameters for another recording. audioRecorder.release(); // Call the release API to release resources and trigger the 'release' event callback.
});
audioRecorder.on('release', () => { // Set the 'release' event callback.
console.log('audio recorder release success');
audioRecorder = undefined;
}); });
audioRecorder.on('error', (error) => { // Set the 'error' event callback. audioRecorder.on('error', (error) => { // Set the 'error' event callback.
console.info(`audio error called, errName is ${error.name}`); console.info(`audio error called, errName is ${error.name}`);
console.info(`audio error called, errCode is ${error.code}`); console.info(`audio error called, errCode is ${error.code}`);
console.info(`audio error called, errMessage is ${error.message}`); console.info(`audio error called, errMessage is ${error.message}`);
}); });
} }
// pathName indicates the passed recording file name, for example, 01.mp3. The generated file address is /storage/media/100/local/files/Movies/01.mp3. // pathName indicates the passed recording file name, for example, 01.mp3. The generated file address is /storage/media/100/local/files/Video/01.mp3.
// To use the media library, declare the following permissions: ohos.permission.MEDIA_LOCATION, ohos.permission.WRITE_MEDIA, and ohos.permission.READ_MEDIA. // To use the media library, declare the following permissions: ohos.permission.MEDIA_LOCATION, ohos.permission.WRITE_MEDIA, and ohos.permission.READ_MEDIA.
async function getFd(pathName) { async getFd(pathName) {
let displayName = pathName; let displayName = pathName;
const mediaTest = mediaLibrary.getMediaLibrary(); const mediaTest = mediaLibrary.getMediaLibrary();
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
...@@ -80,41 +83,29 @@ async function getFd(pathName) { ...@@ -80,41 +83,29 @@ async function getFd(pathName) {
let fetchFileResult = await mediaTest.getFileAssets(fetchOp); let fetchFileResult = await mediaTest.getFileAssets(fetchOp);
let fileAsset = await fetchFileResult.getAllObject(); let fileAsset = await fetchFileResult.getAllObject();
let fdNumber = await fileAsset[0].open('Rw'); let fdNumber = await fileAsset[0].open('Rw');
fdNumber = "fd://" + fdNumber.toString(); this.testFdNumber = "fd://" + fdNumber.toString();
testFdNumber = fdNumber; }
} }
}
await getFd('01.mp3');
// 1. Create an AudioRecorder instance. async audioRecorderDemo() {
let audioRecorder = media.createAudioRecorder(); // 1. Create an AudioRecorder instance.
// 2. Set the callbacks. let audioRecorder = media.createAudioRecorder();
SetCallBack(audioRecorder); // 2. Set the callbacks.
// 3. Set the recording parameters. this.setCallBack(audioRecorder);
let audioRecorderConfig = { await this.getFd('01.mp3'); // Call the getFd method to obtain the FD address of the file to be recorded.
audioEncoder : media.AudioEncoder.AAC_LC , // 3. Set the recording parameters.
let audioRecorderConfig = {
audioEncodeBitRate : 22050, audioEncodeBitRate : 22050,
audioSampleRate : 22050, audioSampleRate : 22050,
numberOfChannels : 2, numberOfChannels : 2,
format : media.AudioOutputFormat.AAC_ADTS, uri : this.testFdNumber, // testFdNumber is generated by getFd.
uri : testFdNumber, // testFdNumber is generated by getFd.
location : { latitude : 30, longitude : 130}, location : { latitude : 30, longitude : 130},
audioEncoderMime : media.CodecMimeType.AUDIO_AAC,
fileFormat : media.ContainerFormatType.CFT_MPEG_4A,
}
audioRecorder.prepare(audioRecorderConfig); // Call the prepare method to trigger the 'prepare' event callback.
}
} }
audioRecorder.prepare(audioRecorderConfig);
// 4. Start recording.
audioRecorder.start(); // The start API can be called to trigger the 'start' event callback only after the 'prepare' event callback is complete.
// 5. Pause recording.
audioRecorder.pause(); // The pause API can be called to trigger the 'pause' event callback only after the 'start' event callback is complete.
// 6. Resume recording.
audioRecorder.resume(); // The resume API can be called to trigger the 'resume' event callback only after the 'pause' event callback is complete.
// 7. Stop recording.
audioRecorder.stop(); // The stop API can be called to trigger the 'stop' event callback only after the 'start' or 'resume' event callback is complete.
// 8. Reset recording.
audioRecorder.reset(); // The prepare API can be called for another recording only after the 'reset' event callback is complete.
// 9. Release resources.
audioRecorder.release(); // The AudioRecorder resource is destroyed.
audioRecorder = undefined;
``` ```
### Normal Recording Scenario ### Normal Recording Scenario
...@@ -124,29 +115,37 @@ Unlike the full-process scenario, the normal recording scenario does not include ...@@ -124,29 +115,37 @@ Unlike the full-process scenario, the normal recording scenario does not include
```js ```js
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import mediaLibrary from '@ohos.multimedia.mediaLibrary' import mediaLibrary from '@ohos.multimedia.mediaLibrary'
export class AudioRecorderDemo {
private testFdNumber; // Used to save the FD address.
let testFdNumber; // Set the callbacks related to audio recording.
setCallBack(audioRecorder) {
function SetCallBack(audioRecorder) {
audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. audioRecorder.on('prepare', () => { // Set the 'prepare' event callback.
console.log('prepare success'); console.log('prepare success');
// The recording page is ready. You can click the Record button to start recording. audioRecorder.start(); // Call the start API to start recording and trigger the 'start' event callback.
}); });
audioRecorder.on('start', () => { // Set the 'start' event callback. audioRecorder.on('start', () => { // Set the 'start' event callback.
console.log('audio recorder start success'); console.log('audio recorder start success');
// The Record button is changed to the pausable state. audioRecorder.stop(); // Call the stop API to stop recording and trigger the 'stop' event callback.
}); });
audioRecorder.on('stop', () => { // Set the 'stop' event callback. audioRecorder.on('stop', () => { // Set the 'stop' event callback.
console.log('audio recorder stop success'); console.log('audio recorder stop success');
audioRecorder.release(); // Call the release API to release resources and trigger the 'release' event callback.
}); });
audioRecorder.on('release', () => { // Set the 'release' event callback. audioRecorder.on('release', () => { // Set the 'release' event callback.
console.log('audio recorder release success'); console.log('audio recorder release success');
audioRecorder = undefined;
}); });
} audioRecorder.on('error', (error) => { // Set the 'error' event callback.
console.info(`audio error called, errName is ${error.name}`);
console.info(`audio error called, errCode is ${error.code}`);
console.info(`audio error called, errMessage is ${error.message}`);
});
}
// pathName indicates the passed recording file name, for example, 01.mp3. The generated file address is /storage/media/100/local/files/Movies/01.mp3. // pathName indicates the passed recording file name, for example, 01.mp3. The generated file address is /storage/media/100/local/files/Video/01.mp3.
// To use the media library, declare the following permissions: ohos.permission.MEDIA_LOCATION, ohos.permission.WRITE_MEDIA, and ohos.permission.READ_MEDIA. // To use the media library, declare the following permissions: ohos.permission.MEDIA_LOCATION, ohos.permission.WRITE_MEDIA, and ohos.permission.READ_MEDIA.
async function getFd(pathName) { async getFd(pathName) {
let displayName = pathName; let displayName = pathName;
const mediaTest = mediaLibrary.getMediaLibrary(); const mediaTest = mediaLibrary.getMediaLibrary();
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
...@@ -162,33 +161,35 @@ async function getFd(pathName) { ...@@ -162,33 +161,35 @@ async function getFd(pathName) {
let fetchFileResult = await mediaTest.getFileAssets(fetchOp); let fetchFileResult = await mediaTest.getFileAssets(fetchOp);
let fileAsset = await fetchFileResult.getAllObject(); let fileAsset = await fetchFileResult.getAllObject();
let fdNumber = await fileAsset[0].open('Rw'); let fdNumber = await fileAsset[0].open('Rw');
fdNumber = "fd://" + fdNumber.toString(); this.testFdNumber = "fd://" + fdNumber.toString();
testFdNumber = fdNumber; }
} }
}
await getFd('01.mp3');
// 1. Create an AudioRecorder instance. async audioRecorderDemo() {
let audioRecorder = media.createAudioRecorder(); // 1. Create an AudioRecorder instance.
// 2. Set the callbacks. let audioRecorder = media.createAudioRecorder();
SetCallBack(audioRecorder); // 2. Set the callbacks.
// 3. Set the recording parameters. this.setCallBack(audioRecorder);
let audioRecorderConfig = { await this.getFd('01.mp3'); // Call the getFd method to obtain the FD address of the file to be recorded.
audioEncoder : media.AudioEncoder.AAC_LC , // 3. Set the recording parameters.
let audioRecorderConfig = {
audioEncodeBitRate : 22050, audioEncodeBitRate : 22050,
audioSampleRate : 22050, audioSampleRate : 22050,
numberOfChannels : 2, numberOfChannels : 2,
format : media.AudioOutputFormat.AAC_ADTS, uri : this.testFdNumber, // testFdNumber is generated by getFd.
uri : testFdNumber, // testFdNumber is generated by getFd.
location : { latitude : 30, longitude : 130}, location : { latitude : 30, longitude : 130},
audioEncoderMime : media.CodecMimeType.AUDIO_AAC,
fileFormat : media.ContainerFormatType.CFT_MPEG_4A,
}
audioRecorder.prepare(audioRecorderConfig); // Call the prepare method to trigger the 'prepare' event callback.
}
} }
audioRecorder.prepare(audioRecorderConfig)
// 4. Start recording.
audioRecorder.start(); // The start API can be called to trigger the 'start' event callback only after the 'prepare' event callback is complete.
// 5. Stop recording.
audioRecorder.stop(); // The stop API can be called to trigger the 'stop' event callback only after the 'start' or 'resume' event callback is complete.
// 6. Release resources.
audioRecorder.release(); // The AudioRecorder resource is destroyed.
audioRecorder = undefined;
``` ```
## Samples
The following samples are provided to help you better understand how to develop audio recording:
- [`Recorder`: Recorder (eTS, API 8)](https://gitee.com/openharmony/app_samples/tree/master/media/Recorder)
- [`eTsAudioPlayer`: Audio Player (eTS)](https://gitee.com/openharmony/app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets)
- [Audio Player](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS)
...@@ -8,7 +8,7 @@ ...@@ -8,7 +8,7 @@
## 接口说明 ## 接口说明
| 模块 | 接口名 | 描述 | | 模块 | 接口名 | 描述 |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| ohos.vibrator | vibrate(duration:&nbsp;number):&nbsp;Promise&lt;void&gt; | 触发马达按照时长振动,Promise型。 | | ohos.vibrator | vibrate(duration:&nbsp;number):&nbsp;Promise&lt;void&gt; | 触发马达按照时长振动,Promise型。 |
| ohos.vibrator | vibrate(duration:&nbsp;number,&nbsp;callback?:&nbsp;AsyncCallback&lt;void&gt;):&nbsp;void | 触发马达按照时长振动,Callback型。 | | ohos.vibrator | vibrate(duration:&nbsp;number,&nbsp;callback?:&nbsp;AsyncCallback&lt;void&gt;):&nbsp;void | 触发马达按照时长振动,Callback型。 |
...@@ -74,7 +74,7 @@ ...@@ -74,7 +74,7 @@
``` ```
import vibrator from "@ohos.vibrator" import vibrator from "@ohos.vibrator"
vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PREET).then((error)=>{ vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then((error)=>{
if(error){//调用失败,打印error.code和error.message if(error){//调用失败,打印error.code和error.message
console.log("Promise return failed.error.code"+error.code+"error.message"+error.message); console.log("Promise return failed.error.code"+error.code+"error.message"+error.message);
}else{//调用成功,设备停止振动 }else{//调用成功,设备停止振动
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册