Java - 在背景音乐之上播放声音

时间:2014-06-02 03:05:44

标签: java audio javasound

这是我第一次发帖,希望我能正确发布。

我正在为我的项目播放一首背景歌曲,我正试图在按下按钮的同时播放背景歌曲的声音效果。然而,声音没有播放,bgm只是继续。请参阅下面的我的音频课程(忽略不良评论),并提前感谢您的帮助。

package pro;

import java.io.IOException;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

public class Audio
{
    private boolean loop = false;
    private AudioInputStream ais = null;
    private static Clip clip = null;
    //declaration of variables

    public Audio (String fileName, boolean loop)
    //Constructor for the class which fileName and accepts whether the clip needs to loop or not
    {
        this.loop = loop;
        //sets the variable within the class as constructor 

        try {
            clip = AudioSystem.getClip();
            ais = AudioSystem.getAudioInputStream(Audio.class.getResource(fileName));
            clip.open(ais);

        } catch (IOException | UnsupportedAudioFileException | LineUnavailableException e) {
            e.printStackTrace();
        }
        //tries to load file into java's built in audio player, else prints the error to console
    }

    public void musicStart ()
    //starts music
    {
        if (loop)
        {
            clip.loop(Clip.LOOP_CONTINUOUSLY);
            //starts music on loop if loop is requested
        }
        else
        {
            clip.start();
            //starts music as not on loop
        }

    }


    public void musicStop ()
    //stops the music
    {
        clip.stop();
    }

}

编辑:我找到了解决问题的方法,感谢MadProgrammer只需从剪辑中删除静态。

1 个答案:

答案 0 :(得分:2)

摆脱static的{​​{1}}声明。 Clip的每个实例都应该是自包含的并指向它自己的Audio实例

基本上,Clip会使static始终指向最后加载的声音文件,这不是你想要的,因为当你拨打Clip时,你不会知道你真正停止的那个片段,或者你实际上是在停止什么