用户使用单选按钮选择一个并按下播放按钮后播放声音剪辑的简单 GUI 应用程序。清理和构建后,从 JAR 文件执行会导致在选择剪辑并按下播放按钮时不播放声音。
条件:NetBeans IDE,声音在包路径的 IDE 中成功播放,JAR 中 .wav 文件的路径正确,文件在 JAR 中的正确目录中,使用 2 个类:一个用于 GUI,一个 .wav 处理程序类(两者都在 IDE 中成功运行。屏幕截图中的更多详细信息。
用于调用资源的代码片段(这在 IDE 中运行良好,因此没有问题):
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
if (jRadioButton1.isSelected()){
URL file = QuotesButtonUI.class.getResource("/my/sounds/fear_converted.wav");
new Player (file.getFile()).start();
}
else if (jRadioButton2.isSelected()){
URL file = QuotesButtonUI.class.getResource("/my/sounds/initiated_converted.wav");
new Player (file.getFile()).start();
}
这是用于处理 .wav 的 Player 类。在 GUI 类中,我使用了 new Player().start() 调用。我在想 Player 类中应该有一个 getResource() 调用,但我不确定。
package my.quotesbutton;
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.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
public class Player extends Thread {
private String filename;
private Position curPosition;
private final int EXTERNAL_BUFFER_SIZE = 524288; // 128Kb
enum Position {
LEFT, RIGHT, NORMAL
};
public Player(String wavfile) {
filename = wavfile;
curPosition = Position.NORMAL;
}
public Player(String wavfile, Position p) {
filename = wavfile;
curPosition = p;
}
public void run() {
File soundFile = new File(filename);
if (!soundFile.exists()) {
System.err.println("Wave file not found: " + filename);
return;
}
AudioInputStream audioInputStream = null;
try {
audioInputStream = AudioSystem.getAudioInputStream(soundFile);
} catch (UnsupportedAudioFileException e1) {
e1.printStackTrace();
return;
} catch (IOException e1) {
e1.printStackTrace();
return;
}
AudioFormat format = audioInputStream.getFormat();
SourceDataLine auline = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
try {
auline = (SourceDataLine) AudioSystem.getLine(info);
auline.open(format);
} catch (LineUnavailableException e) {
e.printStackTrace();
return;
} catch (Exception e) {
e.printStackTrace();
return;
}
if (auline.isControlSupported(FloatControl.Type.PAN)) {
FloatControl pan = (FloatControl) auline
.getControl(FloatControl.Type.PAN);
if (curPosition == Position.RIGHT)
pan.setValue(1.0f);
else if (curPosition == Position.LEFT)
pan.setValue(-1.0f);
}
auline.start();
int nBytesRead = 0;
byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
try {
while (nBytesRead != -1) {
nBytesRead = audioInputStream.read(abData, 0, abData.length);
if (nBytesRead >= 0)
auline.write(abData, 0, nBytesRead);
}
} catch (IOException e) {
e.printStackTrace();
return;
} finally {
auline.drain();
auline.close();
}
}
}