使用Audioplayer播放WAV文件

时间:2017-05-18 10:51:41

标签: java audio media-player

我正在尝试编写一个简短的程序来在Java中播放波形声音,但我看到很多例外。也许有人可以帮助我?

import java.io.*;
import sun.audio.*;
import sun.audio.AudioPlayer;  

@SuppressWarnings("restriction")
public class Main {
    public static void main(String[] args) throws IOException {
        String wav_file = "C:/Users/Patrick/workspace/WaveFreq/zelda_01.wav";
        InputStream in = new FileInputStream(wav_file);
        AudioStream audio = new AudioStream(in);

        AudioPlayer.player.start(audio);
    }
}

这是例外:

  

线程“main”中的异常java.io.IOException:无法从输入流中创建音频流
  在sun.audio.AudioStream。(未知来源)
  在Main.main(Main.java:16)

1 个答案:

答案 0 :(得分:0)

希望这会有所帮助:

import java.io.File;
import javax.sound.sampled.*;
import javax.sound.sampled.DataLine.Info;

public class AudioFilePlayer {
    public static void main(String[] args) {
        try {
            String filePath = "C:/Users/Patrick/workspace/WaveFreq/zelda_01.wav";
            AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File(filePath));
            AudioFormat format = inputStream.getFormat();
            DataLine.Info info = new DataLine.Info(Clip.class, format);
            Clip clip = (Clip) AudioSystem.getLine(info);

            clip.open(inputStream);
            clip.start();
        } catch (Exception e) {
            System.out.println("Error with playing sound.");
            e.printStackTrace( );
        }
    }
}