gpt4 book ai didi

java - 如何向Java程序添加声音

转载 作者:行者123 更新时间:2023-12-03 02:12:57 24 4
gpt4 key购买 nike

我一直在尝试用Java编写基本的“Jeopardy”游戏,现在我正在尝试添加声音,以使玩家得到正确或错误的答案时都能播放。我试图添加声音(将声音文件放置在bin文件夹中并使用下面的代码),但是当我尝试播放文件时没有声音。没有空指针异常。

public class Overview{

static AudioClip right, wrong;

//start the game
public static void guiApp(){

right = Applet.newAudioClip(Jeopardy.class.getResource("correct.wav"));
wrong = Applet.newAudioClip(Jeopardy.class.getResource("wrong.wav"));

right.play();

intro = new Intro();
intro.start();

}

public static void main (String[ ] args)
{
javax.swing.SwingUtilities.invokeLater (new Runnable ( )
{
public void run ( )
{
guiApp();
}
}
);
}

}

以下本质上是在称为的方法中发生的事情:
public class Intro{

public Intro(){

}

public void start(){
JFrame frame = new JFrame();

frame.setSize(100, 100);
frame.setVisible(true);
}
}

最佳答案

这是我用来播放声音的东西。

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

public class SoundPlayer extends Thread
{
private static final int BUFFER_SIZE = 128000;
private static File soundFile;
private static AudioInputStream audioStream;
private static AudioFormat audioFormat;
private static SourceDataLine sourceLine;

private String file;

public static String turn = "data/bell.wav"; //bell sound for black jack when it is your turn (played once each turn)

/**
* Plays the sound of the sent file name
* @param file Audio File's path
*/
public SoundPlayer(String file)
{
super("SoundPlayer");
this.file = file;
start();
}

public void run()
{
String strFilename = file;

try {
soundFile = new File(strFilename);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}

try {
audioStream = AudioSystem.getAudioInputStream(soundFile);
} catch (Exception e){
e.printStackTrace();
System.exit(1);
}

audioFormat = audioStream.getFormat();

DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
try {
sourceLine = (SourceDataLine) AudioSystem.getLine(info);
sourceLine.open(audioFormat);
} catch (LineUnavailableException e) {
e.printStackTrace();
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}

sourceLine.start();

int nBytesRead = 0;
byte[] abData = new byte[BUFFER_SIZE];
while (nBytesRead != -1) {
try {
nBytesRead = audioStream.read(abData, 0, abData.length);
} catch (IOException e) {
e.printStackTrace();
}
if (nBytesRead >= 0) {
@SuppressWarnings("unused")
int nBytesWritten = sourceLine.write(abData, 0, nBytesRead);
}
}
sourceLine.drain();
sourceLine.close();
this.stop();
}

public static void main(String[] args)
{
}

}

关于java - 如何向Java程序添加声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22539651/

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