此頁面由社群從英文翻譯而來。了解更多並加入 MDN Web Docs 社群。
MediaDevices
Baseline
Widely available
*
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2017年9月.
* Some parts of this feature may have varying levels of support.
Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.
媒體捕獲和串流 API 的 MediaDevices 介面提供了存取已連接媒體輸入裝置(如攝影機、麥克風)以及螢幕共享的功能。本質上,它讓你能夠存取任何媒體資料的硬體來源。
實例屬性
繼承其父介面 EventTarget 的屬性。
實例方法
繼承其父介面 EventTarget 的方法。
enumerateDevices()-
取得包含系統可用媒體輸入與輸出裝置資訊的陣列。
getSupportedConstraints()-
回傳一個符合
MediaTrackSupportedConstraints的物件,指出MediaStreamTrack介面支援哪些可約束屬性。參見媒體串流 API 以了解更多關於約束及其用法。 getDisplayMedia()-
提示使用者選擇顯示器或顯示器的部分區域(例如視窗),以擷取為用於共享或錄製目的的
MediaStream。回傳一個兌現為MediaStream的 promise。 getUserMedia()-
在經由提示取得使用者權限後,開啟系統上的攝影機及/或麥克風,並提供一個包含視訊軌及/或音訊軌輸入的
MediaStream。 selectAudioOutput()-
提示使用者選擇特定的音訊輸出裝置。
事件
devicechange-
在媒體輸入或輸出裝置連接到使用者的電腦或從中移除時被觸發。
範例
// 將變數放在全域作用域,以便在瀏覽器主控台中使用。
const video = document.querySelector("video");
const constraints = {
audio: false,
video: true,
};
navigator.mediaDevices
.getUserMedia(constraints)
.then((stream) => {
const videoTracks = stream.getVideoTracks();
console.log("取得符合約束的串流:", constraints);
console.log(`使用視訊裝置:${videoTracks[0].label}`);
stream.onremovetrack = () => {
console.log("串流已結束");
};
video.srcObject = stream;
})
.catch((error) => {
if (error.name === "OverconstrainedError") {
console.error(
`你的裝置不支援解析度 ${constraints.video.width.exact}x${constraints.video.height.exact} px。`,
);
} else if (error.name === "NotAllowedError") {
console.error("你需要授予此頁面存取攝影機與麥克風的權限。");
} else {
console.error(`getUserMedia 錯誤:${error.name}`, error);
}
});
規範
| Specification |
|---|
| Media Capture and Streams> # mediadevices> |
瀏覽器相容性
Enable JavaScript to view this browser compatibility table.
參見
- 媒體捕獲和串流 API:此介面所屬的 API。
- 螢幕捕獲 API:定義了
getDisplayMedia()方法的 API。 - WebRTC API
Navigator.mediaDevices:回傳可用於存取裝置之MediaDevices物件的參照。- CameraCaptureJS:使用
MediaDevices與媒體串流錄製 API 進行 HTML 視訊擷取與播放。 - OpenLang:使用
MediaDevices與媒體串流錄製 API 進行視訊錄製的 HTML 視訊語言實驗室 Web 應用程式。