0

I have a function that is called every time the user clicks which will start the music if the screen has changed. The only problem with it right now is that it does not stop. I have figured out that this is because clip = AudioSystem.getClip(); won't return the currently playing clip, it returns a random location every time. How do I make sure that clip gets the value of the currently playing clip so that I can stop it?

The "StartBGMusic" function

public void startBGMusic() throws LineUnavailableException, IOException
    {   
        clip = AudioSystem.getClip();
        System.out.println(clip);
        try
        {
            if(SCREEN_CHECK != Screen)
            {
                clip.stop();

                clip.close();

                if(Screen != 14 && Screen != 19 && Screen != 16 && Screen != 15 && Screen != 17)
                {
                    clip.open(AudioSystem.getAudioInputStream(getClass().getResource("UpbeatFunk.wav")));
                    clip.loop(99999);
                }
                else
                {
                    clip.open(AudioSystem.getAudioInputStream(getClass().getResource("Background Music.mid")));
                    clip.loop(99999);
                }
            } 

            SCREEN_CHECK = Screen;
        }catch (Exception e)
        {
            e.printStackTrace(System.out);
        }
    }
  • They say JavaScript is a lot like java, so you could use this video series to figure it out: http://www.developphp.com/list_javascript_video.php#Audio_Workshop – a coder Jul 20 '14 at 01:40
  • 1
    @IGotRoot who is "they"? [Relevant Question](http://stackoverflow.com/questions/245062/whats-the-difference-between-javascript-and-java) – username tbd Jul 20 '14 at 01:43
  • They: from programmers who say that if you can learn java, you can learn JavaScript. – a coder Jul 20 '14 at 01:45

1 Answers1

1

According to oracle documentation, getClip() does not return the current playing sound, but a clip object that can be used to play back an audio file.

You will need to pass a reference to the clip you used to start the audio file. This can be done by returning it/passing it as an argument or by using global variables/getter methods

Matt
  • 968
  • 2
  • 13
  • 22
  • Thanks! but why does it "freeze" for a second when the clip changes to another sound file? – user3672378 Jul 20 '14 at 01:56
  • Since you stop the music before you load the next file, there is a slight delay. This could be avoided by alternating between 2 clip objects that already have the correct file loaded (not as neat, but faster song changing) – Matt Jul 20 '14 at 02:01