| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739 |
- <template>
- <Theme>
- <view class="record-page">
- <!-- 页面标题 -->
- <view class="page-title">录音留言</view>
- <!-- 录音区域 -->
- <view class="record-section">
- <view
- class="record-area"
- :class="{ recording: isRecording }"
- @click="toggleRecord"
- >
- <view class="record-icon">
- <i class="icon-font icon-microphone"></i>
- </view>
- <view class="record-text">
- {{ isRecording ? "录音中..." : "点击开始录音" }}
- </view>
- </view>
- </view>
- <!-- 录音文件显示区域 -->
- <view class="audio-display" v-if="voicePath">
- <view class="audio-waveform">
- <view
- class="wave-bar"
- v-for="(bar, index) in displayWaveBars"
- :key="index"
- :style="{ height: bar + 'px' }"
- ></view>
- </view>
- <view class="audio-duration">{{ formatTime(recordTime) }}</view>
- <view class="audio-controls">
- <view
- class="control-btn play-btn"
- :class="{ playing: isPlaying }"
- @click="togglePlay"
- >
- <i
- class="icon-font"
- :class="isPlaying ? 'icon-pause' : 'icon-play'"
- ></i>
- </view>
- <view class="control-btn delete-btn" @click="deleteRecord">
- <i class="icon-font icon-delete"></i>
- </view>
- </view>
- </view>
- <!-- 空状态 -->
- <view class="empty-state" v-else>
- <view class="empty-text">暂无录音</view>
- </view>
- </view>
- <Tabbar page="index" />
- </Theme>
- </template>
- <script setup>
- import { ref, onMounted, onUnmounted } from "vue";
- import Theme from "@/components/Theme.vue";
- import Tabbar from "@/components/tabbar.vue";
- import { onShow } from "@dcloudio/uni-app";
- // 录音状态
- const isRecording = ref(false);
- const recordTime = ref(0);
- const recordTimer = ref(null);
- const voicePath = ref("");
- // 播放状态
- const isPlaying = ref(false);
- let audioContext = null;
- // 录音管理器
- let recorderManager = null;
- // 平台检测
- const platform = ref(uni.getSystemInfoSync().platform);
- const isH5 = ref(process.env.UNI_PLATFORM === "h5");
- const isApp = ref(process.env.UNI_PLATFORM === "app-plus");
- // 录音时的波形动画
- const waveBars = ref([]);
- // 显示时的静态波形
- const displayWaveBars = ref([]);
- // 开始录音
- const startRecord = () => {
- // 检查平台支持
- if (isH5.value) {
- // H5平台使用Web API
- startH5Record();
- } else {
- startAppRecord();
- }
- };
- // H5录音功能
- const startH5Record = () => {
- // 检查浏览器支持
- // if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
- // uni.showToast({
- // title: "浏览器不支持录音功能",
- // icon: "none",
- // });
- // return;
- // }
- navigator.mediaDevices
- .getUserMedia({ audio: true })
- .then((stream) => {
- // 创建MediaRecorder
- const mediaRecorder = new MediaRecorder(stream);
- const audioChunks = [];
- mediaRecorder.ondataavailable = (event) => {
- audioChunks.push(event.data);
- };
- mediaRecorder.onstop = () => {
- const audioBlob = new Blob(audioChunks, { type: "audio/wav" });
- const audioUrl = URL.createObjectURL(audioBlob);
- // 停止所有音频轨道
- stream.getTracks().forEach((track) => track.stop());
- // 保存录音文件
- saveRecordFile({
- tempFilePath: audioUrl,
- fileSize: audioBlob.size,
- });
- };
- mediaRecorder.onerror = (err) => {
- console.error("H5录音错误", err);
- isRecording.value = false;
- stopRecordTimer();
- stopWaveAnimation();
- uni.showToast({
- title: "录音失败",
- icon: "none",
- });
- };
- // 开始录音
- mediaRecorder.start();
- isRecording.value = true;
- startRecordTimer();
- startWaveAnimation();
- // 保存MediaRecorder引用用于停止
- recorderManager = mediaRecorder;
- })
- .catch((error) => {
- console.error("H5录音权限错误", error);
- uni.showToast({
- title: "需要录音权限",
- icon: "none",
- });
- });
- };
- // APP录音功能
- const startAppRecord = () => {
- try {
- recorderManager = uni.getRecorderManager();
- recorderManager.onStart(() => {
- console.log("录音开始");
- isRecording.value = true;
- startRecordTimer();
- startWaveAnimation();
- });
- recorderManager.onStop((res) => {
- console.log("录音结束", res);
- isRecording.value = false;
- stopRecordTimer();
- stopWaveAnimation();
- saveRecordFile(res);
- });
- recorderManager.onError((err) => {
- console.error("录音错误", err);
- isRecording.value = false;
- stopRecordTimer();
- stopWaveAnimation();
- uni.showToast({
- title: "录音失败",
- icon: "none",
- });
- });
- const options = {
- duration: 60000,
- sampleRate: 16000,
- numberOfChannels: 1,
- encodeBitRate: 96000,
- format: "mp3",
- frameSize: 50,
- };
- recorderManager.start(options);
- } catch (error) {
- console.error("录音初始化失败", error);
- uni.showToast({
- title: "录音初始化失败",
- icon: "none",
- });
- }
- };
- // 停止录音
- const stopRecord = () => {
- if (recorderManager) {
- if (isH5.value) {
- // H5平台停止MediaRecorder
- recorderManager.stop();
- } else if (isApp.value) {
- // APP平台停止uni.getRecorderManager
- recorderManager.stop();
- }
- }
- };
- // 切换录音状态
- const toggleRecord = () => {
- if (isRecording.value) {
- stopRecord();
- } else {
- startRecord();
- }
- };
- // 录音计时器
- const startRecordTimer = () => {
- recordTime.value = 0;
- recordTimer.value = setInterval(() => {
- recordTime.value++;
- }, 1000);
- };
- const stopRecordTimer = () => {
- if (recordTimer.value) {
- clearInterval(recordTimer.value);
- recordTimer.value = null;
- }
- };
- // 波形动画
- const startWaveAnimation = () => {
- const animateWave = () => {
- if (isRecording.value) {
- // 创建更真实的波浪效果
- waveBars.value = Array.from({ length: 25 }, (_, index) => {
- // 使用正弦波创建更自然的波浪
- const time = Date.now() / 100;
- const frequency = 0.1 + (index % 3) * 0.05; // 不同频率
- const amplitude = 30 + Math.random() * 20; // 随机振幅
- const baseHeight = 20;
- return (
- baseHeight +
- Math.abs(Math.sin(time * frequency + index * 0.5)) * amplitude
- );
- });
- setTimeout(animateWave, 150);
- }
- };
- animateWave();
- };
- const stopWaveAnimation = () => {
- waveBars.value = [];
- };
- // 生成静态波形显示
- const generateDisplayWave = () => {
- // 根据录音时长生成静态波形
- const duration = recordTime.value;
- const waveCount = Math.min(30, Math.max(15, duration * 2)); // 根据时长调整波形数量
- displayWaveBars.value = Array.from({ length: waveCount }, (_, index) => {
- // 使用录音时长作为种子,生成固定的波形
- const seed = duration + index;
- const amplitude = 20 + (seed % 40); // 20-60的振幅
- const baseHeight = 15;
- return baseHeight + amplitude;
- });
- };
- // 保存录音文件
- const saveRecordFile = (res) => {
- voicePath.value = res.tempFilePath;
- // 生成静态波形显示
- generateDisplayWave();
- // 保存到本地存储
- uni.setStorageSync("voicePath", voicePath.value);
- uni.setStorageSync("recordTime", recordTime.value);
- uni.showToast({
- title: "录音保存成功",
- icon: "success",
- });
- };
- // 播放录音
- const togglePlay = () => {
- if (isPlaying.value) {
- // 停止播放
- stopPlay();
- } else {
- // 开始播放
- startPlay();
- }
- };
- // 开始播放
- const startPlay = () => {
- if (!voicePath.value) {
- uni.showToast({
- title: "没有录音文件",
- icon: "none",
- });
- return;
- }
- if (isH5.value) {
- // H5平台使用HTML5 Audio
- startH5Play();
- } else if (isApp.value) {
- // APP平台使用uni.createInnerAudioContext
- startAppPlay();
- } else {
- uni.showToast({
- title: "当前平台不支持播放功能",
- icon: "none",
- });
- }
- };
- // H5播放功能
- const startH5Play = () => {
- if (audioContext) {
- audioContext.pause();
- audioContext = null;
- }
- try {
- audioContext = new Audio(voicePath.value);
- audioContext.onplay = () => {
- isPlaying.value = true;
- };
- audioContext.onended = () => {
- isPlaying.value = false;
- };
- audioContext.onerror = (err) => {
- console.error("H5播放错误", err);
- isPlaying.value = false;
- uni.showToast({
- title: "播放失败",
- icon: "none",
- });
- };
- audioContext.play();
- } catch (error) {
- console.error("H5播放初始化失败", error);
- uni.showToast({
- title: "播放功能不支持",
- icon: "none",
- });
- }
- };
- // APP播放功能
- const startAppPlay = () => {
- if (audioContext) {
- audioContext.destroy();
- }
- try {
- audioContext = uni.createInnerAudioContext();
- audioContext.src = voicePath.value;
- audioContext.onPlay(() => {
- isPlaying.value = true;
- });
- audioContext.onEnded(() => {
- isPlaying.value = false;
- });
- audioContext.onError((err) => {
- console.error("APP播放错误", err);
- isPlaying.value = false;
- uni.showToast({
- title: "播放失败",
- icon: "none",
- });
- });
- audioContext.play();
- } catch (error) {
- console.error("APP播放初始化失败", error);
- uni.showToast({
- title: "播放功能不支持",
- icon: "none",
- });
- }
- };
- // 停止播放
- const stopPlay = () => {
- if (audioContext) {
- if (isH5.value) {
- // H5平台停止Audio
- audioContext.pause();
- audioContext = null;
- } else if (isApp.value) {
- // APP平台停止uni.createInnerAudioContext
- audioContext.stop();
- audioContext.destroy();
- audioContext = null;
- }
- }
- isPlaying.value = false;
- };
- // 删除录音
- const deleteRecord = () => {
- uni.showModal({
- title: "确认删除",
- content: "确定要删除这条录音吗?",
- success: (res) => {
- if (res.confirm) {
- // 如果正在播放,先停止
- if (isPlaying.value) {
- stopPlay();
- }
- // 删除录音文件
- if (voicePath.value) {
- if (isH5.value) {
- // H5平台释放Blob URL
- try {
- URL.revokeObjectURL(voicePath.value);
- console.log("H5文件URL释放成功");
- } catch (error) {
- console.error("H5文件URL释放失败", error);
- }
- } else if (isApp.value) {
- // APP平台删除文件
- try {
- uni.getFileSystemManager().unlink({
- filePath: voicePath.value,
- success: () => {
- console.log("文件删除成功");
- },
- fail: (err) => {
- console.error("文件删除失败", err);
- },
- });
- } catch (error) {
- console.error("文件删除异常", error);
- }
- }
- }
- // 清除录音数据
- voicePath.value = "";
- recordTime.value = 0;
- displayWaveBars.value = [];
- // 更新本地存储
- uni.removeStorageSync("voicePath");
- uni.removeStorageSync("recordTime");
- uni.showToast({
- title: "删除成功",
- icon: "success",
- });
- }
- },
- });
- };
- // 格式化时间
- const formatTime = (seconds) => {
- const mins = Math.floor(seconds / 60);
- const secs = seconds % 60;
- return `${mins.toString().padStart(2, "0")}:${secs
- .toString()
- .padStart(2, "0")}`;
- };
- // 提交表单
- const submitForm = () => {
- if (!voicePath.value) {
- uni.showToast({
- title: "请先录制语音",
- icon: "none",
- });
- return;
- }
- // 这里可以调用后台接口提交表单数据
- const formData = {
- voiceFile: voicePath.value, // 录音文件路径
- voiceDuration: recordTime.value, // 录音时长
- // 其他表单字段...
- };
- console.log("提交表单数据:", formData);
- uni.showToast({
- title: "表单提交成功",
- icon: "success",
- });
- // 实际项目中这里应该调用API
- // uni.request({
- // url: 'your-api-url',
- // method: 'POST',
- // data: formData,
- // success: (res) => {
- // Toast("提交成功");
- // },
- // fail: (err) => {
- // Toast("提交失败");
- // }
- // });
- };
- // 加载录音
- const loadRecord = () => {
- try {
- const savedVoicePath = uni.getStorageSync("voicePath");
- const savedRecordTime = uni.getStorageSync("recordTime");
- if (savedVoicePath) {
- voicePath.value = savedVoicePath;
- recordTime.value = savedRecordTime || 0;
- generateDisplayWave();
- }
- } catch (error) {
- console.error("加载录音失败", error);
- }
- };
- onMounted(() => {
- loadRecord();
- });
- onUnmounted(() => {
- // 清理资源
- stopRecordTimer();
- stopPlay();
- });
- onShow(() => {
- // 页面显示时重新加载录音
- loadRecord();
- });
- </script>
- <style lang="less" scoped>
- .record-page {
- min-height: 100vh;
- background: #f5f5f5;
- padding: 20px;
- padding-bottom: 120rpx;
- .page-title {
- font-size: 18px;
- font-weight: bold;
- color: #000;
- margin-bottom: 20px;
- }
- .record-section {
- margin-bottom: 20px;
- .record-area {
- background: #fff;
- border: 2px solid #007aff;
- border-radius: 12px;
- padding: 20px;
- display: flex;
- align-items: center;
- cursor: pointer;
- transition: all 0.3s ease;
- &.recording {
- border-color: #ff3b30;
- background: #fff5f5;
- }
- .record-icon {
- width: 24px;
- height: 24px;
- margin-right: 12px;
- display: flex;
- align-items: center;
- justify-content: center;
- .icon-font {
- font-size: 24px;
- color: #999;
- }
- }
- .record-text {
- font-size: 16px;
- color: #999;
- flex: 1;
- }
- }
- }
- .audio-display {
- background: #fff;
- border: 1px solid #e0e0e0;
- border-radius: 12px;
- padding: 16px;
- display: flex;
- align-items: center;
- gap: 12px;
- .audio-waveform {
- flex: 1;
- display: flex;
- align-items: center;
- gap: 2px;
- height: 40px;
- .wave-bar {
- width: 3px;
- background: #000;
- border-radius: 1.5px;
- min-height: 4px;
- }
- }
- .audio-duration {
- font-size: 16px;
- color: #000;
- font-weight: 500;
- min-width: 50px;
- text-align: center;
- }
- .audio-controls {
- display: flex;
- gap: 8px;
- .control-btn {
- width: 32px;
- height: 32px;
- border-radius: 50%;
- display: flex;
- align-items: center;
- justify-content: center;
- cursor: pointer;
- transition: all 0.2s ease;
- &.play-btn {
- background: #000;
- &.playing {
- background: #ff3b30;
- }
- .icon-font {
- font-size: 14px;
- color: #fff;
- }
- }
- &.delete-btn {
- background: #ff3b30;
- .icon-font {
- font-size: 14px;
- color: #fff;
- }
- }
- &:active {
- transform: scale(0.95);
- }
- }
- }
- }
- .empty-state {
- background: #fff;
- border: 1px solid #e0e0e0;
- border-radius: 12px;
- padding: 40px 20px;
- text-align: center;
- .empty-text {
- font-size: 16px;
- color: #999;
- }
- }
- }
- // 录音时的脉冲动画
- @keyframes pulse {
- 0% {
- transform: scale(1);
- opacity: 1;
- }
- 50% {
- transform: scale(1.05);
- opacity: 0.8;
- }
- 100% {
- transform: scale(1);
- opacity: 1;
- }
- }
- .recording {
- animation: pulse 1.5s infinite;
- }
- </style>
|