Java音频 - 将音频文件剪裁到指定的长度

时间:2018-03-26 17:09:11

标签: java audio

我正在尝试创建一个小型java程序,将音频文件剪切到指定的长度。目前我有以下代码: -

import java.util.*;
import java.io.*;
import javax.sound.sampled.*;

public class cuttest_3{

public static void main(String[]args)
    {
     int totalFramesRead = 0;

 File fileIn = new File("output1.wav");

 // somePathName is a pre-existing string whose value was
 // based on a user selection.

 try {
      AudioInputStream audioInputStream = 
      AudioSystem.getAudioInputStream(fileIn);
      int bytesPerFrame = 
      audioInputStream.getFormat().getFrameSize();
      if (bytesPerFrame == AudioSystem.NOT_SPECIFIED) {

     // some audio formats may have unspecified frame size
     // in that case we may read any amount of bytes

      bytesPerFrame = 1;
      } 

      // Set a buffer size of 5512 frames - semiquavers at 120bpm

      int numBytes = 5512 * bytesPerFrame; 
      byte[] audioBytes = new byte[numBytes];



      try {
        int numBytesRead = 0;
        int numFramesRead = 0;

        // Try to read numBytes bytes from the file.

        while ((numBytesRead = 
          audioInputStream.read(audioBytes)) != -1) {
          // Calculate the number of frames actually read.
          numFramesRead = numBytesRead / bytesPerFrame;
          totalFramesRead += numFramesRead;

          // Here,  - output a trimmed audio file

             AudioInputStream cutFile = 
                 new AudioInputStream(audioBytes);

             AudioSystem.write(cutFile, 
             AudioFileFormat.Type.WAVE, 

                new File("cut_output1.wav"));

        }
      } catch (Exception ex) { 
        // Handle the error...
      }
    } catch (Exception e) {
      // Handle the error...
    }
}
}

尝试编译时,会返回以下错误: -

cuttest_3.java:50: error: incompatible types: byte[] cannot be converted to TargetDataLine
                 new AudioInputStream(audioBytes);

我对Java中的AudioInputStream处理不是很熟悉,所以有人可以提出一种方法来整合数据以实现输出吗?非常感谢

1 个答案:

答案 0 :(得分:0)

你必须告诉AudioInputStream如何解密传入的字节,如答案here中的Matt所指定的那样。 This文档指出了每个参数的含义。

字节流没有任何意义,除非你向系统发出声音,指出有多少通道,每个样本的位分辨率,每秒采样数等等。

由于.wav文件是一种理解的协议,我认为它们在文件前面有定义音频轨道各种参数的数据,因此AudioInputStream可以正确解读你传入的第一个文件。