harmony 鸿蒙Using AVScreenCaptureRecorder to Record Screens and Save Them to Files (ArkTS)
Using AVScreenCaptureRecorder to Record Screens and Save Them to Files (ArkTS)
Screen capture is mainly used to record the main screen.
You can call the ArkTS APIs of the AVScreenCaptureRecorder module to record the screen and collect audio and video source data output by the device and microphone. You can call the APIs to obtain audio and video files and transfer the files to other modules for playback or processing. In this way, screen content can be shared in the form of files.
The AVScreenCaptureRecorder, Window, and Graphics modules together implement the entire video capture process.
The full screen capture process involves creating an AVScreenCaptureRecorder instance, configuring audio and video capture parameters, starting and stopping screen capture, and releasing resources.
If you are in a call when screen capture starts or a call is coming during screen capture, screen capture automatically stops, and the SCREENCAPTURE_STATE_STOPPED_BY_CALL status is reported.
This topic describes how to use the AVScreenCaptureRecorder APIs to carry out one-time screen capture. For details about the API reference, see AVScreenCaptureRecorder.
If microphone data collection is configured, configure the permission ohos.permission.MICROPHONE and request a continuous task. For details, see Requesting User Authorization and Continuous Task.
Applying for Permission
Before your development, configure the following permissions for your application.
- To use the microphone, request the ohos.permission.MICROPHONE permission. For details about how to request user authorization, see Requesting User Authorization.
- To read images or videos, preferentially use the media library Picker for access.
- To save images or videos, preferentially use the security component for storage.
NOTE
To clone, back up, or synchronize images and videos in users’ public directory, request the ohos.permission.READ_IMAGEVIDEO and ohos.permission.WRITE_IMAGEVIDEO permissions for reading and writing audio files. For details, see Requesting Restricted Permissions.
How to Develop
After an AVScreenCaptureRecorder instance is created, different APIs can be called to switch the AVScreenCaptureRecorder to different states and trigger the required behavior. If an API is called when the AVScreenCaptureRecorder is not in the given state, the system may throw an exception or generate other undefined behavior. Therefore, you are advised to check the AVScreenCaptureRecorder state before triggering state transition.
Add the header files.
import media from '@ohos.multimedia.media'; import fs from '@ohos.file.fs';
Create the member variable screenCapture of the AVScreenCaptureRecorder type.
// Declare a member variable of the AVScreenCaptureRecorder type. private screenCapture?: media.AVScreenCaptureRecorder; // Create an AVScreenCaptureRecorder instance and assign a value to the member variable screenCapture. this.screenCapture = await media.createAVScreenCaptureRecorder();
Set callback functions for the member variable screenCapture to listen for state changes and errors.
this.screenCapture.on('stateChange', async (infoType: media.AVScreenCaptureStateCode) => { switch (infoType) { case media.AVScreenCaptureStateCode.SCREENCAPTURE_STATE_STARTED: console.info("Callback invoked when screen capture starts"); break; case media.AVScreenCaptureStateCode.SCREENCAPTURE_STATE_CANCELED: this.screenCapture?.release(); this.screenCapture = undefined; console.info("Screen capture is not allowed."); break; case media.AVScreenCaptureStateCode.SCREENCAPTURE_STATE_STOPPED_BY_USER: this.screenCapture?.release(); this.screenCapture = undefined; console.info("Touch the button in the screen capture capsule to stop screen capture. Underlying capture will stop."); break; case media.AVScreenCaptureStateCode.SCREENCAPTURE_STATE_INTERRUPTED_BY_OTHER: console.info("Screen capture stops due to other interruptions. Underlying capture will stop."); break; case media.AVScreenCaptureStateCode.SCREENCAPTURE_STATE_STOPPED_BY_CALL: console.info("Screen capture stops due to incoming calls. Underlying capture will stop."); break; case media.AVScreenCaptureStateCode.SCREENCAPTURE_STATE_MIC_UNAVAILABLE: console.info("The screen capture microphone is unavailable."); break; case media.AVScreenCaptureStateCode.SCREENCAPTURE_STATE_MIC_MUTED_BY_USER: console.info("The screen capture microphone is muted by the user."); break; case media.AVScreenCaptureStateCode.SCREENCAPTURE_STATE_MIC_UNMUTED_BY_USER: console.info("The screen capture microphone is unmuted by the user."); break; case media.AVScreenCaptureStateCode.SCREENCAPTURE_STATE_ENTER_PRIVATE_SCENE: // Currently, you can directly register a listener from the system to enter the privacy scenario. console.info("Screen capture enters the privacy scenario."); break; case media.AVScreenCaptureStateCode.SCREENCAPTURE_STATE_EXIT_PRIVATE_SCENE: console.info("Screen capture exits the privacy scenario."); break; case media.AVScreenCaptureStateCode.SCREENCAPTURE_STATE_STOPPED_BY_USER_SWITCHES: console.info("Underlying capture will stop after the user account is changed."); break; default: break; } }) this.screenCapture.on('error', (err) => { console.error("Handle exceptions."); })
Set screen capture parameters.
After creating the screenCapture instance, you can set the parameters required for screen capture.
Parameters videoBitrate, audioSampleRate, audioChannelCount, audioBitrate, preset, and displayId are optional, with default values provided in the code snippet below. The audio streams of the microphone and system sound share a set of audio parameters: audioSampleRate, audioChannelCount, and audioBitrate.
You can create, read, and write a file descriptor by referring to the sample code in Accessing Application Files to obtain the value of the fd parameter. The getFileFd() API provided in the example below is for reference only.
If displayId is set to the extended display ID of a 2-in-1 device, a dialog box for screen capture selection can be opened. Users can select the screen to capture in the dialog box, and the recorded content will match the user’s choices.
public getFileFd(): number { let filesDir = '/data/storage/el2/base/haps'; let file = fs.openSync(filesDir + '/screenCapture.mp4', fs.OpenMode.READ_WRITE|fs.OpenMode.CREATE); return file.fd; } captureConfig: media.AVScreenCaptureRecordConfig = { // Set the width and height as required. frameWidth: 768, frameHeight: 1280, // Create, read, and write a file descriptor by referring to the sample code in Accessing Application Files. fd: this.getFileFd(), // Optional parameters and their default values videoBitrate: 10000000, audioSampleRate: 48000, audioChannelCount: 2, audioBitrate: 96000, displayId: 0, preset: media.AVScreenCaptureRecordPreset.SCREEN_RECORD_PRESET_H264_AAC_MP4 };
Call init() to initialize the screenCapture instance based on the preset screen capture parameters.
await this.screenCapture.init(this.captureConfig);
Set the windows that will be skipped during screen capture, by entering the subwindow IDs and main window IDs. For details, see Window API Reference.
let windowIDs = [57, 86]; await screenCapture.skipPrivacyMode(windowIDs);
Call startRecording() to start screen capture and listen for state changes using the callback function.
await this.screenCapture.startRecording();
Stop screen capture.
When the user touches the stop button in the screen capture capsule to stop screen capture, the screenCapture instance triggers the SCREENCAPTURE_STATE_STOPPED_BY_USER callback to notify the application that the screen recording has stopped. The application does not need to call the stopRecording() API.
The application proactively calls stopRecording() to stop screen capture.
await this.screenCapture.stopRecording();
Call release() to release the instance.
await this.screenCapture.release();
Development Example
Refer to the sample code below to implement captured file storage using AVScreenCaptureRecorder.
import media from '@ohos.multimedia.media';
import fs from '@ohos.file.fs';
export class AVScreenCaptureDemo {
private screenCapture?: media.AVScreenCaptureRecorder;
captureConfig: media.AVScreenCaptureRecordConfig = {
// Set the width and height as required.
frameWidth: 768,
frameHeight: 1280,
// Create, read, and write a file descriptor by referring to the sample code in Accessing Application Files.
fd: this.getFileFd(),
// Optional parameters and their default values
videoBitrate: 10000000,
audioSampleRate: 48000,
audioChannelCount: 2,
audioBitrate: 96000,
displayId: 0,
preset: media.AVScreenCaptureRecordPreset.SCREEN_RECORD_PRESET_H264_AAC_MP4
};
public getFileFd(): number {
let filesDir = '/data/storage/el2/base/haps';
let file = fs.openSync(filesDir + '/screenCapture.mp4', fs.OpenMode.READ_WRITE|fs.OpenMode.CREATE);
return file.fd;
}
// Call startRecording to start screen capture. To stop screen capture, click the stop button in the screen capture capsule.
public async startRecording() {
this.screenCapture = await media.createAVScreenCaptureRecorder();
if (this.screenCapture != undefined) {
// success.
} else {
// failed.
return;
}
this.screenCapture?.on('stateChange', async (infoType: media.AVScreenCaptureStateCode) => {
switch (infoType) {
case media.AVScreenCaptureStateCode.SCREENCAPTURE_STATE_STARTED:
console.info("Callback invoked when screen capture starts");
break;
case media.AVScreenCaptureStateCode.SCREENCAPTURE_STATE_CANCELED:
this.screenCapture?.release();
this.screenCapture = undefined;
console.info("Screen capture is not allowed.");
break;
case media.AVScreenCaptureStateCode.SCREENCAPTURE_STATE_STOPPED_BY_USER:
this.screenCapture?.release();
this.screenCapture = undefined;
console.info("Touch the button in the screen capture capsule to stop screen capture. Underlying capture will stop.");
break;
case media.AVScreenCaptureStateCode.SCREENCAPTURE_STATE_INTERRUPTED_BY_OTHER:
console.info("Screen capture stops due to other interruptions. Underlying capture will stop.");
break;
case media.AVScreenCaptureStateCode.SCREENCAPTURE_STATE_STOPPED_BY_CALL:
console.info("Screen capture stops due to incoming calls. Underlying capture will stop.");
break;
case media.AVScreenCaptureStateCode.SCREENCAPTURE_STATE_MIC_UNAVAILABLE:
console.info("The screen capture microphone is unavailable.");
break;
case media.AVScreenCaptureStateCode.SCREENCAPTURE_STATE_MIC_MUTED_BY_USER:
console.info("The screen capture microphone is muted by the user.");
break;
case media.AVScreenCaptureStateCode.SCREENCAPTURE_STATE_MIC_UNMUTED_BY_USER:
console.info("The screen capture microphone is unmuted by the user.");
break;
case media.AVScreenCaptureStateCode.SCREENCAPTURE_STATE_ENTER_PRIVATE_SCENE:
// Currently, you can directly register a listener from the system to enter the privacy scenario.
console.info("Screen capture enters the privacy scenario.");
break;
case media.AVScreenCaptureStateCode.SCREENCAPTURE_STATE_EXIT_PRIVATE_SCENE:
console.info("Screen capture exits the privacy scenario.");
break;
case media.AVScreenCaptureStateCode.SCREENCAPTURE_STATE_STOPPED_BY_USER_SWITCHES:
console.info("Underlying capture will stop after the user account is changed.");
break;
default:
break;
}
})
this.screenCapture?.on('error', (err) => {
console.error("Handle exceptions.");
})
await this.screenCapture?.init(this.captureConfig);
// Exempt privacy windows.
let windowIDs = [57, 86];
await this.screenCapture?.skipPrivacyMode(windowIDs);
await this.screenCapture?.startRecording();
}
// Proactively call stopRecording to stop screen capture.
public async stopRecording() {
if (this.screenCapture == undefined) {
// Error.
return;
}
await this.screenCapture?.stopRecording();
// Call release() to release the instance.
await this.screenCapture?.release();
// Call fs.close (fd); to close the FD of the created screen capture file.
}
}
你可能感兴趣的鸿蒙文章
harmony 鸿蒙Using AVImageGenerator to Extract Video Images at a Specified Time (ArkTS)
harmony 鸿蒙Using AVMetadataExtractor to Extract Audio and Video Metadata (ArkTS)
harmony 鸿蒙FAQs About Transcoding
harmony 鸿蒙Creating an Asynchronous Thread for AVTranscoder Video Transcoding (ArkTS)
harmony 鸿蒙Introduction to Media Kit
harmony 鸿蒙Using AVPlayer to Set Playback URLs (ArkTS)
harmony 鸿蒙Using AVPlayer to Play Streaming Media (ArkTS)
- 所属分类: 后端技术
- 本文标签:
热门推荐
-
2、 - 优质文章
-
3、 gate.io
-
8、 golang
-
9、 openharmony
-
10、 Vue中input框自动聚焦