提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
本文是在使用uni-app开发安卓app时,做一个扫描抓拍进行人脸识别功能。
一、通过 uni-app 提供的 live-pusher 组件进行直播推流
注意:是 .nvue 文件,而不是 .vue 文件
<template>
<view>
<div style="width: 100%; height: 320px;">
<live-pusher id='livePusher' ref="livePusher" class="livePusher" url="" mode="FHD" :muted="true"
:enable-camera="true" :auto-focus="true" :beauty="1" whiteness="2" aspect="3:2" @statechange="statechange"
@netstatus="netstatus" @error="error"></live-pusher>
</div>
</view>
</template>
<script>
export default {
data() {
return {
snapshotInterval: null
}
},
onReady() {
// 注意:需要在onReady中 或 onLoad 延时
this.context = uni.createLivePusherContext("livePusher", this);
this.startPreview() // 开启摄像头
this.switchCamera() // 切换为后置摄像头
this.snapshotInterval = setInterval(() => {
this.snapshot();
}, 3000);
},
methods: {
/* 开启摄像头 */
startPreview: function() {
this.context.startPreview({
success: (a) => {
console.log("livePusher.startPreview:" + a);
}
});
},
/* 默认开启的是前置摄像头,根据需求决定是否调用摄像头切换方法 */
switchCamera: function() {
this.context.switchCamera({
success: (a) => {
console.log("livePusher.switchCamera:" + JSON.stringify(a));
}
});
},
/* 自动抓拍方法 */
snapshot: function() {
this.context.snapshot({
success: (e) => {
/* log输出抓拍的图片的路径 */
console.log(e.message.tempImagePath);
/* 抓拍成功后可以清除计时器 */
clearInterval(this.snapshotInterval)
/* 将抓拍的照片的路径传给人脸识别处理方法 */
this.scanFace()
}
});
},
/* 人脸识别方法 */
scanFace() {
/* 成功 */
// 跳转到对应页面
/* 失败,则重新创建计时器开始抓拍图片 */
that.snapshotInterval = setInterval(() => {
this.snapshot()
}, 3000)
}
}
}
</script>
二、以下代码为可运行代码
使用 HBuilder 创建一个空项目,把 pages 里的 index.vue 改为 index.nvue,其他的完全不用改,然后将下述代码替换进去即可运行。
可以参考 live-pusher
<template>
<view>
<div style="width: 100%; height: 320px;">
<live-pusher id='livePusher' ref="livePusher" class="livePusher" url="" mode="FHD" :muted="true"
:enable-camera="true" :auto-focus="true" :beauty="1" whiteness="2" aspect="3:2" @statechange="statechange"
@netstatus="netstatus" @error="error"></live-pusher>
</div>
</view>
</template>
<script>
export default {
data() {
return {
snapshotInterval: null
}
},
onReady() {
// 注意:需要在onReady中 或 onLoad 延时
this.context = uni.createLivePusherContext("livePusher", this);
this.startPreview() // 开启摄像头
this.switchCamera() // 切换为后置摄像头
this.snapshotInterval = setInterval(() => {
this.snapshot();
}, 3000);
},
methods: {
/* 开启摄像头 */
startPreview: function() {
this.context.startPreview({
success: (a) => {
console.log("livePusher.startPreview:" + a);
}
});
},
/* 默认开启的是前置摄像头,根据需求决定是否调用摄像头切换方法 */
switchCamera: function() {
this.context.switchCamera({
success: (a) => {
console.log("livePusher.switchCamera:" + JSON.stringify(a));
}
});
},
/* 自动抓拍方法 */
snapshot: function() {
this.context.snapshot({
success: (e) => {
/* log输出抓拍的图片的路径 */
console.log(e.message.tempImagePath);
/* 抓拍成功后可以清除计时器 */
clearInterval(this.snapshotInterval)
}
});
},
}
}
</script>