当前位置: 移动技术网 > IT编程>脚本编程>vue.js > vue + node如何通过一个Txt文件批量生成MP3并压缩成Zip

vue + node如何通过一个Txt文件批量生成MP3并压缩成Zip

2020年06月23日  | 移动技术网IT编程  | 我要评论

看看效果叭

解压的文件

上传的文件格式

测试1|||测试1的文字
测试2|||测试2的文字
测试3|||测试3的文字
测试4|||测试4的文字
测试5|||测试5的文字

实现的逻辑如下

  • 上传文件
  • 解析txt
  • 发送内容至百度语音合成
  • 生成文件夹放置本次合成的mp3文件,并压缩成zip
  • 发送zip的地址给前端

使用了 element-ui 的 el-upload 组件

<el-upload
  v-loading="loading"
  class="upload-demo"
  drag
  ref="upload"
  action="#"
  accept=".txt"
  :before-upload="onbeforeuploadimage"
  :http-request="uploadimage"
  :on-change="filechange"
  :file-list="filelist"
 >
 <i class="el-icon-upload"></i>
 <div class="el-upload__text">
  将文件拖到此处,或
  <em>点击上传</em>
 </div>
 <div class="el-upload__tip" slot="tip">只能上传txt文件,且不超过1m</div>
</el-upload>

在上传之前判断上传的文件是否符合要求

onbeforeuploadimage(file) {
 const istxt = file.type === "text/plain";
 const islt1m = file.size / 1024 / 1024 < 1;
 if (!istxt) {
  this.$message.error("上传文件只能是txt格式!");
 }
 if (!islt1m) {
  this.$message.error("上传文件大小不能超过 1mb!");
 }
 return istxt && islt1m;
}

一次只上传一个文件,在文件列表更新时先清除之前的文件

filechange(file) {
  let obj = this.onbeforeuploadimage(file.raw);
  if (obj) {
    this.$refs.upload.clearfiles(); 
    this.filelist = [{ name: file.name, url: file.url }];
  }
}

上传的主要函数

uploadimage(param) {
  this.loading = true;
  const formdata = new formdata();
  formdata.append("file", param.file);
  this.$axios({
    url: process.env.vue_app_base_api + "api/txttomp3",
    method: "post",
    data: formdata
  })
  .then(response => {
    if (response.data.code == 0) {
      this.loading = false;
      this.dialogvisible = true;
      this.url = response.data.data.url;
    }
  })
  .catch(error => {
    console.log(error);
  });
}

node代码

用到的依赖项

const formidable = require("formidable"); //获取上传的txt,并保存
const path = require("path"); 
const aipspeech = require("baidu-aip-sdk").speech; //百度语音合成sdk
const fs = require("fs"); 
const compressing = require("compressing"); //压缩文件夹用

接口代码

router.post("/txttomp3", async function (req, res, next) {
 let form = new formidable.incomingform();
 form.encoding = "utf-8"; //编码
 form.uploaddir = path.join(__dirname + "/../txt"); //保存上传文件地址
 form.keepextensions = true; //保留后缀

 form.parse(req, function (err, fields, files) {
  let filename;
  filename = files.file.name;

  let namearray = filename.split("."); //分割
  let type = namearray[namearray.length - 1];
  let name = "";
  for (let i = 0; i < namearray.length - 1; i++) {
   name = name + namearray[i];
  }
  let date = new date();
  let time = "_" + date.gettime();
  let avatarname = name + time + "." + type;
  let newpath = form.uploaddir + "/" + avatarname;
  fs.renamesync(files.file.path, newpath); //移动文件
  fs.readfile(newpath, "utf-8", function (err, data) {
   if (err) {
    console.log(err);
    new result(null, "读取失败").fail(res);
   } else {
    let client = new aipspeech(
     0,
     "百度语音合成key",
     "百度语音合成secret"
    );

    let resultdata = data.split("\n");
    let number = resultdata.length;
    let formtime = new date().gettime();
    let mp3filedir = path.join(__dirname + "/../mp3_" + formtime);
    fs.mkdirsync(mp3filedir);
    for (let i in resultdata) {
      settimeout(function(){
        if (resultdata[i].indexof("|||") != -1) {
        let text = resultdata[i].split("|||")[1];
        // 语音合成,保存到本地文件
        client.text2audio(text, { spd: 4, per: 4 }).then(
         function (result) {
          if (result.data) {
           let time = resultdata[i].split("|||")[0] + "_voice";
           let avatarname_mp3 = mp3filedir + "/" + time + ".mp3";
           fs.writefilesync(avatarname_mp3, result.data);
           number--;
           if (number == 0) {
            let zipfilename = "zip/mp3_" + formtime + ".zip";
            compressing.zip
             .compressdir(mp3filedir, zipfilename)
             .then(() => {
              let item = {
               url: zipfilename,
              };
              new result(item, "压缩成功").success(res);
             })
             .catch((err) => {
              new result(null, "压缩失败").fail(res);
             });
           }
          } else {
           // 合成服务发生错误
           new result(null, "合成失败").fail(res);
          }
         },
         function (err) {
          console.log(err);
         }
        );
       } else {
        new result(null, "文件格式错误").fail(res);
       }  
      },i * 20)
    }
   }
  });
 });
});

ps:

在node部分,在判断需要合成的文件是否全部完成时,我是通过number的值等于0判断完成,不知道大佬们有啥好方法不?

到此这篇关于vue + node如何通过一个txt文件批量生成mp3并压缩成zip的文章就介绍到这了,更多相关vue node批量生成mp3内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网