【发布时间】:2011-02-11 21:15:49
【问题描述】:
通过以下代码,我可以播放和剪切音频文件。 有没有其他方法可以避免使用关闭挂钩? 问题是每当我按下剪切按钮时,文件在我关闭应用程序之前不会被保存
谢谢
void play_cut() {
try {
// 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.
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();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}// end play_cut
其实我想知道的是: 我真的需要关闭挂钩吗?
如果我移动这两个代码语句
AudioInputStream startStream = new AudioInputStream(new FileInputStream(inputAudio), audioFormat, c.getLongFramePosition());
AudioSystem.write(startStream, fileType, outputAudio);
c.start() 之后的其他地方;我收到一个错误:
异常java.io.IOException不会在相应的try语句体中抛出-->catch(IOException e)
你认为我可以在不使用钩子的情况下获得相同的结果吗?
【问题讨论】:
-
你不能随时调用你已经在关闭挂钩中使用的方法吗?
-
您在这里提到的错误是编译器错误,警告您捕获了一个从未在相应的try-block中抛出的异常。对
AudioSystem.write的调用可能会引发 IOException,并且当您将调用移到 try 块之外时,该 try 块不会引发异常。您必须移动完整的 try-catch-block 而不是仅移动两个语句。
标签: java