Adrian Bica
Adrian Bica

Reputation: 71

Java Sound API locks audio file after playing it

I am trying to use Javax.sound to play a .wav file. Everything works fine, the file plays as expected and in the end I close the Clip and I close the AudioInputStream. However, the file remains locked (in use) after that and I cannot touch it without getting an exception: java.nio.file.FileSystemException: alerting.wav: The process cannot access the file because it is being used by another process.

A sample of code is below:

static private class SoundThread extends Thread implements LineListener {
    private boolean playCompleted;
    private int cycles;
    
    public SoundThread(int repeats) {
        cycles = repeats;
    }
    
    @Override
    public void run() {
        Clip clip;
        AudioInputStream inputStream;
        File soundFile = new File("alerting.wav");
        try {
            inputStream = AudioSystem.getAudioInputStream(soundFile);
            try {
                clip = AudioSystem.getClip();
                clip.addLineListener(this);
                clip.open(inputStream);
                while(cycles > 0) {
                    playCompleted = false;
                    clip.setFramePosition(0);
                    clip.start();
                    while(!playCompleted) {
                        Thread.sleep(1000);
                    }
                    Thread.sleep(audioRepeatTime * 1000);
                    cycles--;
                }
                //clip.drain();
                clip.close();
                inputStream.close();
                System.out.println("All closed");
                try {
                    this.finalize();
                } catch (Throwable ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (Exception ex) {
                Main.syslog(Level.WARNING, "E1001 could not play alert sound", ex);
            } finally {
                inputStream.close();
            }
        } catch (UnsupportedAudioFileException ex) {
            Main.syslog(Level.WARNING, "E1001 could not play alert sound", ex);
        } catch (IOException ex) {
            Main.syslog(Level.WARNING, "E1001 could not play alert sound", ex);
        }
    }

    @Override
    public void update(LineEvent event) {
        LineEvent.Type type = event.getType();
        
        System.out.println("Event: " + type);
        if(type == LineEvent.Type.STOP) {
            playCompleted = true;
        } else if (type == LineEvent.Type.CLOSE) {
            System.out.println("listener closed");
        }
    }
}

public static void PlayAlertSound() {
    if(enableAudio) {
        SoundThread st = new SoundThread(audioLoops);
        st.start();
    }
} 

public static void PlayAlertSound(int repeats) {
    if(enableAudio) {
        SoundThread st = new SoundThread(repeats);
        st.start();
    }
} 

In the Java threads list I see "Java Sound Event Dispatcher" running. I think this is what keeps the file locked. Any idea how can I fix this? Thanks

Upvotes: 1

Views: 200

Answers (2)

Reda Boukdir
Reda Boukdir

Reputation: 21

Instead of:

//...
AudioInputStream inputStream;
File soundFile = new File("alerting.wav");
try {
    inputStream = AudioSystem.getAudioInputStream(soundFile);
    // ...
}
// ...

Try this:

//...
AudioInputStream inputStream;
File soundFile = new File("alerting.wav");
try {
    byte[] bytes = Files.readAllBytes(soundFile.toPath());
    inputStream = AudioSystem.getAudioInputStream(new ByteArrayInputStream(bytes));
    // ...
}
// ...

Upvotes: 0

Phil Freihofner
Phil Freihofner

Reputation: 7910

The API for Clip states:

Note that some lines, once closed, cannot be reopened. Attempts to reopen such a line will always result in a LineUnavailableException.

I'm going to make a couple additional suggestions.

Instead of using File, a better way to load audio resources is with the class.getResource method. This method returns a URL which you can then pass as your argument to the AudioSystem.getAudioInputStream method.

I'm not clear what you are trying to do, but I also recommend some further changes to your code. Initializing and playing a Clip in the same method is not generally done, as it goes against the intended use of the Clip. A Clip is meant for sounds that can be held in memory. So, make your Clip an instance variable. Then, place the code that loads and opens the Clip in its own method. And put the code that calls start or loop in a separate method or methods, and don't close the Clip at the end of playing unless you are sure you are not going to ever play it again.

If you use clip.loop, you don't have to bother with listeners and count iterations.

Upvotes: 1

Related Questions