2012-09-25 5 views
0

Java 데스크톱 응용 프로그램에서 사운드 (.wma, .mp3와 같은 형식의 음악 파일)를 어떻게 재생합니까? (애플릿이 아님)Java Desktop 응용 프로그램에서 사운드 재생

다음 코드 (Stack Overflow에 대한 다른 질문에서 가져온 것)를 사용했지만 Exception을 발생시킵니다.

public class playsound { 
    public static void main(String[] args) { 
s s=new s(); 
s.start(); 
    } 
} 
class s extends Thread{ 
    public void run(){ 
     try{ 
      InputStream in = new FileInputStream("C:\\Users\\srgf\\Desktop\\s.wma"); 
     AudioStream as = new AudioStream(in); //line 26 
      AudioPlayer.player.start(as); 
     } 
     catch(Exception e){ 
      e.printStackTrace(); 
      System.exit(1); 
     } 
    } 
} 

실행은 다음 예외가 발생합니다 프로그램 :

java.io.IOException: could not create audio stream from input stream 
    at sun.audio.AudioStream.<init>(AudioStream.java:82) 
    at s.run(delplaysound.java:26) 
+0

http://stackoverflow.com/questions/5667454/playing-audio-file-in-java-application?rq=1을 확인하십시오. 나는 mp3가 자바에 의해 지원되지 않는다는 것을 알고 있지만, .wma의 고려 윈도우는 아주 좋지 않다는 것을 알 수있다. – Austin

답변

0

사용이 라이브러리 : http://www.javazoom.net/javalayer/javalayer.html

public void play() { 
     String song = "http://www.ntonyx.com/mp3files/Morning_Flower.mp3"; 
     Player mp3player = null; 
     BufferedInputStream in = null; 
     try { 
      in = new BufferedInputStream(new URL(song).openStream()); 
      mp3player = new Player(in); 
      mp3player.play(); 
     } catch (MalformedURLException ex) { 
     } catch (IOException e) { 
     } catch (JavaLayerException e) { 
     } catch (NullPointerException ex) { 
     } 

} 

희망

+0

위의 코드는 하드 디스크의 파일도 재생할 수 있습니까? 그것은 나를 위해 작동하지 않습니다. Thread의 run() 메소드와 위의 코드를 mp3player.play() 명령문 뒤에 포함 시켰습니다. sleep (10000); 오디오가 재생을 완료하도록합니다. – Ranjith

+0

예이 예 참조 http://thiscouldbebetter.wordpress.com/2011/06/14/playing-an-mp3-from-java-using-jlayer/ –

0
:-) 비슷한 질문으로 모두를하는 데 도움이

흠. 이것은 내 물건에 대한 광고처럼 보일 수도 있지만, 당신은 여기 내 API를 사용할 수 있습니다

https://github.com/s4ke/HotSound

재생이 하나 매우 쉽습니다.

대안 : (나에 의해 약간의 변경) 클립 예를 들어

public static AudioInputStream getSupportedAudioInputStreamFromInputStream(InputStream pInputStream) throws UnsupportedAudioFileException, 
     IOException { 
    AudioInputStream sourceAudioInputStream = AudioSystem 
      .getAudioInputStream(pInputStream); 
    AudioInputStream ret = sourceAudioInputStream; 
    AudioFormat sourceAudioFormat = sourceAudioInputStream.getFormat(); 
    DataLine.Info supportInfo = new DataLine.Info(SourceDataLine.class, 
      sourceAudioFormat, 
      AudioSystem.NOT_SPECIFIED); 
    boolean directSupport = AudioSystem.isLineSupported(supportInfo); 
    if(!directSupport) { 
     float sampleRate = sourceAudioFormat.getSampleRate(); 
     int channels = sourceAudioFormat.getChannels(); 
     AudioFormat newFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 
       sampleRate, 
       16, 
       channels, 
       channels * 2, 
       sampleRate, 
       false); 
     AudioInputStream convertedAudioInputStream = AudioSystem 
       .getAudioInputStream(newFormat, sourceAudioInputStream); 
     sourceAudioFormat = newFormat; 
     ret = convertedAudioInputStream; 
    } 
    return ret; 
} 

출처 : : 사용하는 Java 클립 (prebuffering)

... code ... 
// specify the sound to play 
File soundFile = new File("pathToYouFile"); 
//this does the conversion stuff for you if you have the correct SPIs installed 
AudioInputStream inputStream = 
getSupportedAudioInputStreamFromInputStream(new FileInputStream(soundFile)); 

// load the sound into memory (a Clip) 
DataLine.Info info = new DataLine.Info(Clip.class, inputStream.getFormat()); 
Clip clip = (Clip) AudioSystem.getLine(info); 
clip.open(sound); 

// due to bug in Java Sound, explicitly exit the VM when 
// the sound has stopped. 
clip.addLineListener(new LineListener() { 
    public void update(LineEvent event) { 
    if (event.getType() == LineEvent.Type.STOP) { 
     event.getLine().close(); 
     System.exit(0); 
    } 
    } 
}); 

// play the sound clip 
clip.start(); 
... code ... 

은 그럼 당신은이 방법을 필요 http://www.java2s.com/Code/Java/Development-Class/AnexampleofloadingandplayingasoundusingaClip.htm

SPI는 클래스 패스에 .jars를 추가하여 추가됩니다.

는 MP3 이러한은 다음과 같습니다 (당신의 JDK와 함께 제공됩니다) 자바 FX를 사용

0

아주 간단합니다.

import javafx.scene.media.Media; 
import javafx.scene.media.MediaPlayer; 
import javafx.util.Duration; 

import java.nio.file.Paths; 

단계 :

초기화 자바 FX :

new JFXPanel(); 

Media (소리) 만들기 : 다음과 같은 수입해야합니다

Media media = new Media(Paths.get(filename).toUri().toString()); 

만들기 ,

player.setStartTime(new Duration(Duration.ZERO)); // Start at the beginning of the sound file 
player.setStopTime(1000); // Stop one second (1000 milliseconds) into the playback 

을 또는 : MediaPlayer 사운드 재생 :

MediaPlayer player = new MediaPlayer(media); 

을 그리고 Media 재생 :

player.play(); 

당신은 시작을 설정할 수 있습니다/MediaPlayer.setStartTime()MediaPlayer.setStopTime()으로뿐만 아니라 정지 시간 MediaPlayer.stop()으로 재생을 멈출 수 있습니다.

샘플 기능 오디오 재생 :

public static void playAudio(String name, double startMillis, double stopMillis) { 
    Media media = new Media(Paths.get(name).toUri().toString()); 
    MediaPlayer player = new MediaPlayer(media); 

    player.setStartTime(new Duration(startMillis)); 
    player.setStopTime(new Duration(stopMillis)); 
    player.play(); 
} 

더 많은 정보는 자바 FX javadoc에서 찾을 수 있습니다.