• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Starting a Camera and Microphone
2
3Web Real-Time Communications (WebRTC) is a real-time communication technology that allows network applications or sites to establish peer-to-peer (P2P) connections between browsers without an intermediary, implementing the transmission of video streams, audio streams, or other data. It enables users to create peer-to-peer (P2P) data sharing and conference calls without installing any plug-in or third-party software. WebRTC is applicable to all modern browsers and native clients on major platforms. The underlying technology is implemented as an open web standard and provided as a common JavaScript API in all major browsers.
4
5The **Web** component can start a camera and microphone by calling the W3C Standards-compliant API **navigator.mediaDevices.getUserMedia()** in JavaScript, and receive the permission request notification through [onPermissionRequest](../reference/apis-arkweb/arkts-basic-components-web-events.md#onpermissionrequest9). To call these APIs, you need to declare the audio permissions in the **module.json5** file.
6
7- For details about how to add audio permissions, see [Declaring Permissions](../security/AccessToken/declare-permissions.md).
8
9   ```json
10    // src/main/resources/base/element/string.json
11    {
12      "name": "reason_for_camera",
13      "value": "reason_for_camera"
14    },
15    {
16      "name": "reason_for_microphone",
17      "value": "reason_for_microphone"
18    }
19  ```
20
21  ```json
22    // src/main/module.json5
23    "requestPermissions":[
24      {
25        "name" : "ohos.permission.CAMERA",
26        "reason": "$string:reason_for_camera",
27        "usedScene": {
28          "abilities": [
29            "EntryAbility"
30          ],
31          "when":"inuse"
32        }
33      },
34      {
35        "name" : "ohos.permission.MICROPHONE",
36        "reason": "$string:reason_for_microphone",
37        "usedScene": {
38          "abilities": [
39            "EntryAbility"
40          ],
41          "when":"inuse"
42        }
43      }
44    ],
45   ```
46
47Invoke the **navigator.mediaDevices.getUserMedia()** API in JavaScript to start the camera and microphone. The **constraints** parameter in the API is a **MediaStreamConstraints** object that specifies the types of media to request. It contains two members: **video** and **audio**.
48
49In the following example, when a user clicks the button for enabling the camera on the frontend page and the **onConfirm** button, the **Web** component starts the camera and microphone.
50
51- Application code:
52
53  ```ts
54  // xxx.ets
55  import { webview } from '@kit.ArkWeb';
56  import { BusinessError } from '@kit.BasicServicesKit';
57  import { abilityAccessCtrl } from '@kit.AbilityKit';
58
59  @Entry
60  @Component
61  struct WebComponent {
62    controller: webview.WebviewController = new webview.WebviewController();
63    uiContext: UIContext = this.getUIContext();
64
65    aboutToAppear() {
66      // Enable web frontend page debugging.
67      webview.WebviewController.setWebDebuggingAccess(true);
68      // Obtain the permission request notification. After the onConfirm button is clicked, the camera and microphone are started.
69      let atManager = abilityAccessCtrl.createAtManager();
70      atManager.requestPermissionsFromUser(this.uiContext.getHostContext(), ['ohos.permission.CAMERA', 'ohos.permission.MICROPHONE'])
71        .then((data) => {
72          console.info('data:' + JSON.stringify(data));
73          console.info('data permissions:' + data.permissions);
74          console.info('data authResults:' + data.authResults);
75        }).catch((error: BusinessError) => {
76        console.error(`Failed to request permissions from user. Code is ${error.code}, message is ${error.message}`);
77      })
78    }
79
80    build() {
81      Column() {
82        Web({ src: $rawfile('index.html'), controller: this.controller })
83          .onPermissionRequest((event) => {
84            if (event) {
85              this.uiContext.showAlertDialog({
86                title: 'title',
87                message: 'text',
88                primaryButton: {
89                  value: 'deny',
90                  action: () => {
91                    event.request.deny();
92                  }
93                },
94                secondaryButton: {
95                  value: 'onConfirm',
96                  action: () => {
97                    event.request.grant(event.request.getAccessibleResource());
98                  }
99                },
100                cancel: () => {
101                  event.request.deny();
102                }
103              })
104            }
105          })
106      }
107    }
108  }
109  ```
110
111- Code of the **index.html** page:
112
113  ```html
114  <!-- index.html -->
115  <!DOCTYPE html>
116  <html>
117  <head>
118    <meta charset="UTF-8">
119  </head>
120  <body>
121  <video id="video" width="500px" height="500px" autoplay="autoplay"></video>
122  <canvas id="canvas" width="500px" height="500px"></canvas>
123  <br>
124  <input type="button" title="HTML5 Camera" value="Enable Camera" onclick="getMedia()"/>
125  <script>
126    function getMedia()
127    {
128      let constraints = {
129        video: {width: 500, height: 500},
130        audio: true
131      };
132      // Obtain the video camera area.
133      let video = document.getElementById("video");
134      // Returned Promise object
135      let promise = navigator.mediaDevices.getUserMedia(constraints);
136      // then() is asynchronous. Invoke the MediaStream object as a parameter.
137      promise.then(function (MediaStream) {
138        video.srcObject = MediaStream;
139        video.play();
140      });
141    }
142  </script>
143  </body>
144  </html>
145  ```
146