3***@qq.com
3***@qq.com
  • 发布:2023-05-22 18:29
  • 更新:2023-05-22 18:29
  • 阅读:822

onReady中调用uni.createLivePusherContext("livePusher", this),获取不到livePusher

分类:HBuilderX

在onReady中使用live-pusher的官方this.livePusher = uni.createLivePusherContext("livePusher", this)写法
ios下可以唤醒相机,但是调用预览、快照等功能无效

<template> <view class="live-camera" :style="{ width: ${windowWidth}px, height: ${windowHeight}px }"> <view class="preview" :style="{ width: ${windowWidth}px, height:${windowHeight - 90 }px }"> <!-- #ifdef APP-PLUS --> <live-pusher v-if="showLive" id="livePusher" ref="livePusher" class="livePusher" mode="FHD" beauty="0" whiteness="0" :aspect="aspect" min-bitrate="1000" audio-quality="16KHz" device-position="back" auto-focus="true" :muted="true" :enable-camera="true" :enable-mic="false" :zoom="false" @statechange="statechange" @error="error" style="{ width: ${cameraWidth }px, height: ${windowHeight - 90 }px}"> <cover-view class="outline-box" :style="{ width: ${windowWidth }px, height: ${windowHeight - 90}px}">
<cover-image class="outline-img"
src="../../../../static/icon/idcard.png"></cover-image>
</cover-view>
</live-pusher>
<!-- #endif -->
<!-- #ifdef MP -->
<camera :style="{ width: ${cameraWidth }px, height: ${windowHeight - 90 }px }" device-position="devicePosition"></camera> <!-- #endif -->
<!--辅助线-->
<cover-view class="outline-box" :style="{ width: ${windowWidth }px, height: ${windowHeight - 90}px}">
<cover-image class="outline-img"
src="../../../../static/icon/idcard.png"></cover-image>
</cover-view>
</view>
<view class="menu flex-row flex-around w">
<!--底部菜单区域背景-->
<!-- <cover-image class="menu-mask" src="../../../../static/icon/tabBar/background.png"></cover-image> -->
<!--返回键-->
<cover-image class="menu-back" @tap="back" src="../../../../static/icon/goback_wite.png"></cover-image>
<!--快门键-->
<cover-image class="menu-snapshot" @tap="snapshot" src="../../../../static/icon/scan.png"></cover-image>
<!--反转键-->
<cover-image class="menu-flip" @tap="flip" src="../../../../static/icon/goback_wite.png"></cover-image>
</view>
<canvas-crop ref="crop"></canvas-crop>
</view>
</template>

<script>
import {judgeiosPermission,requestandroidPermission,gotoAppPermissionSetting} from "@/utils/permission.js"
import {uploadFile} from '@/utils/oss.js'

export default {  
    data() {  
        return {  
            devicePosition: "back", //前置或后置摄像头,值为front, back  
            poenCarmeInterval: null, //打开相机的轮询  
            dotype: 'idcardface', //操作类型  
            message: '', //提示  
            aspect: '2:3', //比例  
            cameraWidth: '', //相机画面宽度  
            cameraHeight: '', //相机画面宽度  
            windowWidth: '', //屏幕可用宽度  
            windowHeight: '', //屏幕可用高度  
            camerastate: false, //相机准备好了  
            livePusher: null, //流视频对象  
            snapshotsrc: null, //快照  
            type: null,  
            showLive: false, //安卓机需要先判断权限有没有授权  
            imageInfo: {}, //取景框内的图片大小  
            context: {}, //canvas实例对象  
            rpx2px: "",  
            finder: { //取景框尺寸,驾驶证、行驶证为333*999,其他为640*980  
                width: 640,  
                height: 980  
            },  
        };  
    },  
    onLoad(e) {  
        this.type = e.type  
        if (["2", "3"].indexOf(this.type) > -1) this.finder = {  
            width: 333,  
            height: 999  
        }  
    },  
    async onReady() {  
        this.initCamera();  
        // #ifdef APP-PLUS  
        if (plus.os.name === "Android") {  
            await this.checkAndriodCamera()  
        } else {  
            this.showLive = true  
        }  
        this.showLive ? this.$nextTick(()=> {  
            this.livePusher = uni.createLivePusherContext("livePusher", this)  
        }) : ""  
        if (plus.os.name === "iOS") {  
            setTimeout(()=>{  
                //开启预览并设置摄像头  
                console.log('ios开启预览')  
                this.startPreview();  
            }, 500)  
        }  
        // #endif  
        // #ifdef MP  
        this.showLive = true  
        if (!await this.checkCamera()) {  
            return  
        }  
        // #endif  
    },  
    methods: {  

        //初始化相机  
        initCamera() {  
            //处理安卓手机异步授权问题  
            uni.getSystemInfo({  
                success: (res) => {  
                    console.log("手机信息", res)  
                    this.windowWidth = res.windowWidth;  
                    this.windowHeight = res.windowHeight;  
                    this.cameraWidth = res.windowWidth;  
                    this.cameraHeight = res.windowWidth * 1.5;  
                    this.rpx2px = 1 / 750 * res.windowWidth;  
                    let imgW = parseInt(this.finder.width * this.rpx2px),  
                        imgH = parseInt(this.finder.height * this.rpx2px) // 640和980是css里定义取景框的rpx宽度  
                    this.imageInfo = {  
                        width: imgW,  
                        height: imgH  
                    }  
                }  
            });  
        },  

        //检查安卓相机权限  
        async checkAndriodCamera() {  
            let androidPermisson = await requestAndroidPermission("android.permission.CAMERA")  
            if (androidPermisson === 1) {  
                this.showLive = true  
                this.$nextTick(() => {  
                    this.livePusher = uni.createLivePusherContext('livePusher', this);  
                })  
                setTimeout(() => {  
                    //开启预览并设置摄像头  
                    this.startPreview();  
                    this.poenCarme()  
                }, 100)  
            } else {  
                uni.showModal({  
                    content: "请打开摄像头授权功能!",  
                    showCancel: false,  
                    success: (res) => {  
                        if (res.confirm) gotoAppPermissionSetting()  
                    }  
                })  
            }  
            console.log("checkAndriodCamera", androidPermisson)  
        },  

        //检查照相机权限  
        checkCamera() {  
            return new Promise(async (resolve) => {  
                // #ifdef APP-PLUS  
                if ((plus.os.name === "iOS" && !judgeIosPermission("camera"))) {  
                    uni.showModal({  
                        content: "请打开摄像头授权功能!",  
                        showCancel: false,  
                        success: (res) => {  
                            if (res.confirm) gotoAppPermissionSetting()  
                        }  
                    })  
                    resolve(false)  
                } else if (plus.os.name === "Android") {  
                    let androidPermisson = await requestAndroidPermission("android.permission.CAMERA")  
                    console.log(androidPermisson)  
                    if (androidPermisson < 1) {  
                        uni.showModal({  
                            content: "请打开摄像头授权功能!",  
                            showCancel: false  
                        })  
                        resolve(false)  
                    } else {  
                        resolve(true)  
                    }  
                } else {  
                    resolve(true)  
                }  
                // #endif  
                // #ifdef MP  
                uni.getSetting({  
                    success: (sRes) => {  
                        console.log(sRes)  
                        if (sRes.authSetting["scope.camera"] === false) {  
                            uni.showModal({  
                                content: "请打开摄像头授权功能!",  
                                showCancel: false  
                            })  
                            resolve(false)  
                        } else {  
                            resolve(true)  
                        }  
                    },  
                    fail: (err) => {  
                        console.log(err)  
                    }  
                })  
                // #endif  
            })  
        },  
        //轮询打开  
        async poenCarme() {  
            //#ifdef APP-PLUS  
            if (plus.os.name == 'Android') {  
                this.poenCarmeInterval = setInterval(() => {  
                    if (!this.camerastate) this.startPreview();  
                }, 1000);  
            }  
            //#endif  
        },  

        //开始预览  
        startPreview() {  
            this.livePusher.startPreview({  
                success: async (a) => {  
                    console.log(a,'开始预览')  
                    //直播推流默认是前置摄像头,预览成功后给转成后置摄像头  
                    if (plus.os.name == "iOS") {  
                        this.livePusher.switchCamera();  
                        this.camerastate = true;  
                    }  
                }  
            });  
        },  
        error(e) {  
            clearInterval(this.poenCarmeInterval)  
            console.log("error:" + JSON.stringify(e));  
            if (e.detail.errCode === 10001) {  
                uni.showModal({  
                    content: "请打开摄像头授权功能!",  
                    showCancel: false,  
                    success: (res) => {  
                        if (res.confirm) gotoAppPermissionSetting()  
                    }  
                })  
            }  
        },  
        //停止预览  
        stopPreview() {  
            this.livePusher.stopPreview({  
                success: a => {  
                    this.camerastate = false; //标记相机未启动  
                }  
            });  
        },  

        //状态  
        statechange(e) {  
            //状态改变  
            console.log(e);  
            if (e.detail.code == 1003 || e.detail.code == 1007) { //1007  
                this.camerastate = true;  
            } else if (e.detail.code == -1301) {  
                this.checkCamera()  
                this.camerastate = false;  
            }  
        },  
        //返回  
        back() {  
            console.log('返回了')  
            uni.navigateBack();  
        },  

        /**  
         * 抓拍,因为APP端用的gcanvas,gcanvas.drawImage不允许临时图片,所以要先传一次图片  
         * **/  
        snapshot() {  
            console.log('抓拍')  
            if (!this.checkCamera()) {  
                console.log('quanx')  
                return false  
            }  
            //震动  
            // uni.vibrateShort();  
            // #ifdef APP-PLUS  
            console.log('抓拍1')  
            this.livePusher.snapshot({  
                success: async e => {  
                    console.log(e,'eepath')  
                    this.uploadImage(`file://${e.message.tempImagePath}`)  
                },  
                fail: err => {  
                    console.log(err)  
                }  
            });  
            // #endif  
            // #ifdef MP  
            const ctx = uni.createCameraContext();  
            ctx.takePhoto({  
                quality: 'high',  
                success: (res) => {  
                    this.uploadImage(res.tempImagePath)  
                }  
            });  
            // #endif  
        },  
        /**  
         * 获取临时路径的图片宽高大小  
         * **/  
        getImageInfo(path) {  
            return new Promise((resolve, reject) => {  
                uni.getImageInfo({  
                    src: path,  
                    success: (res) => {  
                        resolve(res)  
                    },  
                    fail: (err) => {  
                        reject(err)  
                        resolve(err)  
                    }  
                })  
            })  
        },  
        async uploadImage(path) {  
            let info = await this.getImageInfo(path) //获取临时路径的图片宽高大小  
            let width = Math.round(this.rpx2px * this.finder.width / this.cameraWidth * info.width),  
                height = Math.round(this.rpx2px * this.finder.height / (this.windowHeight - 90) * info.height)  
            let x = parseInt((info.width - width) / 2),  
                y = parseInt((info.height - height) / 2)  
            uploadFile(path).then(res => {  
                this.snapshotsrc = res.url +  
                    `?x-oss-process=image/crop,x_${x},y_${y},w_${width},h_${height}/rotate,270`  
                console.log(this.snapshotsrc)  
                // this.setImage({  
                //  x,  
                //  y,  
                //  width,  
                //  height  
                // });  

                // uni.navigateBack({  
                //  delta: 2  
                // })  
                uni.navigateBack()  
            }).catch(err => {  
                console.log(err)  
                // errorMsg(err)  
            })  
        },  

        //反转  
        flip() {  
            // #ifdef APP-PLUS  
            this.livePusher.switchCamera();  
            // #endif  
            // #ifdef MP  
            this.devicePosition = this.devicePosition === 'back' ? 'front' : 'back'  
            // #endif  
        },  

        //设置  
        setImage(x, y, width, height) {  
            let pages = getCurrentPages();  
            let prevPage = pages[pages.length - 3]; //上二个页面  
            //直接调用上二个页面的setImage()方法,把数据存到上二个页面中去  
            prevPage.$vm.setImage({  
                path: this.snapshotsrc,  
                type: this.type  
            });  
        }  
    }  
};  

</script>

<style lang="scss">
.live-camera {
.preview {
justify-content: center;
align-items: center;
position: relative;
z-index: 1;

        .canvas {  
            visibility: hidden;  
            position: absolute;  
            top: 0;  
            z-index: -1;  
        }  

        .gcanvas {  
            z-index: -1;  
            position: absolute;  
        }  

        .outline-box {  
            position: absolute;  
            top: 0;  
            left: 0;  
            bottom: 0;  
            z-index: 99;  
            align-items: center;  
            justify-content: center;  
            display: flex;  

            .outline-img {  
                // width: 640rpx;  
                // height: 980rpx;  
                width: 90vw;  
                height: 440rpx;  
                z-index: 999;  
            }  

            .outline-img1 {  
                width: 333rpx;  
                height: 999rpx;  
            }  
        }  

        .remind {  
            position: absolute;  
            left: -106px;  
            top: 880rpx;  
            width: 750rpx;  
            z-index: 100;  
            transform: rotate(90deg);  
            align-items: center;  
            justify-content: center;  
            color: #FFFFFF;  

            .remind-text {  
                color: #FFFFFF;  
                font-weight: bold;  
            }  
        }  
    }  

    .menu {  
        position: absolute;  
        left: 0;  
        bottom: 0;  
        width: 750rpx;  
        height: 100px;  
        z-index: 98;  
        align-items: center;  
        justify-content: center;  
        background-color: #000;  
        border-radius: 0;  
        box-sizing: inherit;   

        .menu-mask {  
            position: absolute;  
            left: 0;  
            bottom: 0;  
            width: 750rpx;  
            height: 180rpx;  
            z-index: 98;  
        }  

        .menu-back {  
            position: absolute;  
            left: 30rpx;  
            bottom: 50rpx;  
            width: 80rpx;  
            height: 80rpx;  
            z-index: 99;  
            align-items: center;  
            justify-content: center;  
        }  

        .menu-snapshot {  
            width: 100rpx;  
            height: 100rpx;  
            z-index: 99;  
        }  

        .menu-flip {  
            position: absolute;  
            right: 30rpx;  
            bottom: 50rpx;  
            width: 80rpx;  
            height: 80rpx;  
            z-index: 99;  
            align-items: center;  
            justify-content: center;  
        }  
    }  
}  

.back {  
    width: 88rpx;  
    height: 88rpx;  
    margin-left: 20rpx;  
    margin-top: env(safe-area-inset-top);  
    position: absolute;  
    top: 0;  
    left: 0;  
}  

</style>

2023-05-22 18:29 负责人:无 分享
已邀请:

要回复问题请先登录注册