+
88
-

回答

800_auto

通过uni.getRecorderManager()获取录音管理器

touchstart时开始录音

touchmove时检测手指上滑距离,超过50px显示取消提示

touchend时停止录音,根据是否上滑决定是保存还是取消

录音结束后可获取tempFilePath临时文件路径用于上传

点击查看完整代码

<template>
  <view class="container">
    <view 
      class="record-btn"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
      @touchcancel="handleTouchEnd"
    >
      {{ recordStatus }}
    </view>
    
    <!-- 上滑提示 -->
    <view class="cancel-tip" :class="{ show: isMovingUp }">
      松开手指,取消发送
    </view>
  </view>
</template>

<script>
const recorderManager = uni.getRecorderManager();

export default {
  data() {
    return {
      isRecording: false,
      startY: 0,
      moveY: 0,
      isMovingUp: false,
      recordStatus: '按住说话'
    }
  },
  
  onLoad() {
    // 监听录音结束事件
    recorderManager.onStop((res) => {
      if (!this.isMovingUp) {
        const { tempFilePath } = res;
        // 处理录音文件,比如上传服务器
        console.log('录音文件:', tempFilePath);
      }
    });
  },
  
  methods: {
    handleTouchStart(e) {
      this.startY = e.touches[0].clientY;
      this.isRecording = true;
      this.recordStatus = '松开结束,上滑取消';
      
      // 开始录音
      recorderManager.start({
        format: 'wav',
        duration: 60000, // 最长录音时间
        sampleRate: 16000,
        numberOfChannels: 1
      });
    },
    
    handleTouchMove(e) {
      if (!this.isRecording) return;
      
      this.moveY = e.touches[0].clientY;
      const moveDistance = this.startY - this.moveY;
      
      // 上滑超过50像素,显示取消提示
      if (moveDistance > 50) {
        this.isMovingUp = true;
        this.recordStatus = '松开取消';
      } else {
        this.isMovingUp = false;
        this.recordStatus = '松开结束';
      }
    },
    
    handleTouchEnd() {
      if (!this.isRecording) return;
      
      this.isRecording = false;
      this.recordStatus = '按住说话';
      
      // 停止录音
      recorderManager.stop();
      
      // 如果是上滑取消状态
      if (this.isMovingUp) {
        this.isMovingUp = false;
        // 可以在这里添加取消录音的提示
        uni.showToast({
          title: '已取消',
          icon: 'none'
        });
      }
    }
  }
}
</script>

<style>
.container {
  position: relative;
  padding: 20px;
}

.record-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  background-color: #f8f8f8;
  border-radius: 40rpx;
  margin: 10px auto;
}

.cancel-tip {
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: #fff;
  padding: 20rpx 30rpx;
  border-radius: 10rpx;
  display: none;
}

.cancel-tip.show {
  display: block;
}
</style>

网友回复

我知道答案,我要回答