2013-10-15 2 views
0

저는이 문제에 대한 해결책을 찾고 있었지만 도움이되지는 않습니다.항아리에서 파일을로드하는 중 문제가 발생했습니다.

내 soundSound 메서드에서 사용할 수 있도록 파일 ("soundfile.wav")을로드하려고합니다. jar 파일을 내보낼 때 jar 파일에서로드하려고하므로 다운로드 할 때 파일을 볼 수 없습니다.

package soundplayer; 

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.sound.sampled.*; 
import javax.swing.*; 

import java.io.*; 

public class SoundPlayer extends JFrame 
{ 
    private static final long serialVersionUID = 1L; 

    public String code = "up up down down left right left right b a"; 
    static SoundPlayer soundPlayer; 

    public static void main(String[] args) 
    { 
     soundPlayer = new SoundPlayer(); 
     soundPlayer.setVisible(true); 
    } 

    public SoundPlayer() 
    { 
     //Look and feel 
     String lookAndFeel = UIManager.getSystemLookAndFeelClassName(); 
     try { 
     UIManager.setLookAndFeel(lookAndFeel); 
     } catch (ClassNotFoundException | InstantiationException| IllegalAccessException | UnsupportedLookAndFeelException e2) {e2.printStackTrace();} 

     //Window Stuff 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setBounds(50, 50, 250, 80); 
     setTitle("Sound Player Test"); 
     getContentPane().setLayout(null); 

     //Components 
     final JTextField typingArea = new JTextField(1); 
     typingArea.setText("up up down down left right left right b a"); 
     typingArea.setBounds(10, 10, 100, 25); 
     getContentPane().add(typingArea); 

     final JLabel label = new JLabel("Now playing: "); 
     label.setBounds(10, 40, 400, 25); 
     label.setVisible(false); 
     getContentPane().add(label); 

     JButton button = new JButton("Check"); 
     button.addActionListener(new ActionListener() 
     { 
      public void actionPerformed(ActionEvent e) 
      { 
       if(typingArea.getText().equals(code)) 
       { 
        setBounds(50, 50, 250, 110); 
        label.setVisible(true); 
        File file = new File("sound.wav"); 
        playSound(file); 
       } 
      } 
     }); 
     button.setBounds(125, 10, 100, 25); 
     getContentPane().add(button); 
    } 

    public static void playSound(File file) 
    { 
     try 
     { 
      Clip clip = AudioSystem.getClip(); 
      clip.open(AudioSystem.getAudioInputStream(file)); 
      clip.start(); 
     } 
     catch (Exception exc) 
     { 
      exc.printStackTrace(System.out); 
     } 
    } 
} 

답변

2

문제는 라인

File file = new File("sound.wav"); 

이 파일 시스템에 직접 액세스하는 것이다. JAR에서 리소스를로드하는 것이 좋습니다. 이이 클래스 로더를 사용하여 수행 할 수 있습니다

getClass().getResource("sound.wav"); 

그런 다음 당신이 꺼내,에 파일을 통과하지 않도록,뿐만 아니라는 getInputStream를 제공하는 자원,하지만 자원이있을 것이다.

관련 문제