【问题标题】:Avoiding shutdown hook避免关闭挂钩
【发布时间】: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


【解决方案1】:

首先,您所有的 cmets 都是完全多余的,您只需重复您正在使用的各种类和方法的名称。

至于问题,你的保存代码在关闭钩子中,这意味着“在应用程序即将关闭时执行此操作”,这自然意味着它不会保存它,直到程序即将关闭。因此,将该逻辑从关闭挂钩移到任何逻辑位置 - 最有可能在方法结束时,甚至可能在 final 块中 - 就是这样。

【讨论】:

    猜你喜欢
    • 2011-07-20
    • 1970-01-01
    • 2020-10-19
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多