Как избежать отключения крюка - PullRequest
1 голос
/ 24 апреля 2010

Через следующий код я могу воспроизвести и вырезать и аудиофайл. Есть ли другой способ избежать использования крюка отключения? Проблема в том, что всякий раз, когда я нажимаю кнопку вырезания, файл не сохраняется, пока я не закрою приложение

спасибо

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)

Как вы думаете, я могу получить те же результаты, не прибегая к крючку?

1 Ответ

1 голос
/ 24 апреля 2010

Прежде всего, все ваши комментарии полностью избыточны, вы просто повторяете названия различных классов и методов, которые вы используете.

Что касается проблемы, ваш код сохранения находится в ловушке завершения работы, что означает « сделать это, когда приложение собирается закрыть », что, естественно, означает, что оно не сохранит его, пока программа не будет собирается закрыть. Итак, переместите эту логику из ловушки отключения в любое логическое место - скорее всего, в конце метода, возможно, даже в final блоке - и все.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...