溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

vue+node通過(guò)一個(gè)Txt文件批量生成MP3并壓縮成Zip的實(shí)現(xiàn)方法

發(fā)布時(shí)間:2020-07-20 10:22:28 來(lái)源:億速云 閱讀:308 作者:小豬 欄目:web開發(fā)

這篇文章主要講解了vue+node通過(guò)一個(gè)Txt文件批量生成MP3并壓縮成Zip的實(shí)現(xiàn)方法,內(nèi)容清晰明了,對(duì)此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會(huì)有幫助。

看看效果叭

vue+node通過(guò)一個(gè)Txt文件批量生成MP3并壓縮成Zip的實(shí)現(xiàn)方法

解壓的文件

vue+node通過(guò)一個(gè)Txt文件批量生成MP3并壓縮成Zip的實(shí)現(xiàn)方法

上傳的文件格式

測(cè)試1|||測(cè)試1的文字
測(cè)試2|||測(cè)試2的文字
測(cè)試3|||測(cè)試3的文字
測(cè)試4|||測(cè)試4的文字
測(cè)試5|||測(cè)試5的文字

實(shí)現(xiàn)的邏輯如下

  • 上傳文件
  • 解析txt
  • 發(fā)送內(nèi)容至百度語(yǔ)音合成
  • 生成文件夾放置本次合成的mp3文件,并壓縮成zip
  • 發(fā)送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>點(diǎn)擊上傳</em>
 </div>
 <div class="el-upload__tip" slot="tip">只能上傳txt文件,且不超過(guò)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("上傳文件大小不能超過(guò) 1MB!");
 }
 return isTxt && isLt1M;
}

一次只上傳一個(gè)文件,在文件列表更新時(shí)先清除之前的文件

fileChange(file) {
  let obj = this.onBeforeUploadImage(file.raw);
  if (obj) {
    this.$refs.upload.clearFiles(); 
    this.fileList = [{ name: file.name, url: file.url }];
  }
}

上傳的主要函數(shù)

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代碼

用到的依賴項(xiàng)

const formidable = require("formidable"); //獲取上傳的txt,并保存
const path = require("path"); 
const AipSpeech = require("baidu-aip-sdk").speech; //百度語(yǔ)音合成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); //移動(dòng)文件
  fs.readFile(newPath, "utf-8", function (err, data) {
   if (err) {
    console.log(err);
    new Result(null, "讀取失敗").fail(res);
   } else {
    let client = new AipSpeech(
     0,
     "百度語(yǔ)音合成key",
     "百度語(yǔ)音合成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];
        // 語(yǔ)音合成,保存到本地文件
        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 {
           // 合成服務(wù)發(fā)生錯(cuò)誤
           new Result(null, "合成失敗").fail(res);
          }
         },
         function (err) {
          console.log(err);
         }
        );
       } else {
        new Result(null, "文件格式錯(cuò)誤").fail(res);
       }  
      },i * 20)
    }
   }
  });
 });
});

PS:

在node部分,在判斷需要合成的文件是否全部完成時(shí),我是通過(guò)number的值等于0判斷完成,不知道大佬們有啥好方法不?

看完上述內(nèi)容,是不是對(duì)vue+node通過(guò)一個(gè)Txt文件批量生成MP3并壓縮成Zip的實(shí)現(xiàn)方法有進(jìn)一步的了解,如果還想學(xué)習(xí)更多內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI