Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

java - cutting a wave file

How can i cut a .wave file using java ?

What i want is :

when the user presses the button labeled cut it should cut the audio from the previous mark (in nanoseconds) to the current position in nanoseconds. (mark is positioned to the current position in nanoseconds after the sound is cut) After i get that piece of audio,i want to save that piece of audio file.

// obtain an audio stream 
long mark = 0; // initially set to zero
//get the current position in nanoseconds
// after that how to proceed ?
// another method ?

How can i do that ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This has originally been answered by Martin Dow

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); }
 }
}

}

Originally answered HERE


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...