微信小程序多媒体功能实现

摄像头功能实现

可以通过 <camera> 组件实现摄像头预览和拍照功能,以下是相关代码示例及说明:

Page({
  data: {
    devicePosition: 'back', // 初始使用后置摄像头
    flash: 'off', // 闪光灯默认关闭
    photoPath: '' // 照片路径
  },
  
  onLoad() {
    // 检查摄像头权限
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.camera']) {
          // 申请摄像头权限
          wx.authorize({
            scope: 'scope.camera',
            success: () => {
              console.log('摄像头权限已获取');
            },
            fail: () => {
              wx.showToast({
                title: '请授予摄像头权限',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  },
  
  // 切换摄像头
  switchCamera() {
    this.setData({
      devicePosition: this.data.devicePosition === 'back'? 'front' : 'back'
    });
  },
  
  // 切换闪光灯
  toggleFlash() {
    this.setData({
      flash: this.data.flash === 'on'? 'off' : 'on'
    });
  },
  
  // 拍照
  takePhoto() {
    const ctx = wx.createCameraContext();
    ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        this.setData({
          photoPath: res.tempImagePath
        });
      },
      fail: (err) => {
        console.error('拍照失败', err);
        wx.showToast({
          title: '拍照失败',
          icon: 'none'
        });
      }
    });
  },
  
  // 保存图片到相册
  savePhoto() {
    wx.saveImageToPhotosAlbum({
      filePath: this.data.photoPath,
      success: () => {
        wx.showToast({
          title: '保存成功'
        });
      },
      fail: (err) => {
        console.error('保存失败', err);
        wx.showToast({
          title: '保存失败',
          icon: 'none'
        });
      }
    });
  },
  
  // 摄像头错误处理
  onCameraError(e) {
    console.error('摄像头错误', e.detail);
    wx.showToast({
      title: '摄像头打开失败',
      icon: 'none'
    });
  }
});
    

录音功能实现

使用 wx.getRecorderManager() 实现录音功能,代码示例及说明如下:

Page({
  data: {
    isRecording: false,
    recordPath: '',
    recordDuration: 0,
    timer: null
  },
  
  onLoad() {
    // 获取录音管理器
    this.recorderManager = wx.getRecorderManager();
    
    // 监听录音结束
    this.recorderManager.onStop((res) => {
      this.setData({
        recordPath: res.tempFilePath,
        isRecording: false
      });
      clearInterval(this.data.timer);
    });
    
    // 监听录音错误
    this.recorderManager.onError((err) => {
      console.error('录音错误', err);
      wx.showToast({
        title: '录音失败',
        icon: 'none'
      });
    });
  },
  
  // 开始录音
  startRecord() {
    // 检查录音权限
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.record']) {
          wx.authorize({
            scope: 'scope.record',
            success: () => {
              this.startRecording();
            },
            fail: () => {
              wx.showToast({
                title: '请授予录音权限',
                icon: 'none'
              });
            }
          });
        } else {
          this.startRecording();
        }
      }
    });
  },
  
  // 实际开始录音
  startRecording() {
    // 配置录音参数
    const options = {
      duration: 60000, // 最长录音时间,单位ms
      sampleRate: 44100,
      numberOfChannels: 1,
      encodeBitRate: 192000,
      format: 'mp3',
      frameSize: 50
    };
    
    this.recorderManager.start(options);
    
    this.setData({
      isRecording: true,
      recordDuration: 0,
      timer: setInterval(() => {
        this.setData({
          recordDuration: this.data.recordDuration + 1
        });
      }, 1000)
    });
  },
  
  // 停止录音
  stopRecord() {
    this.recorderManager.stop();
  },
  
  // 保存录音
  saveRecord() {
    wx.saveVideoToPhotosAlbum({
      filePath: this.data.recordPath,
      success: () => {
        wx.showToast({
          title: '保存成功'
        });
      },
      fail: (err) => {
        console.error('保存失败', err);
        wx.showToast({
          title: '保存失败',
          icon: 'none'
      });
      }
    });
  },
  
  onUnload() {
    // 页面卸载时清理定时器
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
  }
});
    

视频拍摄功能实现

结合 <camera> 组件和 wx.createCameraContext() 实现视频拍摄,相关代码如下:

Page({
  data: {
    isRecording: false,
    videoPath: ''
  },
  
  onLoad() {
    this.cameraContext = wx.createCameraContext();
  },
  
  // 开始拍摄视频
  startVideo() {
    // 检查摄像头和录音权限
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.camera'] ||!res.authSetting['scope.record']) {
          wx.authorize({
            scope: ['scope.camera', 'scope.record'],
            success: () => {
              this.startRecordingVideo();
            },
            fail: () => {
              wx.showToast({
                title: '请授予摄像头和录音权限',
                icon: 'none'
              });
            }
          });
        } else {
          this.startRecordingVideo();
        }
      }
    });
  },
  
  // 开始录制视频
  startRecordingVideo() {
    this.cameraContext.startRecord({
      success: () => {
        this.setData({
          isRecording: true
        });
        wx.showToast({
          title: '开始录制',
          icon: 'none'
      });
      },
      fail: (err) => {
        console.error('录制失败', err);
        wx.showToast({
          title: '录制失败',
          icon: 'none'
        });
      }
    });
  },
  
  // 停止拍摄视频
  stopVideo() {
    this.cameraContext.stopRecord({
      success: (res) => {
        this.setData({
          videoPath: res.tempVideoPath,
          isRecording: false
        });
      },
      fail: (err) => {
        console.error('停止录制失败',
        err);
        wx.showToast({
          title: '停止录制失败',
          icon: 'none'
        });
      }
    });
  },
  
  // 保存视频到相册
  saveVideo() {
    wx.saveVideoToPhotosAlbum({
      filePath: this.data.videoPath,
      success: () => {
        wx.showToast({
          title: '保存成功'
        });
      },
      fail: (err) => {
        console.error('保存失败', err);
        wx.showToast({
          title: '保存失败',
          icon: 'none'
        });
      }
    });
  }
});
    

注意事项

权限处理

多媒体功能需要用户授权,必须在使用前检查并请求权限:

摄像头权限:scope.camera

录音权限:scope.record

保存到相册权限:scope.writePhotosAlbum

性能优化

不需要使用摄像头时及时关闭,减少资源消耗。

录制视频时注意控制时长,避免占用过多存储空间。

处理大文件时考虑分片上传。

兼容性

不同设备可能有不同的表现,做好异常处理。

使用 wx.canIUse 检查API兼容性。

用户体验

提供清晰的操作反馈。

处理各种异常情况并给出提示。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值