启动和背景音乐停止 [英] Starting and stopping music in background

查看:207
本文介绍了启动和背景音乐停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做一个游戏,有背景音乐在里面。我想添加一个静音按钮启动和停止音乐,但我不知道怎么样。创建音乐的方法是:

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);
    }
}

我想要做的就是在我的按钮操作处理程序,我想补充一个静音键启动,如果用户停止高兴的声音。因此,这将是这样的:if(e.getSource()== muteButton){//启动和停止音乐}

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 }

我将如何去这样做呢?感谢您的帮助!

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. 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...

例如...

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-我从来没有真正处理的音频API的所以有可能是你需要做一些其他的调整,但这是基本的概念,你是...后

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...

这篇关于启动和背景音乐停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆