2014-04-23 5 views
0

사운드 클래스에 대한 설명이 필요합니다. 그래서 Sound 객체 클래스를 만들어 나중에 필요할 때 어떤 소리라도 간단하게 호출 할 수있게되었습니다. 내 파일은 java 파일과 동일한 디렉토리에있는 sounds 폴더에 있습니다. 그래서 ~\Game\sounds\music.wav 이제 주 클래스에서이 코드를 실행하여 개체를 작성하고 호출 할 때마다 파일이 존재하지 않습니다. 파일에 잘못 가리키고 있습니까? 현재 내 fileName"music.wav"입니다. 난 단지 sounds 디렉토리에 하드 코딩하지 않고 디렉토리를 가리키면 모든 CPU에서 작동 할 수 있습니다.자바 디렉토리의 루프 사운드

public Sound(String fileName) { 
     try { 
       File file = new File(fileName); 
       if (file.exists()) { 
        myClip = (AudioClip) Applet.newAudioClip(file.toURI().toURL()); 
       } else { 
        throw new RuntimeException("Sound: file not found: " + fileName); 
       } 
     } catch (MalformedURLException e) { 
      throw new RuntimeException("Sound: malformed URL: " + e); 
     } 
} 
public void play() { 
    myClip.play(); 
} 

답변

1

이 코드가 도움이되기를 바랍니다. 패키지src리소스 아래에 만들었습니다. 리소스 패키지하에 모든 사운드 파일을 저장합니다.

import java.io.*; 
import java.net.URL; 
import javax.sound.sampled.*; 

public enum SoundEffect { 


    BUSY("resources/phone-busy.wav"), 
    CALLING("resources/phone-calling.wav"),   
    DISCONNECT("resources/phone-disconnect.wav"), 
    RING("resources/telephone-ring.wav"); 

    // Each sound effect has its own clip, loaded with its own sound file. 
    private Clip clip; 
    private URL url; 
    private AudioInputStream audioInputStream; 

    // 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. 
      this.url = this.getClass().getClassLoader().getResource(soundFileName); 
      // Set up an audio input stream piped from the sound file. 
      this.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() { 

     clip.loop(Clip.LOOP_CONTINUOUSLY); 

    } 

    public void stop(){ 

     clip.stop(); // Stop the player if it is still running 
     clip.flush(); 
     clip.setFramePosition(0); 
    } 

    // Optional static method to pre-load all the sound files. 
    static void init() { 
     values(); // calls the constructor for all the elements 
    } 

    public boolean isActive(){ 

     return clip.isActive(); 
    } 

    public boolean isOpen() { 

     return clip.isOpen(); 
    } 

    public void setFramePosition() { 
     clip.setFramePosition(0); 

    } 

} 

이 클래스는 스윙 응용 프로그램

import java.awt.*; 
import java.awt.event.*; 

import javax.swing.*; 

// Testing the SoundEffect enum in a Swing application 
@SuppressWarnings("serial") 
public class SoundEffectDemo extends JFrame { 


    // Constructor 
    public SoundEffectDemo() { 
     // Pre-load all the sound files 


     // Set up UI components 
     Container cp = this.getContentPane(); 
     cp.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10)); 

     JButton btnSound1 = new JButton("CALLING"); 
     btnSound1.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       SoundEffect.CALLING.play(); 
      } 
     }); 
     cp.add(btnSound1); 

     JButton btnSound2 = new JButton("RING"); 
     btnSound2.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       SoundEffect.RING.play(); 
      } 
     }); 
     cp.add(btnSound2); 

     JButton btnSound3 = new JButton("BUSY"); 
     btnSound3.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 

       SoundEffect.BUSY.play(); 
      } 
     }); 
     cp.add(btnSound3); 

     JButton btnSound4 = new JButton("Stop Sound "); 
     btnSound4.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       for(SoundEffect value : SoundEffect.values()){ 
        if(value.isActive()){ 
         value.stop(); 
        } 
       } 

      } 
     }); 
     cp.add(btnSound4); 


     this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     this.setTitle("Test SoundEffct"); 
     this.pack(); 
     this.setVisible(true); 
    } 

    public static void main(String[] args) { 
     new SoundEffectDemo(); 
    } 
} 
에 SoundEffect 열거 테스트입니다