【发布时间】:2014-06-02 03:05:43
【问题描述】:
这是我第一次发帖,希望我发的正确。
我目前正在为我的项目播放背景歌曲,并且我正在尝试在按下按钮时在背景歌曲之上播放音效。但是,声音没有播放,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,我通过简单地从剪辑中删除静态来找到问题的解决方案。
【问题讨论】:
-
我建议在
Clip变量上使用static不会有帮助 -
测试了您的
Audio类,即使有嫌疑人staticClip参考,它仍然能够相互播放两个声音... -
非常感谢,显然这有助于解决问题。只是出于好奇,你知道为什么会这样吗? (我希望我能投票给你,但我认为我的排名太低了)