91 lines
2.3 KiB
Vue
91 lines
2.3 KiB
Vue
<template>
|
|
<view class="container">
|
|
<button @click="startRecord">开始录音</button>
|
|
<button @click="stopRecord">停止录音</button>
|
|
<view class="tip">{{ status }}</view>
|
|
</view>
|
|
</template>
|
|
|
|
<script>
|
|
export default {
|
|
data() {
|
|
return {
|
|
status: "未录音",
|
|
recorder: null, // 录音实例
|
|
recordTimer: null, // 定时读取定时器
|
|
};
|
|
},
|
|
onUnload() {
|
|
// 页面卸载清理资源
|
|
this.stopRecord();
|
|
},
|
|
methods: {
|
|
// 申请录音权限
|
|
async applyRecordPermission() {
|
|
const res = await uni.requestPermissions({ scope: "scope.record" });
|
|
return res[0].grantStatus === 1; // 1 表示授权成功
|
|
},
|
|
// 开始录音
|
|
async startRecord() {
|
|
// 权限校验
|
|
const hasPermission = await this.applyRecordPermission();
|
|
if (!hasPermission) {
|
|
this.status = "未授权录音权限,请在设置中开启";
|
|
return;
|
|
}
|
|
|
|
// 初始化录音实例(WAV格式,含PCM原始数据)
|
|
this.recorder = plus.audio.createRecorder({
|
|
format: "wav",
|
|
sampleRate: 16000, // 常用采样率,可按需调整
|
|
numberOfChannels: 1, // 单声道
|
|
bitRate: 128000
|
|
});
|
|
|
|
// 启动录音
|
|
this.recorder.start();
|
|
this.status = "录音中...";
|
|
|
|
// 200ms 定时读取录音数据并打印
|
|
this.recordTimer = setInterval(() => {
|
|
try {
|
|
const audioData = this.recorder.getRecordedData();
|
|
if (audioData && audioData.buffer) {
|
|
// 打印关键信息:数据长度、数据类型
|
|
console.log("当前录音数据长度(字节):", audioData.buffer.byteLength);
|
|
console.log("录音数据类型:", Object.prototype.toString.call(audioData.buffer));
|
|
}
|
|
} catch (e) {
|
|
console.error("读取录音数据异常:", e);
|
|
}
|
|
}, 200);
|
|
},
|
|
// 停止录音
|
|
stopRecord() {
|
|
if (this.recorder) {
|
|
this.recorder.stop();
|
|
this.recorder = null;
|
|
}
|
|
if (this.recordTimer) {
|
|
clearInterval(this.recordTimer);
|
|
this.recordTimer = null;
|
|
}
|
|
this.status = "录音已停止";
|
|
}
|
|
}
|
|
};
|
|
</script>
|
|
|
|
<style scoped>
|
|
.container {
|
|
padding: 20rpx;
|
|
display: flex;
|
|
flex-direction: column;
|
|
gap: 30rpx;
|
|
}
|
|
.tip {
|
|
margin-top: 20rpx;
|
|
color: #666;
|
|
font-size: 28rpx;
|
|
}
|
|
</style> |