1. 給開發者的 Web 技術文件
  2. Web API
  3. MediaDevices

此頁面由社群從英文翻譯而來。了解更多並加入 MDN Web Docs 社群。

View in English Always switch to English

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.

媒體捕獲和串流 APIMediaDevices 介面提供了存取已連接媒體輸入裝置(如攝影機、麥克風)以及螢幕共享的功能。本質上,它讓你能夠存取任何媒體資料的硬體來源。

EventTarget MediaDevices

實例屬性

繼承其父介面 EventTarget 的屬性。

實例方法

繼承其父介面 EventTarget 的方法。

enumerateDevices()

取得包含系統可用媒體輸入與輸出裝置資訊的陣列。

getSupportedConstraints()

回傳一個符合 MediaTrackSupportedConstraints 的物件,指出 MediaStreamTrack 介面支援哪些可約束屬性。參見媒體串流 API 以了解更多關於約束及其用法。

getDisplayMedia()

提示使用者選擇顯示器或顯示器的部分區域(例如視窗),以擷取為用於共享或錄製目的的 MediaStream。回傳一個兌現為 MediaStream 的 promise。

getUserMedia()

在經由提示取得使用者權限後,開啟系統上的攝影機及/或麥克風,並提供一個包含視訊軌及/或音訊軌輸入的 MediaStream

selectAudioOutput()

提示使用者選擇特定的音訊輸出裝置。

事件

devicechange

在媒體輸入或輸出裝置連接到使用者的電腦或從中移除時被觸發。

範例

js
// 將變數放在全域作用域,以便在瀏覽器主控台中使用。
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

瀏覽器相容性

參見

Help improve MDN

Learn how to contribute

This page was last modified on by MDN contributors.

AltStyle によって変換されたページ (->オリジナル) /