게임용 사운드 코드 작업 중입니다. 그리고 난 다음 코드를 사용했다 :* .wav 파일은 디렉토리에서 어디에서 살 필요가 있습니까?
import java.io.*;
import java.net.URL;
import javax.sound.sampled.*;
/**
* This enum encapsulates all the sound effects of a game, so as to separate the sound playing
* codes from the game codes.
* 1. Define all your sound effect names and the associated wave file.
* 2. To play a specific sound, simply invoke SoundEffect.SOUND_NAME.play().
* 3. You might optionally invoke the static method SoundEffect.init() to pre-load all the
* sound files, so that the play is not paused while loading the file for the first time.
* 4. You can use the static variable SoundEffect.volume to mute the sound.
*/
public enum SoundEffect {
EXPLODE("explode.wav"), // explosion
GONG("gong.wav"), // gong
SHOOT("shoot.wav"); // bullet
// Nested class for specifying volume
public static enum Volume {
MUTE, LOW, MEDIUM, HIGH
}
public static Volume volume = Volume.LOW;
// Each sound effect has its own clip, loaded with its own sound file.
private Clip clip;
// Constructor to construct each element of the enum with its own sound file.
SoundEffect(String soundFileName) {
try {
// Use URL (instead of File) to read from disk and JAR.
URL url = this.getClass().getClassLoader().getResource(soundFileName);
// Set up an audio input stream piped from the sound file.
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(url);
// Get a clip resource.
clip = AudioSystem.getClip();
// Open audio clip and load samples from the audio input stream.
clip.open(audioInputStream);
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
// Play or Re-play the sound effect from the beginning, by rewinding.
public void play() {
if (volume != Volume.MUTE) {
if (clip.isRunning())
clip.stop(); // Stop the player if it is still running
clip.setFramePosition(0); // rewind to the beginning
clip.start(); // Start playing
}
}
// Optional static method to pre-load all the sound files.
static void init() {
values(); // calls the constructor for all the elements
}
}
지금 나는 내 자신과 코드에서 나와 * .WAV 파일 중 하나를 교체 할 때, 심지어 위의 코드에서 나열된 파일 이름에 내 자신의 하나의 이름을 지정합니다. 널 읽을되지 않는 나에게 * .wav 파일 자체를 말하고있는의 것입니다 스택 URL URL을 다음에서
Exception in thread "main" java.lang.ExceptionInInitializerError
at soundTest.main(soundTest.java:19)
Caused by: java.lang.NullPointerException
at com.sun.media.sound.StandardMidiFileReader.getSequence(Unknown Source)
at javax.sound.midi.MidiSystem.getSequence(Unknown Source)
at com.sun.media.sound.SoftMidiAudioFileReader.getAudioInputStream(Unknown Source)
at javax.sound.sampled.AudioSystem.getAudioInputStream(Unknown Source)
at SoundEffect.<init>(sfx.java:75)
at SoundEffect.<clinit>(sfx.java:55)
: 나는 다음과 오류가 나타납니다.
다음 줄을 시도했지만 예. * .wav 파일이있었습니다 (동일한 이름의 세 항목을 가질 수 없다는 것을 알고 있습니다. 나는 그 중 하나를 사용하고, 주석을 달고 다시 시도해보십시오. src 폴더에 패키지 (기본값)와 디렉토리에있는 파일의 복사본을 배치,
TEST("file://C:/shoot.wav");
TEST("/soundTest/shoot.wav");
TEST("shoot.wav");
을뿐만 아니라 : 또 다른 하나는, 난 그냥가 "//"로 만들려면)이 읽기 쉽게 제거 물론 루트 (c :)에 있습니다.
나는 모든 표준 자바, 기본 코드 만에 여기서 열거 내 주요 문에 envoking하고 방법 : 정확히 * .wav 파일을 수행
SoundEffect.SHOOT.play();
그가 디렉토리 INT에 있어야합니다 ? 또는 다른 문제가 있다면 놓치기 때문에 지적하십시오. 또한 Windows 8.1에서 Eclipse IDE "Kepler"를 사용하고 있습니다. 나는 게시 된 코드가 내가 지금까지 가지고있는 것임을 주목하고 싶다.
예제에 따라 파일을 기본 패키지에 저장해야합니다. 말하자면 Eclipse를 믿는다면 프로젝트 루트에 "resources"폴더를 만들고 Jar에 포함시킬 리소스를 배치해야합니다. – MadProgrammer
@MadProgrammer 그래서이 문제가 잘못 되었다면 필자를 바로 잡아라, 나는 파일을 package_Name에 끌어서 놓을 수있다. 그런 다음 주석이 말하는 것처럼 그냥 호출한다? 나는 그와 같은 오류를 시도했기 때문에. – user3247187
이클립스를 제대로 이해했다면 (프로젝트 사용자가 아님) 프로젝트의 최상위 레벨에 "resources"디렉토리를 만들어야합니다. 이 경우,'SoundEffect'의 패키지 구조와 같은 디렉토리 구조를 생성해야합니다. 그럼, 당신의 파일을 깨끗하고 빌드 ... 손가락을 넘어 – MadProgrammer