简体   繁体   English

在后台启动和停止音乐

[英]Starting and stopping music in background

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 is: 产生音乐的方法是:

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

What I want to do is in my action handler for the button, I want to add a mute button that starts and stops the audio if the user pleases. 我想做的是在按钮的动作处理程序中,我想添加一个静音按钮,如果用户愿意,可以启动和停止音频。 So it would be like: if(e.getSource() == muteButton) { //Starts and stops music } 就像:if(e.getSource()== MutantButton){//开始和停止音乐}

How would I go about doing this? 我将如何去做呢? Thanks for your help! 谢谢你的帮助!

It has nothing to do with sound, it has to do with being able to access the Clip reference. 它与声音无关,与能够访问Clip引用有关。 Because you've created local reference to Clip , nothing else will be able to access the reference in order to change the state... 因为您已经创建了Clip本地引用,所以其他任何人都无法访问该引用以更改状态...

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... ps-我从来没有真正处理过音频API,因此可能还需要进行一些其他调整,但这是您要遵循的基本概念...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM