obtaining an AudioInputStream upto some x bytes from the original (Cutting an Audio File)

做~自己de王妃 提交于 2019-11-28 02:15:53

问题


How can i read an AudioInputStream upto a particular number of bytes/microsecond position ? For example :

AudioInputStream ais = AudioSystem.getAudioInputStream( new File("file.wav") );
// let the file.wav be of y bytes

Now i want to obtain an AudioInputStream that has data upto some x bytes where x < y bytes.

How can i do that ?

I have been thinking hard but haven't got any method to do that ?


回答1:


The code below shows you how to copy a part of an audio stream, reading from one file and writing to another.

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

class AudioFileProcessor {

  public static void main(String[] args) {
    copyAudio("/tmp/uke.wav", "/tmp/uke-shortened.wav", 2, 1);
  }

  public static void copyAudio(String sourceFileName, String destinationFileName, int startSecond, int secondsToCopy) {
    AudioInputStream inputStream = null;
    AudioInputStream shortenedStream = null;
    try {
      File file = new File(sourceFileName);
      AudioFileFormat fileFormat = AudioSystem.getAudioFileFormat(file);
      AudioFormat format = fileFormat.getFormat();
      inputStream = AudioSystem.getAudioInputStream(file);
      int bytesPerSecond = format.getFrameSize() * (int)format.getFrameRate();
      inputStream.skip(startSecond * bytesPerSecond);
      long framesOfAudioToCopy = secondsToCopy * (int)format.getFrameRate();
      shortenedStream = new AudioInputStream(inputStream, format, framesOfAudioToCopy);
      File destinationFile = new File(destinationFileName);
      AudioSystem.write(shortenedStream, fileFormat.getType(), destinationFile);
    } catch (Exception e) {
      println(e);
    } finally {
      if (inputStream != null) try { inputStream.close(); } catch (Exception e) { println(e); }
      if (shortenedStream != null) try { shortenedStream.close(); } catch (Exception e) { println(e); }
    }
  }

  public static void println(Object o) {
    System.out.println(o);
  }

  public static void print(Object o) {
    System.out.print(o);
  }

}



回答2:


Now that you have the stream you can read one byte at a time up to the maximum number ob bytes you want using read(), or read a fixed number of bytes with read(byte[] b).



来源:https://stackoverflow.com/questions/7546010/obtaining-an-audioinputstream-upto-some-x-bytes-from-the-original-cutting-an-au

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!