我正在使用Netbeans而我只是想编写一个简单的程序(用于实践目的),它将打包的文件流式传输到已编译的.JAR中。在这种情况下,打包文件是一个音频剪辑。
我已经清理并构建了我的项目,并在/ src / package / MyResources /文件夹中包含了我要传输的文件,并且InputStream也指向了相应的位置。
当我在Netbeans中运行调试或“运行项目”时,流工作正常并找到打包的资源。因此播放音频文件。
当我尝试使用“java -jar MyJar.jar”从命令提示符运行已编译的.JAR时,无法再找到打包的资源并抛出IOException。使用归档程序打开.jar会显示资源文件IS与编译前定义的文件夹结构相同。
我不确定是否需要一些代码?但我不明白为什么无法访问打包的资源。
编辑:所以当前的代码应用了很多有用的用户提供的内容:Trouble playing wav in Java
package audioplayer;
import javax.sound.sampled.*;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.IOException;
import javax.sound.sampled.LineEvent.Type;
public class ClipPlayer
{
public static void play()throws UnsupportedAudioFileException, LineUnavailableException, InterruptedException, FileNotFoundException
{
class AudioListener implements LineListener//Sub class that can be used to ensure file completion.
{
//AudioListener ensures that the streamed file finishes streaming (or playing in our case) before the thread can be stopped.
private boolean done=false;
@Override
public synchronized void update(LineEvent event)
{
Type eventType = event.getType();
if (eventType == Type.STOP || eventType == Type.CLOSE)
{
done = true;
notifyAll();
}
}
public synchronized void waitUntilDone() throws InterruptedException
{
while(!done)
{
wait();
}
}
}
try
{
InputStream my_audio=ClipPlayer.class.getClassLoader().getResourceAsStream("Resources/Music/background.wav");
if(my_audio!=null)
{
//Since we are embedding the audio file in the class, we do not need to create a file object.
AudioListener bg_listener = new AudioListener();
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(my_audio);//We create a player with the indicated resource.
try
{
Clip clip = AudioSystem.getClip();//The audio system has the file ready to stream now, we capture that stream.
clip.addLineListener(bg_listener);//Then we add the audiolistener so we ensure completion if something tells the thread to stop.
clip.open(audioInputStream);//Open the stream for playing, we're almost there now.
try
{
clip.start();//Start playing the audio stream. Note this creates a seperate thread.
bg_listener.waitUntilDone();//So we can invoke the listener while the clip is playing.
}
finally //A finally statement is used to ensure the resource stream is properly closed even if an error occurs.
{
clip.close();
}
}
finally //We do the same for the AudioSystem too.
{
audioInputStream.close();
}
}
else
{
throw new FileNotFoundException("File not found.");
}
}
catch(IOException dir)
{
System.err.println("Could not get packaged resource.");
}
}
}
因此,当我在Netbeans中调试或运行时,我没有收到任何错误。当我尝试通过命令行运行程序但是使用java -jar MyClass.jar时,我被告知“无法获取打包资源。”
MyClass.jar包含一行(使用try / catch):
ClipPlayer.play()