項(xiàng)目中,需要客戶(hù)錄制一段視頻,上傳到服務(wù)器,找了很久,終于實(shí)現(xiàn)了這個(gè)功能。微信小程序有兩種方式可以實(shí)現(xiàn)錄制視頻。
1.使用相機(jī)的CameraContext.startRecord
2.使用官方API:wx.chooseVideo
方法一
wxml
<view class="video">
<camera wx:if="{{videoSrc.length === 0}}" device-position="font" flash="off" binderror="error" style="width: {{cameraWidth}}px;height: 442rpx;">
</camera>
<video style="width: {{cameraWidth}}px; height: 442rpx;" wx:else src="{{videoSrc}}" controls></video>
</view>
<view class="btn" id='btn-photo' bindtouchstart="handleTouchStart" bindtouchend="handleTouchEnd" bindlongpress="handleLongPress">按住錄制</view>
js部分代碼
onLoad: function (options) {
//調(diào)用設(shè)置相機(jī)大小的方法
this.setCameraSize();
this.ctx = wx.createCameraContext();
},
/**
* 獲取系統(tǒng)信息 設(shè)置相機(jī)的大小適應(yīng)屏幕
*/
setCameraSize() {
//獲取設(shè)備信息
const res = wx.getSystemInfoSync();
//獲取屏幕的可使用寬高,設(shè)置給相機(jī)
this.setData({
cameraHeight: res.windowHeight,
cameraWidth: res.windowWidth
})
console.log(res)
},
/**
* 開(kāi)始錄像的方法
*/
startShootVideo() {
this.setData({
videoSrc: ''
})
console.log("========= 調(diào)用開(kāi)始錄像 ===========")
let that = this
this.ctx.startRecord({
timeoutCallback: () => {
},
success: (res) => {
},
fail() {
wx.showToast({
title: '錄像失敗',
icon: 'none',
duration:4000
})
console.log("========= 調(diào)用開(kāi)始錄像失敗 ===========")
}
})
},
/**
* 結(jié)束錄像
*/
stopShootVideo() {
wx.hideLoading();
// console.log("========= 調(diào)用結(jié)束錄像 ===========")
this.ctx.stopRecord({
compressed: true, //壓縮視頻
success: (res) => {
console.log(res)
this.setData({
videoSrc: res.tempVideoPath
})
},
fail() {
wx.showToast({
title: '錄像失敗',
icon: 'none',
duration:4000
})
console.log("========= 調(diào)用結(jié)束錄像失敗 ===========")
}
})
},
//touch start 手指觸摸開(kāi)始
handleTouchStart: function (e) {
this.setData({
startTime: e.timeStamp
})
},
//touch end 手指觸摸結(jié)束
handleTouchEnd: function (e) {
// wx.hideLoading();
let endTime = e.timeStamp;
//判斷是點(diǎn)擊還是長(zhǎng)按 點(diǎn)擊不做任何事件,長(zhǎng)按 觸發(fā)結(jié)束錄像
if (endTime - this.data.startTime > 350) {
//長(zhǎng)按操作 調(diào)用結(jié)束錄像方法
this.stopShootVideo();
} else {
this.setData({
textFlag: ''
})
}
},
/**
* 長(zhǎng)按按鈕進(jìn)行錄像
*/
handleLongPress: function (e) {
// 長(zhǎng)按方法觸發(fā),調(diào)用開(kāi)始錄像方法
this.startShootVideo();
},
注:由于官方限制,只能錄制30秒。
方法二
在js中
wx.chooseVideo({
sourceType: ['album','camera'],
maxDuration: 60,
camera: 'back',
success(res) {
console.log(res.tempFilePath)
}
})
使用wx.chooseVideo拍攝視頻或從手機(jī)相冊(cè)中選視頻,拍攝界面不能自定義。
如果有什么不清楚的地方,歡迎私信哦.
具體參數(shù)說(shuō)明請(qǐng)參考官方文檔
https://developers.weixin.qq.com/miniprogram/dev/api/media/video/wx.chooseVideo.html(鏈接地址)