在Java Desktop应用程序中播放声音

时间:2012-09-25 06:29:02

标签: java audio

我们如何在Java桌面应用程序中播放声音(任何格式的音乐文件,如.wma,.mp3)? (不是小程序)

我使用了以下代码(取自Stack Overflow上的另一个问题),但它抛出异常。

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)

3 个答案:

答案 0 :(得分: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) {
        }

}

希望能帮助每个人提出类似的问题: - )

答案 1 :(得分:0)

嗯。这可能看起来像我的东西的广告,但你可以在这里使用我的API:

https://github.com/s4ke/HotSound

用这个播放很容易。

替代方案:使用Java剪辑(预缓冲)

... 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 ...

然后你需要这个方法:

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;
}

Clip示例的来源(我几乎没有变化):http://www.java2s.com/Code/Java/Development-Class/AnexampleofloadingandplayingasoundusingaClip.htm

通过将.jars添加到类路径

来添加SPI 对于mp3来说,这些是:

答案 2 :(得分:0)

使用JavaFX(与JDK捆绑在一起)非常简单。 您将需要以下导入:

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

import java.nio.file.Paths;

步骤:

初始化JavaFX:

new JFXPanel();

创建Media(声音):

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

创建MediaPlayer播放声音:

MediaPlayer player = new MediaPlayer(media);

播放Media

player.play();

您也可以使用MediaPlayer.setStartTime()MediaPlayer.setStopTime()设置开始/停止时间:

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.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();
}

可以在JavaFX javadoc找到更多信息。