通过以下代码,我可以播放和剪切音频文件。
还有其他方法可以避免使用关机钩子吗?
问题是,每当我按下“剪切”按钮时,文件都不会保存,直到我关闭应用程序

谢谢

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()之后的其他地方;我得到一个错误:


  永远不会在相应的try语句的正文中抛出java.io.IOException异常-> catch(IOException e)


您是否认为我不借助钩子也可以获得相同的结果?

最佳答案

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

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

10-08 12:53