Java 實(shí)現(xiàn)音頻添加自定義時(shí)長(zhǎng)靜音(附代碼) | Java工具類(lèi)

前言

本文提供一個(gè)可以給一個(gè)wav音頻添加自定義時(shí)長(zhǎng)靜音的工具類(lèi)。正好工作中用到,所以正好分享分享。

Maven依賴(lài)

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>30.1.1-jre</version>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.5.2</version>
        </dependency>

代碼

package ai.guiji.csdn.tools;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import com.google.common.base.Joiner;
import com.google.common.primitives.Bytes;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.LongStream;

/** @Author 劍客阿良_ALiang @Date 2022/1/26 14:27 @Description: wav添加靜音時(shí)長(zhǎng)工具 */
public class WavAddSilenceUtils {
  /**
   * 根據(jù)PCM文件構(gòu)建wav的header字段
   *
   * @param srate Sample rate - 8000, 16000, etc.
   * @param channel Number of channels - Mono = 1, Stereo = 2, etc..
   * @param format Number of bits per sample (16 here)
   * @throws IOException
   */
  public static byte[] buildWavHeader(int dataLength, int srate, int channel, int format)
      throws IOException {
    byte[] header = new byte[44];

    long totalDataLen = dataLength + 36;
    long bitrate = srate * channel * format;

    header[0] = 'R';
    header[1] = 'I';
    header[2] = 'F';
    header[3] = 'F';
    header[4] = (byte) (totalDataLen & 0xff);
    header[5] = (byte) ((totalDataLen >> 8) & 0xff);
    header[6] = (byte) ((totalDataLen >> 16) & 0xff);
    header[7] = (byte) ((totalDataLen >> 24) & 0xff);
    header[8] = 'W';
    header[9] = 'A';
    header[10] = 'V';
    header[11] = 'E';
    header[12] = 'f';
    header[13] = 'm';
    header[14] = 't';
    header[15] = ' ';
    header[16] = (byte) format;
    header[17] = 0;
    header[18] = 0;
    header[19] = 0;
    header[20] = 1;
    header[21] = 0;
    header[22] = (byte) channel;
    header[23] = 0;
    header[24] = (byte) (srate & 0xff);
    header[25] = (byte) ((srate >> 8) & 0xff);
    header[26] = (byte) ((srate >> 16) & 0xff);
    header[27] = (byte) ((srate >> 24) & 0xff);
    header[28] = (byte) ((bitrate / 8) & 0xff);
    header[29] = (byte) (((bitrate / 8) >> 8) & 0xff);
    header[30] = (byte) (((bitrate / 8) >> 16) & 0xff);
    header[31] = (byte) (((bitrate / 8) >> 24) & 0xff);
    header[32] = (byte) ((channel * format) / 8);
    header[33] = 0;
    header[34] = 16;
    header[35] = 0;
    header[36] = 'd';
    header[37] = 'a';
    header[38] = 't';
    header[39] = 'a';
    header[40] = (byte) (dataLength & 0xff);
    header[41] = (byte) ((dataLength >> 8) & 0xff);
    header[42] = (byte) ((dataLength >> 16) & 0xff);
    header[43] = (byte) ((dataLength >> 24) & 0xff);

    return header;
  }

  /**
   * 默認(rèn)寫(xiě)入的pcm數(shù)據(jù)是16000采樣率,16bit,可以按照需要修改
   *
   * @param filePath
   * @param pcmData
   */
  public static boolean writeToFile(String filePath, byte[] pcmData) {
    BufferedOutputStream bos = null;
    try {
      bos = new BufferedOutputStream(new FileOutputStream(filePath));
      byte[] header = buildWavHeader(pcmData.length, 16000, 1, 16);
      bos.write(header, 0, 44);
      bos.write(pcmData);
      bos.close();
      return true;
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (bos != null) {
        try {
          bos.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }

    return false;
  }

  /**
   * 增加延時(shí)靜音
   *
   * @param filePath 音頻地址
   * @param tmpDirPath 臨時(shí)目錄地址
   * @param delayTime 延時(shí)時(shí)長(zhǎng),單位毫秒
   * @return 最終文件地址
   * @throws Exception 異常
   */
  public static String delayWav(String filePath, String tmpDirPath, Long delayTime)
      throws Exception {
    byte[] bytes;
    if (filePath.startsWith("http")) {
      bytes = IoUtil.readBytes(URLUtil.getStream(new URL(filePath)));
    } else {
      bytes = FileUtil.readBytes(filePath);
    }
    List<Byte> resultByte =
        new ArrayList<>(Bytes.asList(Arrays.copyOfRange(bytes, 44, bytes.length)));
    LongStream.range(0, (long) (delayTime * 32)).forEach(x -> resultByte.add((byte) 0));
    String resultPath =
        Joiner.on(File.separator).join(Arrays.asList(tmpDirPath, IdUtil.simpleUUID() + ".wav"));
    writeToFile(resultPath, Bytes.toArray(resultByte));
    return resultPath;
  }

  public static void main(String[] args) throws Exception {
    System.out.println(delayWav("http://xxxx/xxx.wav", "C:\\Users\\huyi\\Desktop\\", 10000L));
  }
}

代碼說(shuō)明:

1、delayWav方法參數(shù)分別為wav音頻文件地址(可以支持http的url地址)、臨時(shí)文件目錄地址、延時(shí)靜音時(shí)長(zhǎng)(單位毫秒)

2、對(duì)wav的要求默認(rèn)為:采樣率16K、單聲道。可以參考:https://huyi-aliang.blog.csdn.net/article/details/120567978

對(duì)需要處理的音頻參數(shù)調(diào)整。

3、生成uuid的隨機(jī)文件名,避免重復(fù)。

驗(yàn)證一下

下面是準(zhǔn)備的音頻

file

執(zhí)行結(jié)果

file

執(zhí)行后音頻

file

OK,加了10秒的靜音。

總結(jié)

沒(méi)啥總結(jié)的,最近想開(kāi)個(gè)新專(zhuān)欄,正在準(zhǔn)備中。

分享:令她反感的,遠(yuǎn)不是世界的丑陋,而是這個(gè)世界所戴的漂亮面具?!恫豢沙惺艿纳p》

如果本文對(duì)你有幫助的話,點(diǎn)個(gè)贊吧,謝謝??!

file

本人CSDN主頁(yè)地址:劍客阿良_ALiang的主頁(yè)

一起學(xué)習(xí),一起進(jìn)步。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容