Starting and stopping music in background

后端 未结 1 430
日久生厌
日久生厌 2021-01-24 08:34

I\'m making a game and there is background music in it. I want to add a mute button that starts and stops the music but I don\'t know how to. The method that creates the music i

相关标签:
1条回答
  • 2021-01-24 08:55

    It has nothing to do with sound, it has to do with being able to access the Clip reference. Because you've created local reference to Clip, nothing else will be able to access the reference in order to change the state...

    You need to change the local reference so that it is a class level reference, allowing other methods to interact with it...

    For example...

    protected static Clip clip;
    
    
    public static void backgroundMusic() {
        try {
          if (clip == null) {
              AudioInputStream audio = AudioSystem.getAudioInputStream(new File("SoundFile.wav"));
              clip = AudioSystem.getClip();
              clip.open(audio);
          } 
          if (!clip.isRunning()) {
              clip.start();
          }
        } 
        catch(UnsupportedAudioFileException uae) {
          System.out.println(uae);
        } 
        catch(IOException ioe) { 
          System.out.println(ioe);
        } 
        catch(LineUnavailableException lua) { 
          System.out.println(lua);
        }
    }
    
    public static void stopBackgroundMusic() {
        if (clip != null) {
          clip.stop();
        } 
    }
    

    ps- I've never really dealt with the audio APIs so there might be a few other tweaks you need to make, but this is the basic concept you are after...

    0 讨论(0)
提交回复
热议问题