所以我试图在我的乒乓球游戏中添加声音,但由于某些原因我似乎无法发出声音......没有错误信息,这意味着路径是正确的,但声音根本就没有发挥。
以下是我的背景音乐代码,所有的pong东西都被剪掉了,提前谢谢〜
import java.applet.Applet;
import java.applet.AudioClip;
import java.net.URL;
import javax.swing.JApplet;
import javax.swing.JPanel;
public class pong1 extends JPanel {
static AudioClip music;
static URL path; // soundfile path
public static void main(String[] args) {
path = pong1.class.getResource("Battle2.ogg"); // change url
music = Applet.newAudioClip(path); // load sound
music.loop();
}
}
答案 0 :(得分:2)
这是一个使用javazoom library播放OGG文件的类:
import java.io.File;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
import javazoom.spi.PropertiesContainer;
public class OGGPlayer {
public final String fileName;
public boolean mustStop = false;
public OGGPlayer(String pFileName) {
fileName = pFileName;
}
public void play() throws Exception {
mustStop = false;
File file = new File(fileName);
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
if (audioInputStream == null) {
throw new Exception("Unable to get audio input stream");
}
AudioFormat baseFormat = audioInputStream.getFormat();
AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
baseFormat.getSampleRate(), 16, baseFormat.getChannels(),
baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false);
AudioInputStream decodedAudioInputStream = AudioSystem.getAudioInputStream(decodedFormat,
audioInputStream);
if (!(decodedAudioInputStream instanceof PropertiesContainer)) {
throw new Exception("Wrong PropertiesContainer instance");
}
DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, decodedFormat);
SourceDataLine sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
sourceDataLine.open(decodedFormat);
byte[] tempBuffer = new byte[4096];
// Start
sourceDataLine.start();
int nbReadBytes = 0;
while (nbReadBytes != -1) {
if (mustStop) {
break;
}
nbReadBytes = decodedAudioInputStream.read(tempBuffer, 0, tempBuffer.length);
if (nbReadBytes != -1)
sourceDataLine.write(tempBuffer, 0, nbReadBytes);
}
// Stop
sourceDataLine.drain();
sourceDataLine.stop();
sourceDataLine.close();
decodedAudioInputStream.close();
audioInputStream.close();
}
public void setMustStop(boolean pMustStop) {
mustStop = pMustStop;
}
public void stop() {
mustStop = true;
}
}
只需在应用的新Thread
中调用此课程,即可在后台播放音乐。