gpt4 book ai didi

java - 在eclipse中播放ogg文件

转载 作者:行者123 更新时间:2023-12-01 14:23:37 26 4
gpt4 key购买 nike

所以我正在尝试为我的乒乓球游戏添加声音,但由于某种原因我似乎无法播放声音......没有错误消息,这意味着路径是正确的,但声音只是不要玩。

以下是我的背景音乐代码,剪掉了所有乒乓球的东西,在此先感谢~

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

最佳答案

这是一个使用 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 中调用此类,即可在后台播放音乐。

关于java - 在eclipse中播放ogg文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22749909/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com