uniapp上传音频文件到服务器

视频教程地址:

【uniapp录音上传组件,将录音上传到django服务器】 https://www.bilibili.com/video/BV1wi4y1p7FL/?share_source=copy_web&vd_source=e66c0e33402a09ca7ae1f0ed3d5ecf7c

  • uniapp 录制音频文件上传到django服务器保存到服务器 ,要求uniapp显示录制进度波形图 请提供完整代码
  • 以下是一个示例代码,演示了如何在uniapp中录制音频文件并将其上传到Django服务器,并在uniapp中显示录制进度波形图。

    在uniapp的页面中,你可以使用uni-voice组件来录制音频,并使用uni-upload组件来上传文件。在Django服务器端,你可以使用Django的文件上传功能来保存音频文件。

    uniapp页面代码(index.vue):

<template>
  <view class="container">
    <view class="waveform" :style="{ width: waveformWidth + 'px' }"></view>
    <view class="controls">
      <button @tap="startRecording" :disabled="isRecording">开始录制</button>
      <button @tap="stopRecording" :disabled="!isRecording">停止录制</button>
      <button @tap="uploadFile" :disabled="!recordedFile">上传文件</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isRecording: false,
      recordedFile: null,
      waveformWidth: 0,
      audioContext: null,
      audioRecorder: null,
      audioChunks: [],
    };
  },
  mounted() {
    this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
  },
  methods: {
    startRecording() {
      this.isRecording = true;
      this.audioChunks = [];
      navigator.mediaDevices.getUserMedia({ audio: true })
        .then((stream) => {
          this.audioRecorder = new MediaRecorder(stream);
          this.audioRecorder.addEventListener('dataavailable', (event) => {
            this.audioChunks.push(event.data);
            this.drawWaveform();
          });
          this.audioRecorder.start();
        })
        .catch((error) => {
          console.error('Error accessing microphone:', error);
        });
    },
    stopRecording() {
      this.isRecording = false;
      this.audioRecorder.stop();
      this.audioRecorder.stream.getTracks().forEach((track) => track.stop());
      this.audioRecorder = null;
      this.recordedFile = new File(this.audioChunks, 'recorded_audio.wav', { type: 'audio/wav' });
    },
    drawWaveform() {
      const waveformElement = this.$refs.waveform;
      const canvas = waveformElement.getContext('2d');
      const width = waveformElement.width;
      const height = waveformElement.height;
      const data = new Uint8Array(this.audioChunks.reduce((acc, chunk) => acc + chunk.byteLength, 0));
      let offset = 0;
      this.audioChunks.forEach((chunk) => {
        const reader = new FileReader();
        reader.onload = () => {
          const array = new Uint8Array(reader.result);
          data.set(array, offset);
          offset += array.length;
          canvas.clearRect(0, 0, width, height);
          canvas.fillStyle = '#000000';
          for (let i = 0; i < width; i++) {
            const value = data[Math.floor(i * (data.length / width))];
            const barHeight = (value / 255) * height;
            canvas.fillRect(i, height - barHeight, 1, barHeight);
          }
        };
        reader.readAsArrayBuffer(chunk);
      });
    },
    uploadFile() {
      const formData = new FormData();
      formData.append('audio', this.recordedFile);
      uni.uploadFile({
        url: 'http://your-django-server/upload/',
        filePath: this.recordedFile.path,
        name: 'audio',
        formData: formData,
        success: (res) => {
          console.log('File uploaded:', res);
        },
        fail: (error) => {
          console.error('Error uploading file:', error);
        },
      });
    },
  },
};
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

.waveform {
  width: 300px;
  height: 100px;
  background-color: #f0f0f0;
}

.controls {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

button {
  margin: 0 10px;
}
</style>

在Django服务器端,你需要设置一个视图函数来处理文件上传请求,并将音频文件保存到服务器上的某个目录中。以下是一个简单的示例代码:


  
  • from django.http import JsonResponse
    
    def upload_file(request):
        if request.method == 'POST' and request.FILES.get('audio'):
            audio_file = request.FILES['audio']
            with open('path/to/save/audio.wav', 'wb') as f:
                for chunk in audio_file.chunks():
                    f.write(chunk)
            return JsonResponse({'success': True})
        return JsonResponse({'success': False, 'message': 'Invalid request'})
    

    请将上述代码保存为一个Django视图函数,并将其添加到你的Django项目的URL配置中。

    注意:上述代码仅为示例,你可能需要根据你的具体需求进行适当的修改和调整。

  • 要保存文mp3文件
  • 如果你想保存音频文件为MP3格式,你可以使用lamejs库来将录制的音频文件转换为MP3格式。以下是修改后的示例代码:

    uniapp页面代码(index.vue):

<template>
  <view class="container">
    <view class="waveform" :style="{ width: waveformWidth + 'px' }"></view>
    <view class="controls">
      <button @tap="startRecording" :disabled="isRecording">开始录制</button>
      <button @tap="stopRecording" :disabled="!isRecording">停止录制</button>
      <button @tap="convertToMp3" :disabled="!recordedFile">转换为MP3</button>
      <button @tap="uploadFile" :disabled="!mp3File">上传文件</button>
    </view>
  </view>
</template>

<script>
import lamejs from 'lamejs';

export default {
  data() {
    return {
      isRecording: false,
      recordedFile: null,
      mp3File: null,
      waveformWidth: 0,
      audioContext: null,
      audioRecorder: null,
      audioChunks: [],
    };
  },
  mounted() {
    this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
  },
  methods: {
    startRecording() {
      this.isRecording = true;
      this.audioChunks = [];
      navigator.mediaDevices.getUserMedia({ audio: true })
        .then((stream) => {
          this.audioRecorder = new MediaRecorder(stream);
          this.audioRecorder.addEventListener('dataavailable', (event) => {
            this.audioChunks.push(event.data);
            this.drawWaveform();
          });
          this.audioRecorder.start();
        })
        .catch((error) => {
          console.error('Error accessing microphone:', error);
        });
    },
    stopRecording() {
      this.isRecording = false;
      this.audioRecorder.stop();
      this.audioRecorder.stream.getTracks().forEach((track) => track.stop());
      this.audioRecorder = null;
      this.recordedFile = new File(this.audioChunks, 'recorded_audio.wav', { type: 'audio/wav' });
    },
    drawWaveform() {
      const waveformElement = this.$refs.waveform;
      const canvas = waveformElement.getContext('2d');
      const width = waveformElement.width;
      const height = waveformElement.height;
      const data = new Uint8Array(this.audioChunks.reduce((acc, chunk) => acc + chunk.byteLength, 0));
      let offset = 0;
      this.audioChunks.forEach((chunk) => {
        const reader = new FileReader();
        reader.onload = () => {
          const array = new Uint8Array(reader.result);
          data.set(array, offset);
          offset += array.length;
          canvas.clearRect(0, 0, width, height);
          canvas.fillStyle = '#000000';
          for (let i = 0; i < width; i++) {
            const value = data[Math.floor(i * (data.length / width))];
            const barHeight = (value / 255) * height;
            canvas.fillRect(i, height - barHeight, 1, barHeight);
          }
        };
        reader.readAsArrayBuffer(chunk);
      });
    },
    convertToMp3() {
      const wavData = new Uint8Array(this.audioChunks.reduce((acc, chunk) => acc + chunk.byteLength, 0));
      let offset = 0;
      this.audioChunks.forEach((chunk) => {
        const array = new Uint8Array(chunk);
        wavData.set(array, offset);
        offset += array.length;
      });
      const wavFile = new Blob([wavData], { type: 'audio/wav' });
      const mp3Encoder = new lamejs.Mp3Encoder(1, this.audioContext.sampleRate, 128);
      const samples = new Int16Array(wavData.buffer);
      const mp3Data = [];
      let remaining = samples.length;
      let index = 0;
      while (remaining >= 0) {
        const bufferSize = Math.min(remaining, 1152);
        const buffer = samples.subarray(index, index + bufferSize);
        const mp3Buffer = mp3Encoder.encodeBuffer(buffer);
        mp3Data.push(mp3Buffer);
        remaining -= bufferSize;
        index += bufferSize;
      }
      const mp3Buffer = mp3Encoder.flush();
      mp3Data.push(mp3Buffer);
      const mp3DataBlob = new Blob(mp3Data, { type: 'audio/mp3' });
      this.mp3File = new File([mp3DataBlob], 'recorded_audio.mp3', { type: 'audio/mp3' });
    },
    uploadFile() {
      const formData = new FormData();
      formData.append('audio', this.mp3File);
      uni.uploadFile({
        url: 'http://your-django-server/upload/',
        filePath: this.mp3File.path,
        name: 'audio',
        formData: formData,
        success: (res) => {
          console.log('File uploaded:', res);
        },
        fail: (error) => {
          console.error('Error uploading file:', error);
        },
      });
    },
  },
};
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

.waveform {
  width: 300px;
  height: 100px;
  background-color: #f0f0f0;
}

.controls {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

button {
  margin: 0 10px;
}
</style>

请确保在uniapp项目中安装了lamejs库,可以使用以下命令进行安装:


  
npm install lamejs

在Django服务器端,你需要修改视图函数来处理MP3文件的上传和保存。以下是一个简单的示例代码:


  
  • from django.http import JsonResponse
    
    def upload_file(request):
        if request.method == 'POST' and request.FILES.get('audio'):
            audio_file = request.FILES['audio']
            with open('path/to/save/audio.mp3', 'wb') as f:
                for chunk in audio_file.chunks():
                    f.write(chunk)
            return JsonResponse({'success': True})
        return JsonResponse({'success': False, 'message': 'Invalid request'})
    

    请将上述代码保存为一个Django视图函数,并将其添加到你的Django项目的URL配置中。

    注意:上述代码仅为示例,你可能需要根据你的具体需求进行适当的修改和调整。

  • npm install lamejs 下载不下来
  • 如果你无法通过npm install lamejs命令下载lamejs库,可能是由于网络问题或库的可用性问题。你可以尝试以下解决方案:

    1. 使用淘宝镜像:在命令行中执行以下命令,将npm的镜像源切换为淘宝镜像,然后再次尝试安装:

  • npm config set registry https://registry.npm.taobao.org
    
  • 使用cnpm:cnpm是淘宝镜像提供的npm镜像的命令行工具,可以尝试使用cnpm来安装:

    1. npm install -g cnpm --registry=https://registry.npm.taobao.org
      cnpm install lamejs
      
    2. 手动下载:如果以上方法仍然无法下载,你可以尝试手动下载lamejs库的压缩包。你可以在https://www.npmjs.com/package/lamejs上找到lamejs的页面,然后下载最新版本的压缩包。下载完成后,解压缩并将其中的文件复制到你的uniapp项目中的合适位置。

    请注意,以上解决方案仅供参考,具体的操作可能因个人环境和网络条件而有所不同。如果问题仍然存在,请尝试在其他网络环境下进行安装,或者考虑使用其他类似的库来处理音频文件的转换。

  • npm ERR! code CERT_HAS_EXPIRED
    npm ERR! errno CERT_HAS_EXPIRED
    npm ERR! request to https://registry.npm.taobao.org/cnpm failed, reason: certificate has expired
    
    npm ERR! A complete log of this run can be found in:
    npm ERR!     C:\Users\Administrator\AppData\Local\npm-cache\_logs\2024-01-25T09_21_52_636Z-debug-0.log
  • 这个错误提示表明你的npm证书已过期,导致无法从https://registry.npm.taobao.org下载lamejs库。你可以尝试以下解决方案:

    1. 更新npm:运行以下命令来更新npm到最新版本:

  • npm install -g npm
    
  • 清除npm缓存:运行以下命令来清除npm缓存:

  • npm cache clean --force
    
  • 使用其他镜像源:尝试使用其他npm镜像源来安装lamejs。你可以尝试使用npm的官方镜像源或其他可靠的镜像源。运行以下命令来切换镜像源:

  • npm config set registry https://registry.npmjs.org/
    
  • 使用代理:如果你在使用代理服务器,请确保npm配置了正确的代理设置。你可以通过运行以下命令来配置代理:

    1. npm config set proxy http://your-proxy-server:port
      npm config set https-proxy http://your-proxy-server:port
      

    如果以上解决方案仍然无法解决问题,可能是由于网络或其他环境问题导致的。你可以尝试在其他网络环境下进行安装,或者考虑使用其他类似的库来处理音频文件的转换。

这里笔者使用手动下载的方式

要手动下载lamejs到UniApp项目中,可以按照以下步骤进行操作:

  1. 打开lamejs的GitHub页面:https://github.com/zhuker/lamejs

  2. 在页面上找到并点击绿色的 “Code” 按钮,然后选择 “Download ZIP” 下载lamejs的源代码压缩包。

  3. 解压下载的ZIP文件,得到一个名为 “lamejs-master” 的文件夹。

  4. 打开你的UniApp项目,在项目的根目录下找到 “static” 文件夹(如果没有则手动创建一个)。

  5. 将解压得到的 “lamejs-master” 文件夹复制到 “static” 文件夹中。

  6. 在你的UniApp项目中,找到需要使用lamejs的页面或组件。

  7. 在需要使用lamejs的页面或组件中,使用相对路径引入lamejs的相关文件。例如,如果你在页面的script标签中引入lamejs,可以使用以下代码:


  
  • import lamejs from '@/static/lamejs-master/lame.min.js';
    
    1. 现在你可以在页面或组件中使用lamejs的功能了。

    请注意,以上步骤假设你已经安装了UniApp开发环境,并且已经创建了一个UniApp项目。如果你的项目结构有所不同,你需要根据实际情况进行相应的调整。

lamejs (v1.2.1) - Pure JavaScript MP3 Encoder | BootCDN - Bootstrap 中文网开源项目免费 CDN 加速服务

 

相关推荐

  1. golang文件ftp服务器

    2024-01-26 13:04:03       44 阅读
  2. uniapp APP 文件

    2024-01-26 13:04:03       37 阅读
  3. 微信小程序 图片文件服务器

    2024-01-26 13:04:03       28 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-26 13:04:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-26 13:04:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-26 13:04:03       82 阅读
  4. Python语言-面向对象

    2024-01-26 13:04:03       91 阅读

热门阅读

  1. 流量控制+MSTP+堆叠+VRRP+BFD

    2024-01-26 13:04:03       55 阅读
  2. 使用ajax异步获取下拉列表的值

    2024-01-26 13:04:03       59 阅读
  3. OpenSSL library错误

    2024-01-26 13:04:03       44 阅读
  4. k8s从入门到实践

    2024-01-26 13:04:03       48 阅读
  5. 举例说明计算机视觉(CV)技术的优势和挑战

    2024-01-26 13:04:03       53 阅读
  6. ArrayList扩容机制

    2024-01-26 13:04:03       61 阅读
  7. retrofit基本模板

    2024-01-26 13:04:03       62 阅读
  8. 大寒节气:天童美语带你感受大寒的传统文化

    2024-01-26 13:04:03       54 阅读
  9. 367.有效的完全平方数(力扣LeetCode)

    2024-01-26 13:04:03       49 阅读
  10. 如何利用ChatGPT提升工作效率?

    2024-01-26 13:04:03       56 阅读