我制作了一个程序,在某个事件发生时播放.wav文件。我的问题是,一旦我将它导出到.jar文件,我不认为音频仍然可用,因为当我将文件移动到另一个文件夹时路径甚至失败。我怎样才能使导出的jar可以被其他人下载,声音仍然可以播放。这是我用来播放声音的代码:
package one;
import java.io.*;
import java.net.URL;
import sun.audio.*;
/**
* A simple Java sound file example (i.e., Java code to play a sound file)
*/
public class Sound extends Thread
{
public void play(String address)
throws Exception
{
// open the sound file as a Java input stream
String soundfile = address;
InputStream in = new FileInputStream(soundfile);
// create an audiostream from the inputstream
AudioStream audioStream = new AudioStream(in);
// play the audio clip with the audioplayer class
AudioPlayer.player.start(audioStream);
}
}
我在另一个类中创建了这个类的对象,并将其链接提供给文件:
try {
sound = new Sound();
sound.play("/Users/ekurt/Documents/coding/projects or exercise/Java Files/Ultimate Study Timer/study.wav");
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
编辑: 我试过这个
sound = new Sound();
InputStream i = TimerField.class.getResourceAsStream("/Users/ekurt/Documents/coding/projects or exercise/Java Files/Ultimate Study Timer/untitled.wav");
sound.play(i);
我修改了Sound类来改为使用InputStream。
public void play(InputStream address)
throws Exception
{
// open the sound file as a Java input stream
// String soundfile = address;
// InputStream in = new FileInputStream(soundfile);
// create an audiostream from the inputstream
AudioStream audioStream = new AudioStream(address);
// play the audio clip with the audioplayer class
AudioPlayer.player.start(audioStream);
}
我不知道jar中的音频文件在哪里。我在eclipse中使用了export函数并导出为runnable jar。
编辑2:
我将尝试澄清一下我的问题。我目前正在eclipse中运行该程序。我知道如果声音文件在其他地方,我现在使用的代码将无效。我的问题是,如果我导出为jar,我认为如果我将其发送给其他人,那个人将无法运行代码,因为提供文件位置的字符串仅适用于声音文件正确的文件夹。
那么我如何制作它以便将声音文件打包在jar中并且代码可以在任何地方播放声音?