While playing an audio file (.wav) I want, if I resort to Ctrl+C, to stop the开发者_运维知识库 playback and save part of the audio file in a file called "file2.wav".
Here's the thread I'd like to add to my code. Unfortunately it doesn't work at all.
class myThread extends Thread{
public void run(){
try {
PipedOutputStream poStream = new PipedOutputStream();
PipedInputStream piStream = new PipedInputStream();
poStream.connect(piStream);
File cutaudioFile = new File ("file2.wav");
AudioInputStream ais =
new AudioInputStream(piStream,
AudioFileFormat.Type.WAVE,
cutaudioFile);
poStream.write(ais,AudioFileFormat.Type.WAVE,cutaudioFile);
}catch (Exception e){
e.printStackTrace();
}
} // end run
} // end myThread
This should be basically what you want. It uses a shutdown hook.
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.sound.sampled.Clip;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class CtrlCAudio
{
public static void main(String[] args) throws LineUnavailableException, UnsupportedAudioFileException, IOException
{
final File inputAudio = new File(args[0]);
final File outputAudio = new File(args[1]);
// First, we get the format of the input file
final AudioFileFormat.Type fileType = AudioSystem.getAudioFileFormat(inputAudio).getType();
// Then, we get a clip for playing the audio.
final Clip c = AudioSystem.getClip();
// We get a stream for playing the input file.
AudioInputStream ais = AudioSystem.getAudioInputStream(inputAudio);
// We use the clip to open (but not start) the input stream
c.open(ais);
// We get the format of the audio codec (not the file format we got above)
final AudioFormat audioFormat = ais.getFormat();
// We add a shutdown hook, an anonymous inner class.
Runtime.getRuntime().addShutdownHook(new Thread()
{
public void run()
{
// We're now in the hook, which means the program is shutting down.
// You would need to use better exception handling in a production application.
try
{
// Stop the audio clip.
c.stop();
// Create a new input stream, with the duration set to the frame count we reached. Note that we use the previously determined audio format
AudioInputStream startStream = new AudioInputStream(new FileInputStream(inputAudio), audioFormat, c.getLongFramePosition());
// Write it out to the output file, using the same file type.
AudioSystem.write(startStream, fileType, outputAudio);
}
catch(IOException e)
{
e.printStackTrace();
}
}
});
// After setting up the hook, we start the clip.
c.start();
}
}
精彩评论