0

我们如何在 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)
4

3 回答 3

0

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

https://github.com/s4ke/HotSound

用这个播放很容易。

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

... 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,这些是:

于 2012-09-27T01:01:01.763 回答
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) {
        }

}

希望对有类似问题的每个人都有帮助:-)

于 2012-09-25T06:32:50.590 回答
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中找到。

于 2016-01-28T22:25:19.500 回答