文档管理中心
您当前正在浏览新版开发者文档中心,目录分类和层级有所调整。点击左侧当前文档分类名称前的“☰”图标,可切换文档分类。 了解新版目录
指南与API参考指南应用框架ArkWeb(方舟Web)使用网页多媒体在Web中打开摄像头和麦克风

在Web中打开摄像头和麦克风

WebRTC(Web Real-Time Communications)是一项实时通讯技术,它允许网络应用或站点在无需中间媒介的情况下建立浏览器之间的点对点(Peer-to-Peer)连接,实现视频流、音频流或其他任意数据的传输。WebRTC所包含的标准使得用户无需安装任何插件或第三方软件即可创建点对点(Peer-to-Peer)的数据共享与音视频会议。WebRTC技术适用于所有现代浏览器和主要平台的本机客户端,其背后的技术作为开放的Web标准实现,并在所有主要浏览器中作为常规JavaScript API提供。

申请权限

Web组件可以通过W3C标准协议接口访问摄像头和麦克风,通过onPermissionRequest接口接收权限请求通知,需在配置文件中声明相应的音视频权限并且进行系统侧授权与应用侧授权。

在module.json5配置权限

  • 使用摄像头和麦克风功能前请在module.json5中添加音视频相关权限,权限的添加方法请参考在配置文件中声明权限。

    收起
    自动换行
    深色代码主题
    复制
    1. // src/main/resources/base/element/string.json
    2. "string":[
    3. {
    4. "name": "reason_for_camera",
    5. "value": "reason_for_camera"
    6. },
    7. {
    8. "name": "reason_for_microphone",
    9. "value": "reason_for_microphone"
    10. }
    11. ]
    收起
    自动换行
    深色代码主题
    复制
    1. // src/main/module.json5
    2. "requestPermissions":[
    3. {
    4. "name" : "ohos.permission.CAMERA",
    5. "reason": "$string:reason_for_camera",
    6. "usedScene": {
    7. "abilities": [
    8. "EntryAbility"
    9. ],
    10. "when":"inuse"
    11. }
    12. },
    13. {
    14. "name" : "ohos.permission.MICROPHONE",
    15. "reason": "$string:reason_for_microphone",
    16. "usedScene": {
    17. "abilities": [
    18. "EntryAbility"
    19. ],
    20. "when":"inuse"
    21. }
    22. }
    23. ]

通过在JavaScript中调用W3C标准协议接口navigator.mediaDevices.getUserMedia(),该接口用于打开摄像头和麦克风。constraints参数是一个包含了video和audio两个成员的MediaStreamConstraints对象,用于说明请求的媒体类型。

系统侧授权

参考完整示例代码中,调用requestPermissionsFromUser,使得进入应用后会弹出是否允许该应用访问摄像头和麦克风的授权框,需点击"始终允许"或"每次使用时询问"按钮,授权应用访问摄像头和麦克风。

应用侧授权

参考完整示例代码中,点击前端界面中的"开启摄像头"按钮后会通过onPermissionRequest触发权限请求,在弹出的对话框中单击"onConfirm"按钮后,打开摄像头和麦克风。

完整示例代码

收起
自动换行
深色代码主题
复制
  1. import { webview } from '@kit.ArkWeb';
  2. import { BusinessError } from '@kit.BasicServicesKit';
  3. import { abilityAccessCtrl } from '@kit.AbilityKit';
  4. @Entry
  5. @Component
  6. struct WebComponent {
  7. controller: webview.WebviewController = new webview.WebviewController();
  8. uiContext: UIContext = this.getUIContext();
  9. aboutToAppear() {
  10. // 配置Web开启调试模式
  11. webview.WebviewController.setWebDebuggingAccess(true);
  12. // 获取摄像头和麦克风权限,在组件创建时主动申请权限。
  13. let atManager = abilityAccessCtrl.createAtManager();
  14. atManager.requestPermissionsFromUser(this.uiContext.getHostContext(), ['ohos.permission.CAMERA', 'ohos.permission.MICROPHONE'])
  15. .then((data) => {
  16. console.info('data:' + JSON.stringify(data));
  17. console.info('data permissions:' + data.permissions);
  18. console.info('data authResults:' + data.authResults);
  19. }).catch((error: BusinessError) => {
  20. console.error(`Failed to request permissions from user. Code is ${error.code}, message is ${error.message}`);
  21. })
  22. }
  23. build() {
  24. Column() {
  25. Web({ src: $rawfile('index.html'), controller: this.controller })
  26. .onPermissionRequest((event) => {
  27. if (event) {
  28. this.uiContext.showAlertDialog({
  29. title: 'title',
  30. message: 'text',
  31. primaryButton: {
  32. value: 'deny',
  33. action: () => {
  34. event.request.deny();
  35. }
  36. },
  37. secondaryButton: {
  38. value: 'onConfirm',
  39. action: () => {
  40. event.request.grant(event.request.getAccessibleResource());
  41. }
  42. },
  43. cancel: () => {
  44. event.request.deny();
  45. }
  46. })
  47. }
  48. })
  49. }
  50. }
  51. }
  • 前端界面index.html代码。

    收起
    自动换行
    深色代码主题
    复制
    1. <!-- index.html -->
    2. <!DOCTYPE html>
    3. <html>
    4. <head>
    5. <meta charset="UTF-8">
    6. </head>
    7. <body>
    8. <video id="video" width="500px" height="500px" autoplay></video>
    9. <canvas id="canvas" width="500px" height="500px"></canvas>
    10. <br>
    11. <input type="button" title="HTML5摄像头" value="开启摄像头" onclick="getMedia()"/>
    12. <script>
    13. function getMedia()
    14. {
    15. let constraints = {
    16. video: {width: 500, height: 500},
    17. audio: true
    18. };
    19. // 获取video摄像头区域
    20. let video = document.getElementById("video");
    21. // 返回的Promise对象
    22. let promise = navigator.mediaDevices.getUserMedia(constraints);
    23. // then()异步,调用MediaStream对象作为参数
    24. promise.then(function(MediaStream) {
    25. video.srcObject = MediaStream;
    26. video.play();
    27. }).catch(function(err) {
    28. console.info(err.name + ": " + err.message);
    29. });
    30. }
    31. </script>
    32. </body>
    33. </html>

WebRTC常见问题

WebRTC在实际应用中可能会遇到包括设备调用相关的问题,常见问题如下。

华为浏览器中HTML5页面选择长焦摄像头无法对焦

问题现象

网站打开相机,设备默认选择长焦摄像头,无法对焦。

可能原因

  • 当前鸿蒙平台的相机列表顺序返回deviceId。

  • 华为浏览器是系统应用,最后一个摄像头是长焦摄像头。

部分网站遍历设备后通过deviceId来强选最后一个摄像头,这两个因素叠加,在华为浏览器上就选择到长焦了。

解决措施

鸿蒙平台的相机列表顺序返回deviceId,因此有两个修改方案。

方案一:可以直接使用facingMode: 'environment'让浏览器自动选择后置摄像头,从而绕过直接指定deviceId的逻辑。

示例如下:

收起
自动换行
深色代码主题
复制
  1. <!-- index.html -->
  2. <!DOCTYPE html>
  3. <html lang="zh-CN">
  4. <head>
  5. <meta charset="UTF-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  7. <title>后置摄像头预览</title>
  8. <style>
  9. body { text-align: center; padding-top: 50px; }
  10. button { font-size: 18px; padding: 12px 24px; margin: 10px; }
  11. video { width: 80%; max-width: 500px; border: 1px solid #ccc; margin-top: 20px; background: #222; }
  12. </style>
  13. </head>
  14. <body>
  15. <h2>后置摄像头预览facingMode</h2>
  16. <video id="video" autoplay playsinline></video>
  17. <br>
  18. <button id="onBtn">打开后置摄像头</button>
  19. <button id="offBtn" disabled>关闭摄像头</button>
  20. <script>
  21. let currentStream = null;
  22. const video = document.getElementById('video');
  23. const onBtn = document.getElementById('onBtn');
  24. const offBtn = document.getElementById('offBtn');
  25. async function openCamera() {
  26. try {
  27. if (currentStream) {
  28. currentStream.getTracks().forEach(t => t.stop());
  29. currentStream = null;
  30. }
  31. // 使用facingMode:'environment'让浏览器自动选择后置摄像头
  32. const stream = await navigator.mediaDevices.getUserMedia({
  33. video: { facingMode: 'environment' },
  34. audio: false
  35. });
  36. video.srcObject = stream;
  37. currentStream = stream;
  38. onBtn.disabled = true;
  39. offBtn.disabled = false;
  40. console.info('后置摄像头已打开');
  41. } catch (err) {
  42. console.error('打开摄像头失败:', err);
  43. alert('无法打开后置摄像头,请检查权限或 HTTPS 环境。');
  44. }
  45. }
  46. function closeCamera() {
  47. if (currentStream) {
  48. currentStream.getTracks().forEach(t => t.stop());
  49. currentStream = null;
  50. }
  51. video.srcObject = null;
  52. onBtn.disabled = false;
  53. offBtn.disabled = true;
  54. console.info('摄像头已关闭');
  55. }
  56. onBtn.addEventListener('click', openCamera);
  57. offBtn.addEventListener('click', closeCamera);
  58. window.addEventListener('beforeunload', () => {
  59. if (currentStream) {
  60. currentStream.getTracks().forEach(t => t.stop());
  61. }
  62. });
  63. </script>
  64. </body>
  65. </html>

方案二:遍历后置摄像头选择第一个后置摄像头。

  • 遍历设备,获取第一个后置摄像头的deviceId。

  • 通过deviceId来强选第一个后置摄像头。

示例如下:

收起
自动换行
深色代码主题
复制
  1. <!-- index.html -->
  2. <!DOCTYPE html>
  3. <html lang="zh-CN">
  4. <head>
  5. <meta charset="UTF-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  7. <title>打开后置摄像头</title>
  8. <style>
  9. body { text-align: center; padding-top: 50px; }
  10. button { font-size: 18px; padding: 12px 24px; margin: 10px; }
  11. video { width: 80%; max-width: 500px; border: 1px solid #ccc; margin-top: 20px; background: #222; }
  12. </style>
  13. </head>
  14. <body>
  15. <h2>后置摄像头预览</h2>
  16. <video id="video" autoplay playsinline></video>
  17. <br>
  18. <button id="onBtn">打开后置摄像头</button>
  19. <button id="offBtn" disabled>关闭摄像头</button>
  20. <script>
  21. let currentStream = null;
  22. const video = document.getElementById('video');
  23. const onBtn = document.getElementById('onBtn');
  24. const offBtn = document.getElementById('offBtn');
  25. // 遍历设备,获取第一个后置摄像头的 deviceId
  26. async function getFirstBackCameraId() {
  27. const devices = await navigator.mediaDevices.enumerateDevices();
  28. const videoDevices = devices.filter(d => d.kind === 'videoinput');
  29. const back = videoDevices.find(d => {
  30. const label = d.label.toLowerCase();
  31. return label.includes('back') || label.includes('rear') || label.includes('后置');
  32. });
  33. return back ? back.deviceId : (videoDevices[0] ? videoDevices[0].deviceId : null);
  34. }
  35. async function openCamera() {
  36. try {
  37. if (currentStream) {
  38. currentStream.getTracks().forEach(t => t.stop());
  39. currentStream = null;
  40. }
  41. // 通过deviceId来强选第一个后置摄像头
  42. const deviceId = await getFirstBackCameraId();
  43. if (!deviceId) {
  44. alert('未找到摄像头');
  45. return;
  46. }
  47. const stream = await navigator.mediaDevices.getUserMedia({
  48. video: { deviceId: { exact: deviceId } },
  49. audio: false
  50. });
  51. video.srcObject = stream;
  52. currentStream = stream;
  53. onBtn.disabled = true;
  54. offBtn.disabled = false;
  55. console.info('后置摄像头已打开');
  56. } catch (err) {
  57. console.error('打开摄像头失败:', err);
  58. alert('无法打开摄像头,请检查权限或 HTTPS 环境。');
  59. }
  60. }
  61. function closeCamera() {
  62. if (currentStream) {
  63. currentStream.getTracks().forEach(t => t.stop());
  64. currentStream = null;
  65. }
  66. video.srcObject = null;
  67. onBtn.disabled = false;
  68. offBtn.disabled = true;
  69. console.info('摄像头已关闭');
  70. }
  71. onBtn.addEventListener('click', openCamera);
  72. offBtn.addEventListener('click', closeCamera);
  73. window.addEventListener('beforeunload', () => {
  74. if (currentStream) {
  75. currentStream.getTracks().forEach(t => t.stop());
  76. }
  77. });
  78. </script>
  79. </body>
  80. </html>