備忘錄_20160105(定位)
修改
回首頁
程式 2025-05-13 23:20:17 1747149617 100
用 js 抓出所有可用的多媒體裝置
用 js 抓出所有可用的多媒體裝置
●test.htm (要放在有 https 的地方)
<!doctype html>
<html lang="zh-Hant-TW">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=classDevice-width, initial-scale=1.0">
<title>裝置媒體裝置列舉</title>
<style>
body
{
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
button
{
padding: 10px 15px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover
{
background-color: #45a049;
}
.classDevice
{
padding: 10px;
margin: 5px 0;
background-color: #f5f5f5;
border-radius: 4px;
}
.classDeviceList
{
margin-top: 20px;
}
.classDeviceCategory
{
margin-bottom: 30px;
}
</style>
</head>
<body>
<h1>媒體裝置列舉</h1>
<p>此頁面將列出所有可用的攝影鏡頭和麥克風裝置。</p>
<button id="btnRefresh" onclick="funcEnumerateDevices();">重新整理裝置列表</button>
<div class="classDeviceList">
<div class="classDeviceCategory">
<h2>攝影鏡頭</h2>
<div id="divVideoInputDevices"></div>
</div>
<div class="classDeviceCategory">
<h2>麥克風</h2>
<div id="divAudioInputDevices"></div>
</div>
</div>
<script>
async function funcEnumerateDevices()
{
try
{
// 請求使用者權限(這會觸發瀏覽器的權限對話框)
await navigator.mediaDevices.getUserMedia({ audio: true, video: true });
// 列舉所有媒體裝置
const oDevices=await navigator.mediaDevices.enumerateDevices();
// 過濾並顯示攝影鏡頭
const oVideoInputDevices=oDevices.filter(oDevice => oDevice.kind==='videoinput');
funcDisplayDevices(oVideoInputDevices, 'divVideoInputDevices');
// 過濾並顯示麥克風
const oAudioInputDevices=oDevices.filter(oDevice => oDevice.kind==='audioinput');
funcDisplayDevices(oAudioInputDevices, 'divAudioInputDevices');
}
catch(oError)
{
console.error('列舉裝置時發生錯誤:', oError);
alert('列舉裝置時發生錯誤: ' + oError.message);
}
}
function funcDisplayDevices(oDevices, strElementId)
{
const oContainer=document.getElementById(strElementId);
oContainer.innerHTML='';
if(oDevices.length === 0)
{
oContainer.innerHTML='<div class="classDevice">未找到裝置</div>';
return;
}
oDevices.forEach(
oDevice =>
{
const oDeviceElement=document.createElement('div');
oDeviceElement.className='classDevice';
const strDeviceId=oDevice.deviceId || '無ID';
const strDeviceLabel=oDevice.label || '未命名裝置';
oDeviceElement.innerHTML
='<strong>名稱:</strong> '+strDeviceLabel+'<br>'
+'<strong>ID:</strong> '+strDeviceId+'<br>'
+'<strong>類型:</strong> '+oDevice.kind+'';
oContainer.appendChild(oDeviceElement);
}
);
}
</script>
</body>
</html>