有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

我正在为我的项目播放一首背景曲,当按下背景曲上方的一个按钮时,我正在尝试播放音效。然而,声音没有播放,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) 个答案

  1. # 1 楼答案

    去掉Clipstatic声明。Audio的每个实例都应该是自包含的,并指向它自己的Clip实例

    基本上,static将使Clip始终指向加载的最后一个声音文件,这并不是您真正想要的,因为当您调用stopMusic时,您将不知道您真正停止了哪个剪辑,或者您是否真的停止了任何东西