Java negative arraysize exception when launching music with clip.open

458 views Asked by At

I am currently trying to launch music into my program using javax.sound.sampled, and I wrote a method called music which is supposed to launch a music clip when executed. It goes like this:

public void playMusic(){
    try {
        AudioInputStream astream = AudioSystem.getAudioInputStream(
                newFileInputStream("bin/ctk_tune.mp3"));    
        AudioFormat baseFormat = astream.getFormat();

        AudioFormat newFormat = new AudioFormat(
            AudioFormat.Encoding.PCM_SIGNED,
            baseFormat.getSampleRate(),
            16,
            baseFormat.getChannels(),
            baseFormat.getChannels() * 2,
            baseFormat.getSampleRate(),
            false);
    
        AudioInputStream dstream = AudioSystem.getAudioInputStream(
                newFormat, astream); 
    
        Clip clip = AudioSystem.getClip();
        clip.open(dstream);
    
        clip.setFramePosition(0);
        clip.start();
    } catch(IOException ex) {
        System.out.println("music not loaded : ");
        ex.printStackTrace();
    } catch (UnsupportedAudioFileException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (LineUnavailableException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

When I tried running it, I got an uncaught exception (the program didn't launch) which said:

Exception in thread "main" java.lang.NegativeArraySizeException
at org.classpath.icedtea.pulseaudio.PulseAudioClip.open(PulseAudioClip.java:449)
at mainProgram.playMusic(mainProgram.java:211)
at mainProgram.<init>(mainProgram.java:67)
at Launcher.main(Launcher.java:16)
1

There are 1 answers

2
Stephen C On

I think your code is failing when it calls this method:

@Override
public void open(AudioInputStream stream) 
        throws LineUnavailableException, IOException {
    byte[] buffer = new byte[(int) (stream.getFrameLength() * 
                                    stream.getFormat().getFrameSize())];
    stream.read(buffer, 0, buffer.length);
    open(stream.getFormat(), buffer, 0, buffer.length);
}

It would appear that the expression:

    stream.getFrameLength() * stream.getFormat().getFrameSize()

is giving you a negative value. That will cause that exception ... and I cannot see any other way that the exception could happen in that method.

My guess is that either there is something wrong with the way you are creating the stream or format descriptor, or there is something wrong with the audio file you are trying to play.


I suggest you use a debugger to figure out why that expression is negative.