2012-10-02 5 views
1

프로그램에 사운드를 추가하려고합니다. 프로그램에 사운드를 추가하는 방법에 대한 경험이 없습니다. 이 코드는 예외이지만 "null"을 지정하려고합니다. 나는 playSound 함수에서 어떤 인수를 전달해야하는지 모른다. 그래서 제발 도와주세요.프로그램에 사운드를 추가하는 방법은 무엇입니까?

import java.io.InputStream; 
import sun.audio.*; //import the sun.audio package 
import java.io.*; 
import javax.sound.sampled.AudioInputStream; 
import javax.sound.sampled.AudioSystem; 
import javax.sound.sampled.Clip; 

public class Main { 

    public Main() { 

    } 

    public static void main(String[] args) { 
     System.out.println("hello there"); 
     playSound("Hi there"); 

    } 

    public static synchronized void playSound(final String url) { 
     new Thread(new Runnable() { // the wrapper thread is unnecessary, unless 
            // it blocks on the Clip finishing, see 
            // comments 
        public void run() { 
         try { 
          Clip clip = AudioSystem.getClip(); 
          AudioInputStream inputStream = AudioSystem 
            .getAudioInputStream(Main.class 
              .getResourceAsStream("pacman_chomp.wav" 
                + url)); 
          clip.open(inputStream); 
          clip.start(); 
         } catch (Exception e) { 
          System.err.println(e.getMessage()); 
         } 
        } 
       }).start(); 
    } 

} 
+1

Null 어디서? 어느 선 이요? – OscarRyz

+0

.wav 파일이나 다른 사운드 파일에 대한 경로를 지정해야합니다. –

+0

@ console ... 두 번째 줄 "null"에 "Hello there"가 인쇄됩니다. – OOkhan

답변

1

당신 꺼내, 방법이 작동하지 않았다 때문에, 여기로의 내가 코딩 한 ound 클래스. 여기

import java.io.IOException; 
import java.io.InputStream; 

import javax.sound.sampled.AudioFormat; 
import javax.sound.sampled.AudioInputStream; 
import javax.sound.sampled.AudioSystem; 
import javax.sound.sampled.DataLine; 
import javax.sound.sampled.LineUnavailableException; 
import javax.sound.sampled.SourceDataLine; 
import javax.sound.sampled.UnsupportedAudioFileException; 

public class AePlayWave extends Thread { 

    protected static final boolean DEBUG = false; 

    protected InputStream inputStream; 

    public AePlayWave(InputStream inputStream) { 
     this.inputStream = inputStream; 
     if (DEBUG) System.out.println("AePlayWave constructor"); 
    } 

    @Override 
    public void run() { 
     if (DEBUG) System.out.println("AePlayWave running"); 

     AudioInputStream audioInputStream = verifyInputStream(); 
     if (audioInputStream == null) { 
      return; 
     } 

     AudioFormat format = audioInputStream.getFormat(); 
     SourceDataLine audioLine = openInputStream(format); 

     if (DEBUG) System.out.println(audioLine.getLineInfo()); 

     if (audioLine != null) { 
      audioLine.start(); 
      playInputStream(audioInputStream, audioLine); 
     } 
    } 

    protected AudioInputStream verifyInputStream() { 
     if (DEBUG) System.out.println("AePlayWave verifyInputStream"); 
     AudioInputStream audioInputStream = null; 
     try { 
      audioInputStream = AudioSystem.getAudioInputStream(inputStream); 
     } catch (UnsupportedAudioFileException e) { 
      e.printStackTrace(); 
      return null; 
     } catch (IOException e) { 
      e.printStackTrace(); 
      return null; 
     } 
     return audioInputStream; 
    } 

    protected SourceDataLine openInputStream(AudioFormat format) { 
     if (DEBUG) System.out.println("AePlayWave openInputStream"); 
     DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); 
     SourceDataLine audioLine = null; 
     if (DEBUG) System.out.println("AePlayWave openInputStream try"); 
     try { 
      audioLine = (SourceDataLine) AudioSystem.getLine(info); 
      if (DEBUG) System.out.println("AePlayWave openInputStream getLine"); 
      audioLine.open(format); 
      if (DEBUG) System.out.println("AePlayWave openInputStream open"); 
     } catch (LineUnavailableException e) { 
      e.printStackTrace(); 
      return null; 
     } catch (Exception e) { 
      e.printStackTrace(); 
      return null; 
     } 
     return audioLine; 
    } 

    protected void playInputStream(AudioInputStream audioInputStream, 
      SourceDataLine audioLine) { 
     if (DEBUG) System.out.println("AePlayWave playInputStream"); 
     int externalBufferSize = (int) audioInputStream.getFrameLength() * 4; 
     if (DEBUG) System.out.println("AePlayWave playInputStream externalBufferSize: " 
       + externalBufferSize); 
     int nBytesRead = 0; 
     byte[] abData = new byte[externalBufferSize]; 

     try { 
      while (nBytesRead != -1) { 
       nBytesRead = audioInputStream.read(abData, 0, abData.length); 
       if (nBytesRead >= 0) { 
        if (DEBUG) System.out.println("Bytes read: " + nBytesRead); 
        audioLine.write(abData, 0, nBytesRead); 
       } 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
      return; 
     } finally { 
      audioLine.drain(); 
      audioLine.close(); 
     } 
    } 
} 

그리고 그것이라고 방법은 다음과 같습니다

InputStream inputStream = getClass().getResourceAsStream("alarm-clock-1.wav"); 
AePlayWave playWave = new AePlayWave(inputStream); 
playWave.run(); 
+0

남자 : ( – OOkhan

+0

)이 라인에 오류가 발생했습니다 InputStream inputStream = getClass(). getResourceAsStream ("alarm-clock-1. Error = "Object 유형에서 정적이 아닌 메서드 getClass()에 정적 참조를 만들 수 없습니다." 응답에 대한 감사합니다. – OOkhan

0

클립은 긴 오디오 파일을 허용하지 않습니다. 내 게임 엔진에 속하는 클래스를 참조하십시오. WavPlayer WavSound

SoundState

그런 다음이 코드를 사용합니다.

// First load the sound 
WavSound snd = WavPlayer.loadSound("pacman_chomp.wav"); 
// play it then 
snd.play(); 

무료로 사용할 수 있습니다. 그들이 도움이되기를 바랍니다.

1

파일을 찾을 수 없어서 널 예외가 발생했을 수 있습니다. 순간 그것은라는 파일을 찾고 있습니다 :

"이 pacman_chomp.wavHi"URL의 값이 "안녕하세요"로 설정되고 있으며,이처럼 구성되어 있기 때문에

:

AudioInputStream inputStream = AudioSystem 
            .getAudioInputStream(Main.class 
              .getResourceAsStream("pacman_chomp.wav" 
                + url)); 

난 당신이 경우는 "+ URL을"제거하는 파일 ""pacman_chomp.wav을? "원하는 가정.

+0

글쎄 크리스가 응답 해 주셔서 감사합니다. 파일 이름이 pacman_chomp.wave 맞지만 작동하지 않습니다. ( – OOkhan

+0

올바른 위치에 있습니까? "Main.class"파일과 동일한 위치에있는 파일을 찾을 것입니다 –

+0

파일이 있습니다. – OOkhan

0
playSound("pacman_chomp.wav"); 


public static synchronized void playSound(final String url) { 
    new Thread(new Runnable() { // the wrapper thread is unnecessary, unless 
           // it blocks on the Clip finishing, see 
           // comments 
       public void run() { 
        try { 
         Clip clip = AudioSystem.getClip(); 
         AudioInputStream inputStream = AudioSystem 
           .getAudioInputStream(Main.class 
             .getResourceAsStream(url)); 
         clip.open(inputStream); 
         clip.start(); 
        } catch (Exception e) { 
         System.err.println(e.getMessage()); 
        } 
       } 
      }).start(); 
} 

A : 그것은 "이 pacman_chomp.wavHi"

B를 찾습니다 위에서 언급 한 바와 같이 : 하드 코딩 여기에 사용하지 않는 것이 좋습니다. 당신은 코드를 재사용 할 능력을 잃게됩니다. 당신이 꺼내, 방법에 하드 코딩하는 경우 예를 들어, 당신은이 작업을 수행 할 수 없습니다뿐만 아니라

playSound("pacman_chomp.wav"); 
    playSound("pacman_dies.wav"); 

, 메소드 이름 "꺼내,"그것은 항상 pacman_chomp을 담당 할 것입니다 때문에 제대로 (하드 코딩 된 파일)라는된다 파일 (올바르게 지적 된 경우).

c : 어쨌든 "안녕하세요"의 목적은 무엇입니까?

+0

프로그램에 Sound를 추가하는 방법을 테스트하고 있습니다. 잘 모르겠습니다. 이 URL 인수는 무엇입니까? 그래서 그냥 "안녕하세요"문자열을 보냅니다. 내가 성공하면 내 메인 프로그램에 소리가 추가됩니다. 희망을 갖고 있기 때문에 ... 영어가 유감입니다. – OOkhan

+0

URL은 파일이므로 클래스와 동일한 디렉토리에 파일이 있으면 "pacman_chop.wav"를 인수로 입력 할 수 있습니다. – tehdoommarine

+0

이 작업을 수행했지만 작동하지 않습니다 ... – OOkhan

관련 문제