2013-07-28 4 views
0

의 Runnable JAR 파일로 내보낼 때 실행되지 않습니다 : 나는 실행 가능한 JAR를 실행하면, 프레임이 올바른 크기로 열립니다프로그램은 이클립스에서 완전히 실행하지만이처럼 보이는 메인 클래스가

package complete; 

import java.io.File; 
import java.io.*; 
import javax.sound.sampled.*; 
import javax.sound.sampled.AudioFormat; 
import javax.sound.sampled.AudioInputStream; 
import javax.sound.sampled.AudioSystem; 
import javax.sound.sampled.BooleanControl; 
import javax.sound.sampled.DataLine; 
import javax.sound.sampled.FloatControl; 
import javax.sound.sampled.SourceDataLine; 
import javax.swing.JFrame; 

public class Main { 

public static void main(String[] args) { 
    JFrame frame = new JFrame("Presentation"); 
    frame.setSize(806, 506); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setResizable(false); 
    frame.add(new GameFrame()); 
    frame.setVisible(true); 
sound = new File("Assets/BackgroundSound.wav"); // Write you own file location here and be aware that it need to be an .wav file 

    new Thread(play).start(); 
} 

static File sound; 
static boolean muted = false; // This should explain itself 
static float volume = 100.0f; // This is the volume that goes from 0 to 100 
static float pan = 0.0f; // The balance between the speakers 0 is both sides and it goes from -1 to 1 

static double seconds = 0.0d; // The amount of seconds to wait before the sound starts playing 

static boolean looped_forever = true; // It will keep looping forever if this is true 

static int loop_times = 0; // Set the amount of extra times you want the sound to loop (you don't need to have looped_forever set to true) 
static int loops_done = 0; // When the program is running this is counting the times the sound has looped so it knows when to stop 

final static Runnable play = new Runnable() // This Thread/Runnabe is for playing the sound 
{ 
    public void run() 
    { 
     try 
     { 
      // Check if the audio file is a .wav file 
      if (sound.getName().toLowerCase().contains(".wav")) 
      { 
       AudioInputStream stream = AudioSystem.getAudioInputStream(sound); 

       AudioFormat format = stream.getFormat(); 

       if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) 
       { 
        format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 
          format.getSampleRate(), 
          format.getSampleSizeInBits() * 2, 
          format.getChannels(), 
          format.getFrameSize() * 2, 
          format.getFrameRate(), 
          true); 

        stream = AudioSystem.getAudioInputStream(format, stream); 
       } 

       SourceDataLine.Info info = new DataLine.Info(
         SourceDataLine.class, 
         stream.getFormat(), 
         (int) (stream.getFrameLength() * format.getFrameSize())); 

       SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info); 
       line.open(stream.getFormat()); 
       line.start(); 

       // Set Volume 
       FloatControl volume_control = (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN); 
       volume_control.setValue((float) (Math.log(volume/100.0f)/Math.log(10.0f) * 20.0f)); 

       // Mute 
       BooleanControl mute_control = (BooleanControl) line.getControl(BooleanControl.Type.MUTE); 
       mute_control.setValue(muted); 

       FloatControl pan_control = (FloatControl) line.getControl(FloatControl.Type.PAN); 
       pan_control.setValue(pan); 

       long last_update = System.currentTimeMillis(); 
       double since_last_update = (System.currentTimeMillis() - last_update)/1000.0d; 

       // Wait the amount of seconds set before continuing 
       while (since_last_update < seconds) 
       { 
        since_last_update = (System.currentTimeMillis() - last_update)/1000.0d; 
       } 

       //System.out.println("Playing!"); 

       int num_read = 0; 
       byte[] buf = new byte[line.getBufferSize()]; 

       while ((num_read = stream.read(buf, 0, buf.length)) >= 0) 
       { 
        int offset = 0; 

        while (offset < num_read) 
        { 
         offset += line.write(buf, offset, num_read - offset); 
        } 
       } 

       line.drain(); 
       line.stop(); 

       if (looped_forever) 
       { 
        new Thread(play).start(); 
       } 
       else if (loops_done < loop_times) 
       { 
        loops_done++; 
        new Thread(play).start(); 
       } 
      } 
     } 
     catch (Exception ex) { ex.printStackTrace(); } 
    } 
}; 



} 

제목이 있지만 빈 화면이 있습니다. 나는 JAR 모든 클래스, 이미지와 WAV 파일에서 파일이있는 압축을 푼

java.io.FileNotFoundException: Assets\BackgroundSound.wav <The system cannot find the path specified> 

at java.io.FileInputStream.open<Native Method> 

at java.io.FileInputStream.<init><Unknown Source> 

at com.sun.media.sound.WaveFloatFileReader.getAudioInputStream<Unknown Source> 

at javax.sound.sampled.AudioSystem.getAudioInputStream<Unknown Source> 

at complete.Main$1.run<Main.Java:50> 

at java.lang.Thread.run<Unknown Source> 

: 나는 명령 줄에서 실행하면

나는이 오류가 발생합니다.

Main 클래스에서 사운드 섹션을 제거하고 Eclipse에서 실행하면 프로그램이 소리없이 정상적으로 실행됩니다.

이 버전을 Runnable JAR로 내보낼 때 명령 줄 오류가없는 것 외에는 실행하려고 할 때 이전과 같은 결과가 발생합니다.

답변

0

jar 파일을로드하려면 getResources 또는 getResourceAsStream을 사용해야합니다.

0

사용 :

sound = new File(Main.class.getResource("Assets/BackgroundSound.wav").getPath()); 
+0

내 사운드 파일이 정적이므로 this.getClass()를 사용할 수 없습니다. –

+0

@justprogrammingsomething 내 업데이트를 참조하십시오. – Mac

+0

자원이 JAR 파일에있는 경우에는 작동하지 않습니다. 이 경우 URL getResource는 jar : file : URL이되고 File 생성자는 예외를 throw합니다. –

0

sound에 대한 데이터를 직접 디스크에있는 파일에 포함되어 있지; 프로젝트의 jar 파일 안에 있습니다. 따라서 File을 사용하여 액세스하는 것은 올바르지 않습니다. 당신은 Class.getResourceAsStream(String name)를 사용하여 InputStream를 얻을 수

public static AudioInputStream getAudioInputStream(InputStream stream) 
             throws UnsupportedAudioFileException, 
               IOException 

Obtains an audio input stream from the provided input stream. The stream must point to valid audio file data. The implementation of this method may require multiple parsers to examine the stream to determine whether they support it. These parsers must be able to mark the stream, read enough data to determine whether they support the stream, and, if not, reset the stream's read pointer to its original position. If the input stream does not support these operation, this method may fail with an IOException.

대신, 오버로드 AudioStream 방법을 사용합니다. 그러면 클래스 경로를 살펴볼 것이므로 Eclipse와 jar 파일에서 모두 작동하도록 설정할 수 있습니다. - 내가 마지막 부분을 편집 할 필요 -이 모든 main 있다는 잊었 죄송합니다

InputStream soundResource = Main.class.getResourceAsStream("BackgroundSound.wav"); 
AudioInputStream ais = AudioSystem.getAudioInputStream(soundResource); 

을 : 당신은 그냥 사용할 수 있도록 가장 쉬운, 당신의 클래스 파일과 함께 할 사운드 파일을 이동하는 것입니다. 가장 사소한 프로그램을 제외하고는 그렇게하지 마십시오. 대신 클래스를 인스턴스화하고 인스턴스에서 작업을 수행하십시오. 그리고 클래스 이름을 Main에서 SoundDemo으로 변경하십시오. 그렇지 않으면 3 개월 후에 스스로에게 "Java 재생 사운드 학습 방법에 대한 연습은 어디에서 했습니까? 파일은 무엇입니까? Main에 있었습니까?"라고 말할 것입니다.

관련 문제