使用 Azure 通訊服務 UI 連結庫要求相機和麥克風存取
重要
此 Azure 通訊服務功能目前處於預覽狀態。
提供的預覽 API 和 SDK 並無服務等級協定。 建議您不要將其用於生產工作負載。 部分功能可能不受支援,或是在功能上有所限制。
如需詳細資訊,請參閱 Microsoft Azure 預覽版增補使用規定。
本教學課程是接續三部分的通話整備教學課程,並遵循先前的指示: 確定使用者位於支援的瀏覽器上。
下載程式碼
在 GitHub 上存取本教學課程的完整程式碼。
要求存取相機和麥克風
對於呼叫應用程式,使用者通常必須授與使用麥克風和相機的權限。 在本節中,我們會建立一系列元件,鼓勵使用者授與相機和麥克風的存取權。 我們會向使用者顯示提示,引導他們透過授與存取權。 如果未授與存取權,我們會提示使用者。
建立相機和麥克風存取的提示
我們先建立一系列裝置權限提示,讓使用者進入他們接受麥克風和相機權限的狀態。 這些提示會從 UI 連結庫使用 CameraAndMicrophoneSitePermissions
元件。 如同不支援的瀏覽器提示,我們會在 FluentUI modal
內裝載這些提示。
src/DevicePermissionPrompts.tsx
import { CameraAndMicrophoneSitePermissions } from '@azure/communication-react';
import { Modal } from '@fluentui/react';
/** Modal dialog that prompt the user to accept the Browser's device permission request. */
export const AcceptDevicePermissionRequestPrompt = (props: { isOpen: boolean }): JSX.Element => (
<PermissionsModal isOpen={props.isOpen} kind="request" />
);
/** Modal dialog that informs the user we are checking for device access. */
export const CheckingDeviceAccessPrompt = (props: { isOpen: boolean }): JSX.Element => (
<PermissionsModal isOpen={props.isOpen} kind="check" />
)
/** Modal dialog that informs the user they denied permission to the camera or microphone with corrective steps. */
export const PermissionsDeniedPrompt = (props: { isOpen: boolean }): JSX.Element => (
<PermissionsModal isOpen={props.isOpen} kind="denied" />
);
/** Base component utilized by the above prompts for better code separation. */
const PermissionsModal = (props: { isOpen: boolean, kind: "denied" | "request" | "check" }): JSX.Element => (
<Modal isOpen={props.isOpen}>
<CameraAndMicrophoneSitePermissions
appName={'this site'}
kind={props.kind}
onTroubleshootingClick={() => alert('This callback should be used to take the user to further troubleshooting')}
/>
</Modal>
);
檢查相機和麥克風存取
在這裡,我們新增了兩個新的公用程式函式,以檢查和要求相機和麥克風存取。 使用兩個函式建立名為 devicePermissionUtils.ts
的檔案,checkDevicePermissionsState
和 requestCameraAndMicrophonePermissions
。
checkDevicePermissionsState
使用 PermissionAPI。 不過,Firefox 不支援查詢相機和麥克風,因此我們可確保此方法在此案例中傳回 unknown
。 稍後我們會確保我們會在提示使用者提供權限時處理 unknown
案例。
src/DevicePermissionUtils.ts
import { DeviceAccess } from "@azure/communication-calling";
import { StatefulCallClient } from "@azure/communication-react";
/**
* Check if the user needs to be prompted for camera and microphone permissions.
*
* @remarks
* The Permissions API we are using is not supported in Firefox, Android WebView or Safari < 16.
* In those cases this returns 'unknown'.
*/
export const checkDevicePermissionsState = async (): Promise<{camera: PermissionState, microphone: PermissionState} | 'unknown'> => {
try {
const [micPermissions, cameraPermissions] = await Promise.all([
navigator.permissions.query({ name: "microphone" as PermissionName }),
navigator.permissions.query({ name: "camera" as PermissionName })
]);
console.info('PermissionAPI results', [micPermissions, cameraPermissions]); // view console logs in the browser to see what the PermissionsAPI info is returned
return { camera: cameraPermissions.state, microphone: micPermissions.state };
} catch (e) {
console.warn("Permissions API unsupported", e);
return 'unknown';
}
}
/** Use the DeviceManager to request for permissions to access the camera and microphone. */
export const requestCameraAndMicrophonePermissions = async (callClient: StatefulCallClient): Promise<DeviceAccess> => {
const response = await (await callClient.getDeviceManager()).askDevicePermission({ audio: true, video: true });
console.info('AskDevicePermission response', response); // view console logs in the browser to see what device access info is returned
return response
}
提示使用者授與相機和麥克風的存取權
現在我們有提示並檢查和要求邏輯,我們會建立 DeviceAccessComponent
來提示使用者有關裝置權限。
在此元件中,我們會根據裝置權限狀態向使用者顯示不同的提示:
- 如果裝置權限狀態未知,我們會向使用者顯示提示,告知我們正在檢查裝置權限。
- 如果我們要求權限,我們會向使用者顯示提示,鼓勵他們接受權限要求。
- 如果權限遭到拒絕,我們會向使用者顯示提示,告知他們他們已拒絕權限,而且他們需要授與權限才能繼續。
src/DeviceAccessChecksComponent.tsx
import { useEffect, useState } from 'react';
import { CheckingDeviceAccessPrompt, PermissionsDeniedPrompt, AcceptDevicePermissionRequestPrompt } from './DevicePermissionPrompts';
import { useCallClient } from '@azure/communication-react';
import { checkDevicePermissionsState, requestCameraAndMicrophonePermissions } from './DevicePermissionUtils';
export type DevicesAccessChecksState = 'runningDeviceAccessChecks' |
'checkingDeviceAccess' |
'promptingForDeviceAccess' |
'deniedDeviceAccess';
/**
* This component is a demo of how to use the StatefulCallClient with CallReadiness Components to get a user
* ready to join a call.
* This component checks the browser support and if camera and microphone permissions have been granted.
*/
export const DeviceAccessChecksComponent = (props: {
/**
* Callback triggered when the tests are complete and successful
*/
onTestsSuccessful: () => void
}): JSX.Element => {
const [currentCheckState, setCurrentCheckState] = useState<DevicesAccessChecksState>('runningDeviceAccessChecks');
// Run call readiness checks when component mounts
const callClient = useCallClient();
useEffect(() => {
const runDeviceAccessChecks = async (): Promise<void> => {
// First we check if we need to prompt the user for camera and microphone permissions.
// The prompt check only works if the browser supports the PermissionAPI for querying camera and microphone.
// In the event that is not supported, we show a more generic prompt to the user.
const devicePermissionState = await checkDevicePermissionsState();
if (devicePermissionState === 'unknown') {
// We don't know if we need to request camera and microphone permissions, so we'll show a generic prompt.
setCurrentCheckState('checkingDeviceAccess');
} else if (devicePermissionState.camera === 'prompt' || devicePermissionState.microphone === 'prompt') {
// We know we need to request camera and microphone permissions, so we'll show the prompt.
setCurrentCheckState('promptingForDeviceAccess');
}
// Now the user has an appropriate prompt, we can request camera and microphone permissions.
const devicePermissionsState = await requestCameraAndMicrophonePermissions(callClient);
if (!devicePermissionsState.audio || !devicePermissionsState.video) {
// If the user denied camera and microphone permissions, we prompt the user to take corrective action.
setCurrentCheckState('deniedDeviceAccess');
} else {
// Test finished successfully, trigger callback to parent component to take user to the next stage of the app.
props.onTestsSuccessful();
}
};
runDeviceAccessChecks();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<>
{/* We show this when we are prompting the user to accept device permissions */}
<AcceptDevicePermissionRequestPrompt isOpen={currentCheckState === 'promptingForDeviceAccess'} />
{/* We show this when the PermissionsAPI is not supported and we are checking what permissions the user has granted or denied */}
<CheckingDeviceAccessPrompt isOpen={currentCheckState === 'checkingDeviceAccess'} />
{/* We show this when the user has failed to grant camera and microphone access */}
<PermissionsDeniedPrompt isOpen={currentCheckState === 'deniedDeviceAccess'} />
</>
);
}
完成建立此元件之後,我們會將它新增至 App.tsx
。 首先,新增匯入:
import { DeviceAccessChecksComponent } from './DeviceAccessChecksComponent';
然後將 TestingState
類型更新為下列值:
type TestingState = 'runningEnvironmentChecks' | 'runningDeviceAccessChecks' | 'finished';
最後,更新 App
元件:
/**
* Entry point of a React app.
*
* This shows a PreparingYourSession component while the CallReadinessChecks are running.
* Once the CallReadinessChecks are finished, the TestComplete component is shown.
*/
const App = (): JSX.Element => {
const [testState, setTestState] = useState<TestingState>('runningEnvironmentChecks');
return (
<FluentThemeProvider>
<CallClientProvider callClient={callClient}>
{/* Show a Preparing your session screen while running the environment checks */}
{testState === 'runningEnvironmentChecks' && (
<>
<PreparingYourSession />
<EnvironmentChecksComponent onTestsSuccessful={() => setTestState('runningDeviceAccessChecks')} />
</>
)}
{/* Show a Preparing your session screen while running the device access checks */}
{testState === 'runningDeviceAccessChecks' && (
<>
<PreparingYourSession />
<DeviceAccessChecksComponent onTestsSuccessful={() => setTestState('finished')} />
</>
)}
{/* After the device setup is complete, take the user to the call. For this sample we show a test complete page. */}
{testState === 'finished' && <TestComplete />}
</CallClientProvider>
</FluentThemeProvider>
);
}
應用程式會向使用者呈現提示,以引導他們完成裝置存取:
注意
若要進行測試,建議您在 InPrivate/Incognito 模式中瀏覽您的應用程式,讓相機和麥克風權限先前未獲授與 localhost:3000
。