uniapp app端如何使用live-pusher实现camera效果

<template>
	<view class="live-camera" :style="{ width: windowWidth, height: windowHeight }">
		<live-pusher 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: windowWidth, height: windowHeight }"
			v-if="!snapshotsrc"></live-pusher>
		<cover-image :src="snapshotsrc" class="live-camera" v-else
			:style="{ width: windowWidth, height: windowHeight }"></cover-image>
		<!-- <view class="menu"> -->
		<!--底部菜单区域背景-->
		<!-- <cover-image class="menu-mask" src="/static/live-camera/bar.png"></cover-image> -->

		<!--返回键-->
		<!-- <cover-image class="menu-back" @tap="back" src="/static/live-camera/back.png"></cover-image> -->

		<!--快门键-->
		<!-- <cover-image class="menu-snapshot" @tap="snapshot" src="/static/live-camera/shutter.png"></cover-image> -->

		<!--反转键-->
		<!-- <cover-image class="menu-flip" @tap="flip" src="/static/live-camera/flip.png"></cover-image> -->
		<!-- </view> -->
	</view>
</template>

<script>
	let _this = null;
	import indexConfig from '@/common/config/config.js'
	import http from '@/common/http.js'
	export default {
		data() {
			return {
				poenCarmeInterval: null, //打开相机的轮询
				aspect: '2:3', //比例
				windowWidth: '', //屏幕可用宽度
				windowHeight: '', //屏幕可用高度
				camerastate: false, //相机准备好了
				livePusher: null, //流视频对象
				snapshotsrc: null, //快照
				lastAcceleration: null,
				isMoving: false,
				timerId: null, // 用来存储setTimeout的返回值,以便于清除定时器
			};
		},
		onShow() {

		},
		onUnload() {
			// 页面关闭时执行的代码
			console.log('页面已经关闭');
			uni.stopAccelerometer();
			uni.offAccelerometerChange(this.accelerometerChangeHandler);
			// 在这里执行你需要的清理工作
		},
		onHide() {
			// 当页面隐藏时,停止监听加速度变化,避免不必要的资源消耗
			uni.stopAccelerometer();
			uni.offAccelerometerChange(this.accelerometerChangeHandler);
		},
		onLoad(e) {
			_this = this;
			this.initCamera();
			console.log(111111111)
		},
		onReady() {
			setTimeout(() => {
				this.livePusher = uni.createLivePusherContext('livePusher', this);
				console.log("this.livePusher", this.livePusher)
				this.startPreview(); //开启预览并设置摄像头
				this.poenCarme();

			}, 500)
			setTimeout(() => {
				// 开始监听加速度变化事件
				uni.startAccelerometer({
					interval: 'normal', // 或者使用'game'来获取更高频率的数据,但会更耗电
				});
				// 注册加速度变化事件的回调
				uni.onAccelerometerChange(this.accelerometerChangeHandler);
			}, 1000)


		},
		methods: {
			accelerometerChangeHandler(res) {
				// console.log("ressssx", res)
				// 获取当前加速度值
				const {
					x,
					y,
					z
				} = res;

				// 计算加速度的总变化量,可以根据实际情况调整阈值
				const acceleration = Math.sqrt(x * x + y * y + z * z);

				// 判断是否开始移动,这里只是一个简单的示例,实际应用中可能需要更复杂的判断逻辑
				const isCurrentlyMoving = acceleration > 10; // 假设加速度大于10即认为手机在动,具体阈值需要根据实际情况调整
				if (!isCurrentlyMoving) {
					this.timerId = setTimeout(() => {
						this.snapshot(); // 执行具体任务的函数
					}, 3000);
				}
				// 防止频繁切换状态,可以添加一个简单的防抖逻辑
				if (isCurrentlyMoving !== this.isMoving) {
					clearTimeout(this.timerId);
					this.isMoving = isCurrentlyMoving;
					if (this.isMoving) {
						console.log('手机在动!');
						// 在这里执行手机在动时需要的操作
					} else {
						console.log('手机静止!');
						// 在这里执行手机静止时需要的操作
						setTimeout(() => {
							this.snapshot()
						}, 1000)
					}
				}
			},
			error(e) {
				console.log("error:" + JSON.stringify(e));
			},
			//轮询打开
			poenCarme() {
				//#ifdef APP-PLUS
				if (plus.os.name == 'Android') {
					this.poenCarmeInterval = setInterval(function() {
						// console.log(_this.camerastate);
						if (!_this.camerastate) _this.startPreview();
					}, 2500);
				}
				//#endif
			},
			//初始化相机
			initCamera() {
				uni.getSystemInfo({
					success: function(res) {
						// console.log("res",res)
						_this.windowWidth = res.windowWidth;
						_this.windowHeight = res.windowHeight;
						let zcs = _this.aliquot(_this.windowWidth, _this.windowHeight);
						_this.aspect = (_this.windowWidth / zcs) + ':' + (_this.windowHeight / zcs);
						// console.log('画面比例:' + _this.aspect);
					}
				});
			},

			//整除数计算
			aliquot(x, y) {
				if (x % y == 0) return y;
				return this.aliquot(y, x % y);
			},

			//开始预览
			startPreview() {
				// console.log('this.livePusher.startPreview',this.livePusher.startPreview)
				this.livePusher.startPreview({
					success: a => {
						// console.log("zzzzzzzzzzzzz", a)
					},
					fail: err => {
						// console.log("errerr", err)
					}
				});
			},

			//停止预览
			stopPreview() {
				this.livePusher.stopPreview({
					success: a => {
						_this.camerastate = false; //标记相机未启动
					}
				});
			},

			//状态
			statechange(e) {
				//状态改变
				// console.log(e);
				// console.log("statechange:" + JSON.stringify(e));
				if (e.detail.code == 1007) {
					_this.camerastate = true;
				} else if (e.detail.code == -1301) {
					_this.camerastate = false;
				}
			},


			//返回
			back() {
				uni.navigateBack();
			},

			//抓拍
			snapshot() {
				uni.stopAccelerometer();
				uni.offAccelerometerChange(this.accelerometerChangeHandler);
				//震动
				// uni.vibrateShort({
				// 	success: function() {
				// 		// console.log('success');
				// 	}
				// });
				//拍照
				this.livePusher.snapshot({
					success: e => {
						// _this.snapshotsrc = e.message.tempImagePath;
						console.log("_this.snapshotsrc_this.snapshotsrc", _this.snapshotsrc)
						this.chooseImg(e.message.tempImagePath)
						uni.showLoading({
							title: '识别中'
						});
						_this.stopPreview();
						// _this.setImage();
						// uni.navigateBack();
					}
				});
			},
			chooseImg(e) {

				console.log("e", e)
				uni.uploadFile({
					url: indexConfig.baseUrl + 'upfile/image', //仅为示例,非真实的接口地址
					// url: this.$indexConfig.baseUrl + 'upfile/clockin',
					filePath: e,
					header: {
						token: this.$store.state.token
					},
					name: 'file',
					success: (uploadFileRes) => {
						console.log("zzzzzzzzzz", JSON.parse(uploadFileRes.data))
						let data = JSON.parse(uploadFileRes.data)
						_this.snapshotsrc = data.data.show;
						console.log("zxzzzzz", _this.snapshotsrc)
						this.wasteDiscern(data.data.path)
					}
				});
			},
			wasteDiscern(img) {
				uni.request({
					url: indexConfig.baseUrl + 'publics/waste/discern',
					method: 'GET',
					data: {
						image: img
					},
					success: res => {
						console.log("cxzczczx", res.data)
						setTimeout(() => {
							uni.hideLoading()
							uni.redirectTo({
								url: '/pages/home/identify?data=' + JSON.stringify(res.data
									.data)
							})
						}, 2000)
					}
				})
				// 	http('publics/waste/discern', {
				// 		image: img
				// 	}, "GET").then(res => {
				// 		console.log("res", res)

				// 		setTimeout(() => {
				// 			uni.hideLoading()
				// 			uni.navigateTo({
				// 				url: '/pages/home/identify?data=' + JSON.stringify(res.data)
				// 			})
				// 		}, 2000)
				// 		this.camera.stop();
				// 		this.camera = null;
				// 	})
			},
			//反转
			flip() {
				this.livePusher.switchCamera();
			},

			//设置
			// setImage() {
			// 	let pages = getCurrentPages();
			// 	let prevPage = pages[pages.length - 2]; //上一个页面

			// 	//直接调用上一个页面的setImage()方法,把数据存到上一个页面中去
			// 	prevPage.$vm.setImage({
			// 		path: _this.snapshotsrc
			// 	});
			// }
		}
	};
</script>

<style lang="scss">
	.live-camera {
		justify-content: center;
		align-items: center;

		.menu {
			position: absolute;
			left: 0;
			bottom: 50px;
			width: 750rpx;
			height: 180rpx;
			z-index: 98;
			align-items: center;
			justify-content: center;

			.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: 130rpx;
				height: 130rpx;
				z-index: 99;
			}

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

有什么更好的方法,欢迎讨论,谢谢大家 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值