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 JsonResponsedef 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 JsonResponsedef 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 expirednpm 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 加速服务

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/648166.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

《动手学深度学习(PyTorch版)》笔记3.6

注&#xff1a;书中对代码的讲解并不详细&#xff0c;本文对很多细节做了详细注释。另外&#xff0c;书上的源代码是在Jupyter Notebook上运行的&#xff0c;较为分散&#xff0c;本文将代码集中起来&#xff0c;并加以完善&#xff0c;全部用vscode在python 3.9.18下测试通过。…

stm32 裸机点亮led

stm32不用库 裸机点亮led startup.s 定义栈入口函数 进入main .syntax unified .cpu cortex-m3 .fpu softvfp .thumb.global vtable .global reset_handler.type vtable, %object vtable:.word _estack.word reset_handler .size vtable, .-vtable.section .data .word _sidat…

docker 网络及如何资源(CPU/内存/磁盘)控制

安装Docker时&#xff0c;它会自动创建三个网络&#xff0c;bridge&#xff08;创建容器默认连接到此网络&#xff09;、 none 、host docker网络模式 Host 容器与宿主机共享网络namespace&#xff0c;即容器和宿主机使用同一个IP、端口范围&#xff08;容器与宿主机或其他使…

第140期 为什么有人无脑吹分布式(20240126)

数据库管理140期 2024-01-26 第140期 为什么有人无脑吹分布式&#xff08;20240126&#xff09;1 环境2 场景3 首席补刀总结 第140期 为什么有人无脑吹分布式&#xff08;20240126&#xff09; 作者&#xff1a;胖头鱼的鱼缸&#xff08;尹海文&#xff09; Oracle ACE Associa…

mac安装telnet命令

1、安装brew 在mac终端执行命令&#xff1a; /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" 报错&#xff1a; curl: (35) LibreSSL SSL_connect: SSL_ERROR_SYSCALL in connection to raw.githubusercon…

C++ 设计模式之解释器模式

【声明】本题目来源于卡码网&#xff08;卡码网KamaCoder&#xff09; 【提示&#xff1a;如果不想看文字介绍&#xff0c;可以直接跳转到C编码部分】 【设计模式大纲】 【简介】 --什么是解释器模式&#xff08;第22种设计模式&#xff09; 解释器模式&#xff08;Interpreter…

CodeGPT

GitCode - 开发者的代码家园 gitcode.com/ inscode.csdn.net/liujiaping/java_1706242128563/edit?openFileMain.java&editTypelite marketplace.visualstudio.com/items?itemNameCSDN.csdn-codegpt&spm1018.2226.3001.9836&extra%5Butm_source%5Dvip_chatgpt_c…

【算法】用JAVA代码实现LRU 【缓存】【LRU】

LRU(Least Recently Used)是一种常见的缓存淘汰策略,用于在缓存空间不足时确定哪些数据应该被淘汰。其基本原则是淘汰最近最少被访问的数据。 工作原理: 最近使用优先: LRU算法基于这样的思想:最近被使用的数据很可能在短时间内还会被使用,因此保留这些数据有助于提高缓…

linux bash shell的getopt以及函数用法小记

getopt 长选项 短选项 可选参数whilecaseifbasename函数变量shiftread 实现功能描述&#xff1a; 1. 实现可选参数传入 -c 或 --clearBuild。 2. 用shell脚本来实现选择&#xff0c;make时是否clean。 3. 可以打印用法帮助 和 作者信息。 #!/bin/bash# sh函数定义 *******…

vue3 实现上传图片裁剪

在线的例子以及代码&#xff0c;请点击访问链接

实力上榜!安全狗入选《CCSIP 2023中国网络安全行业业全景册(第六版)》多个细项

1月24日&#xff0c;Freebuf发布了《CCSIP 2023中国网络安全行业业全景册&#xff08;第六版&#xff09;》。 作为国内云原生安全领导厂商&#xff0c;安全狗也入选多个细分领域。 厦门服云信息科技有限公司&#xff08;品牌名&#xff1a;安全狗&#xff09;创办于2013年&…

学习gin框架知识的小注意点

Gin框架的初始化 有些项目中 初始化gin框架写的是&#xff1a; r : gin.New() r.Use(logger.GinLogger(), logger.GinRecovery(true)) 而不是r : gin.Default() 为什么呢&#xff1f; 点击进入Default源码发现其实他也是new两个中间件&#xff0c;&#xff08;Logger&…

【并发编程】锁死的问题——如何解决?以及如何避免?

目录 1.如何解决 一、死锁的定义和原因 1.1 定义 1.2 原因 二、常见的死锁场景 2.1 线程间相互等待资源 2.2 嵌套锁的循环等待 2.3 对资源的有序请求 三、死锁排查的方法 3.1 使用jstack命令 3.2 使用jconsole 3.3 使用VisualVM 四、常见的解决方案 4.1 避免嵌套锁…

深入研究C语言数组:高级技巧和性能优化的探索

在前文中&#xff0c;我们介绍了C语言数组的基本概念、多维数组的使用以及作为函数参数的传递方式。本文将进一步探索C语言数组的高级用法和性能优化技巧&#xff0c;帮助读者更深入地理解和运用数组。 动态数组 C语言中&#xff0c;数组的大小在创建时就被确定了&#xff0c…

STK姿态分析(一)矢量组件

文章目录 内容简介一、卫星矢量二、卫星坐标平面三、卫星姿态球面 – 内容简介 接下来一系列文章将进行STK目标&#xff08;卫星、导弹、火箭、飞机、船舶&#xff09;姿态分析的仿真。本篇将使用矢量&#xff08;vector&#xff09;组件对卫星姿态、传感器指向等进行3D可视化…

注册表学习——注册表结构

简介&#xff1a;注册表是由很多项和值构成的。 HEKY_USERS&#xff08;HKU&#xff09; 主要保存默认用户及当前登录用户配置信息。 .DEFAULT 该项是针对未来创建的新用户所保存的默认配置项。 S-1-5-18等项 这些项叫作安全标识符&#xff08;SID&#xff09;用来表示Windows操…

Maven 跳过test 进行 package

在使用Maven构建项目时&#xff0c;如果你想要跳过测试阶段&#xff08;test phase&#xff09;并直接打包&#xff08;package&#xff09;&#xff0c;你可以在命令行中使用特定的Maven命令选项。以下是一些常用的命令和选项&#xff1a; 1. 使用-DskipTests选项&#xff1a…

Linux(linux版本 centos 7) 下安装 oracle 19c详细教程(新手小白易上手)

一、安装前准备 1、下载预安装包 wget http://yum.oracle.com/repo/OracleLinux/OL7/latest/x86_64/getPackage/oracle-database-preinstall-19c-1.0-1.el7.x86_64.rpm预安装包下载成功 2、下载oracle安装包 下载地址如下 https://www.oracle.com/cn/database/technologies…

渲染与创造之美:互为表里的艺术

在五彩斑斓的艺术世界中&#xff0c;渲染与创造是两股不可或缺的力量。它们之间的关系&#xff0c;恰如弓与箭&#xff0c;互为表里&#xff0c;共同塑造出无数令人叹为观止的视觉景象。创造之美是指通过创新思维和创造力&#xff0c;将想象具象化为现实&#xff0c;创造出新的…

spring-aop的介绍和使用

目录 1&#xff1a;为什么我会使用这个框架 2&#xff1a;那怎么快速入手属于自己的spring-aop呢&#xff08;或者说怎么在自己项目调用spring-aop这个框架呢&#xff09; 1->环境&#xff08;自己去建一个maven项目&#xff09; 2->导入spring-aop框架包&#xff08…