h5操作媒体设备(音频和视频)
// 访问用户媒体设备的兼容方法
function getUserMedia(constraints, success, error){
if(navigator.mediaDevices.getUserMedia){
// 最新的标准API
navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error)
}else if(navigator.webkitGetUserMedia){
// Webkit 核心浏览器
navigator.webkitGetUserMedia(constraints, success, error)
}else if(navigator.mozGetUserMedia){
// Firefox 核心浏览器
navigator.mozGetUserMedia(constraints, success, error)
}else if(navigator.getUserMedia) {
// 旧版API
navigator.getUserMedia(constraints, success, error)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
constraints
: 请求指定的媒体类型,主要包含video
和audio
- 不带任何参数:
{video: true, audio: true}
- 指定视频分辨率:
{video: {width: 640, height: 320}}
- 移动设备上指定摄像头:前置
{video: {facingMode: 'user'}}
,后置{video: {facingMode: {exact: 'enviroment'}}}
- 不带任何参数:
success
: 成功回调函数,参数为MediaStream
对象,表示媒体内容的数据流,可以通过URL.createObjectURL
转换后设置给video
和audio
的src
属性,新版浏览器也可以直接赋值给srcObject
属性
案例
<video id="video" autoplay style="width: 480px;height: 320px;"></video>
<p>
<button onclick="onCapture()" class="btn btn-primary">拍照</button>
</p>
<canvas id="canvas" width="480" height="320"></canvas>
<script>
const video = document.getElementById('video')
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')
navigator.mediaDevices.getUserMedia({video: true, audio:true}).then(res => {
const CompatibleURL = window.URL || window.webkitURL
// video.src = CompatibleURL.createObjectURL(res)
video.srcObject = res // 新版浏览器不支持使用 createObjectURL 的形式,可以做兼容处理
video.play()
}).catch(e => {
alert(e.message)
})
function onCapture(){
ctx.drawImage(video, 0,0,480,320)
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
上次更新: 2023/09/22, 16:54:32