如何读取AudioInputStream
特定数量的字节/微秒位置?例如 :
AudioInputStream ais = AudioSystem.getAudioInputStream( new File("file.wav") );
// let the file.wav be of y bytes
现在我想获得一个AudioInputStream
数据高达一些x
字节的x < y
字节。
我怎样才能做到这一点 ?
我一直在努力思考,但没有任何方法可以做到这一点?
下面的代码向您展示了如何复制音频流的一部分,从一个文件读取并写入另一个文件。
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);
}
}
现在您有了流,您可以一次读取一个字节,直到您想要使用的最大数量 ob 字节read()
,或者读取固定数量的字节read(byte[] b)
。