在尝试捕捉的同时播放声音

时间:2019-02-20 12:24:31

标签: java file-io try-catch fileinputstream

无法编译。我正在尝试使用try and catch播放声音。 wav文件位于我的桌面上。 我收到如下错误:     无法将AudioStream解析为一种类型     无法将AudioStream解析为一种类型     无法解析AudioPlayer。

我不确定如何解决这个问题,我知道它很简单,

import java.io.FileInputStream;
import java.io.InputStream;

public class PlayMySoundApplication
{
public static void main(String[] args) 
 throws Exception
{
// open the sound file as a Java input stream
String applause2x = "/Users/pc/Desktop/applause2x.wav";
InputStream in = new FileInputStream(applause2x);

// create an audiostream from the inputstream
AudioStream audioStream = new AudioStream(in);

// play the audio clip with the audioplayer class
AudioPlayer.player.start(audioStream);

2 个答案:

答案 0 :(得分:1)

我不知道您要使用哪个声音库。

如果您使用的是JDK的不错的版本,那应该可以解决问题:

import java.io.File;
import java.io.IOException;

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 MakeSound {

    public static void main(String[] args) throws LineUnavailableException, UnsupportedAudioFileException, IOException {
        playSound("test.wav");
    }

    public static void playSound(String strFilename)
            throws LineUnavailableException, UnsupportedAudioFileException, IOException {

        File soundFile = new File(strFilename);

        AudioInputStream audioStream = AudioSystem.getAudioInputStream(soundFile);

        AudioFormat audioFormat = audioStream.getFormat();

        DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
        try (SourceDataLine sourceLine = (SourceDataLine) AudioSystem.getLine(info);) {
            sourceLine.open(audioFormat);
            sourceLine.start();

            int nBytesRead = 0;
            byte[] abData = new byte[128000];
            while (nBytesRead != -1) {
                nBytesRead = audioStream.read(abData, 0, abData.length);
                if (nBytesRead > 0) {
                    sourceLine.write(abData, 0, nBytesRead);
                }
            }

            sourceLine.drain();
        }
    }
}

HTH!

答案 1 :(得分:1)

添加音频导入,

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


public class PlayMySoundApplication
{
  public static void main(String[] args) 
  throws Exception
  {
    // open the sound file as a Java input stream
    String applause2x = "/Users/pc/Desktop/applause2x.wav";
InputStream in = new FileInputStream(applause2x);


    // create an audiostream from the inputstream
    AudioStream audioStream = new AudioStream(in);

    // play the audio clip with the audioplayer class
    AudioPlayer.player.start(audioStream);
  }
}