?主要是用setTimeout函数控制结束,还要考虑this指代的作用域
wxml文件
<!--index.wxml-->
<view class='camera'>
<image src="/images/border.png" mode="widthFix"></image>
<camera wx:if="{{isAuth}}" device-position="front" flash="off" binderror="error"></camera>
</view>
<button class="takePhoto" type="primary" bindtap="startShootVideo">录像</button>
wxss文件
/**index.wxss**/
.camera {
width: 430rpx;
height: 430rpx;
border-radius: 50%;
margin: 20px auto 0;
position: relative;
}
.camera image {
position: absolute;
width: 100%;
height: 100%;
z-index: 10;
}
.camera camera {
width: 430rpx;
height: 430rpx;
}
button.takePhoto:not([size='mini']) {
position: fixed;
bottom: 0;
left: 0;
width: 100vw;
height: 90rpx;
border-radius: 0;
}
js文件
// index.js
// 获取应用实例
const app = getApp()
Page({
data: {
isAuth: false,
src: ''
},
onLoad() {
const _this = this
wx.getSetting({
success: res => {
if (res.authSetting['scope.camera']) {
// 用户已经授权
_this.setData({
isAuth: true
})
} else {
// 用户还没有授权,向用户发起授权请求
wx.authorize({
scope: 'scope.camera',
success() { // 用户同意授权
_this.setData({
isAuth: true
})
},
fail() { // 用户不同意授权
_this.openSetting().then(res => {
_this.setData({
isAuth: true
})
})
}
})
}
},
fail: res => {
console.log('获取用户授权信息失败')
}
})
},
// 打开授权设置界面
openSetting() {
const _this = this
let promise = new Promise((resolve, reject) => {
wx.showModal({
title: '授权',
content: '请先授权获取摄像头权限',
success(res) {
if (res.confirm) {
wx.openSetting({
success(res) {
if (res.authSetting['scope.camera']) { // 用户打开了授权开关
resolve(true)
} else { // 用户没有打开授权开关, 继续打开设置页面
_this.openSetting().then(res => {
resolve(true)
})
}
},
fail(res) {
console.log(res)
}
})
} else if (res.cancel) {
_this.openSetting().then(res => {
resolve(true)
})
}
}
})
})
return promise;
},
takePhoto() {
const ctx = wx.createCameraContext()
ctx.takePhoto({
quality: 'high',
success: (res) => {
this.setData({
src: res.tempImagePath
})
console.log(res.tempImagePath)
wx.previewImage({
current: res.tempImagePath, // 当前显示图片的http链接
urls: [res.tempImagePath] // 需要预览的图片http链接列表
})
}
})
},
startShootVideo() {
this.setData({
videoSrc: ''
})
console.log("========= 开始录像 ===========")
this.ctx = wx.createCameraContext();
let that = this
this.ctx.startRecord({
timeoutCallback: () => {
},
success: (res) => {
setTimeout(()=>{
this.ctx.stopRecord({
compressed: true, //压缩视频
success: (res) => {
this.setData({
videoSrc: res.tempVideoPath
})
console.log("========= 结束录像 ===========")
console.log(res.tempVideoPath)
}
});
},5000)
},
fail() {
wx.showToast({
title: '录像失败',
icon: 'none',
duration:4000
})
console.log("========= 调用开始录像失败 ===========")
}
})
},
})
还附带了一个拍照函数,换到网页上就能用。
纳闷怎么没人写微信小程序定时录像的帖子,Debug了好久~
|