gpt4 book ai didi

java - 从 JAR 读取音频时出现 NullPointerException

转载 作者:行者123 更新时间:2023-12-02 09:10:18 25 4
gpt4 key购买 nike

我尝试制作一个可运行的 JAR,但由于某种原因我无法玩我的游戏。我做了一些研究并通过命令提示符运行它以尝试找到错误,我在下面得到了这个。显然我知道问题所在,我只需要解决它。我是编程新手,所以不太确定这告诉我什么。

Exception in thread "main" java.lang.NullPointerException
at java.base/java.util.Objects.requireNonNull(Unknown Source)
at java.desktop/javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
at builder.AudioPlayer.playMenuSound(AudioPlayer.java:20)
at builder.Game.<init>(Game.java:56)
at builder.Game.main(Game.java:61)
package builder;

import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

public class AudioPlayer {

private static Clip play;

public static void playMenuSound()
{
try {
//AudioInputStream menuSound = AudioSystem.getAudioInputStream(new File("src/res/introSong.wav")); //Take in audio from res folder
AudioInputStream menuSound = AudioSystem.getAudioInputStream(AudioPlayer.class.getClassLoader().getResourceAsStream("res/introSong.wav"));
play = AudioSystem.getClip(); //
play.open(menuSound); //Play the sound
FloatControl volume = (FloatControl) play.getControl(FloatControl.Type.MASTER_GAIN); //Get control of volume
volume.setValue(1.0f); //0.0 - 1.0 volume
play.loop(Clip.LOOP_CONTINUOUSLY); //Loop once clip is over
}catch (LineUnavailableException | IOException | UnsupportedAudioFileException e){
e.printStackTrace();
}
}

public static void playGameSound()
{
try {
//AudioInputStream gameSound = AudioSystem.getAudioInputStream(new File("src/res/inGame.wav")); //Take in audio from res folder
AudioInputStream gameSound = AudioSystem.getAudioInputStream(AudioPlayer.class.getClassLoader().getResourceAsStream("res/inGame.wav"));
play = AudioSystem.getClip(); //
play.open(gameSound); //Play the sound
FloatControl volume = (FloatControl) play.getControl(FloatControl.Type.MASTER_GAIN); //Get control of volume
volume.setValue(0.5f); //0.0 - 1.0 volume
play.loop(Clip.LOOP_CONTINUOUSLY); //Loop once clip is over
}catch (LineUnavailableException | IOException | UnsupportedAudioFileException e){
e.printStackTrace();
}
}

public static void stopMusic()
{
play.close(); //Stop music
}
}

最佳答案

您的声音文件inGame.wav位于源目录内的res目录中。

当您导出它时,源代码将被编译并复制到 JAR。

这会导致声音文件位于 JAR 内的子目录 res 中。

您尝试读取文件inGame.wav,但您必须读取res/inGame.wav

第二个问题是系统无法在InputStream上设置标记。这可以通过将 getResourceAsStream 更改为 getResource() 来解决。

AudioInputStream menuSound = AudioSystem.getAudioInputStream(AudioPlayer.class.getClassLoader().getResource("res/inGame.wav"));

关于java - 从 JAR 读取音频时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59479397/

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