使用javax.sound.sampled播放录制的音频输出

时间:2014-06-05 08:07:21

标签: java audio

我在验证已捕获的输出时遇到问题。我的程序应该从麦克风捕获音频,然后将其保存为WAVE文件。它就是这样,但是只听到文件会导致声音崩溃,没有录制实际的声音。

我的代码就是这个

import java.io.IOException;
import javax.sound.sampled.*;

import java.io.File;

public class Main
{
public static void main(String[] args) throws IOException, InterruptedException, LineUnavailableException {
    TargetDataLine line = null;
    DataLine.Info info = new DataLine.Info(TargetDataLine.class, getAudioFormat());

    try
    {
        line = (TargetDataLine) AudioSystem.getLine(info);
        line.open(getAudioFormat());
    }
    catch (LineUnavailableException e)
    {
        e.printStackTrace();
    }

    line.start();
    AudioInputStream stream = new AudioInputStream(line);

    Stopper stopper = new Stopper(line, stream);
    stopper.start();


    File file = new File("C:/Users/Martin/Documents/soundfile.wav");
    AudioSystem.write(stream, AudioFileFormat.Type.WAVE, file);

    System.out.println("Stopped...");
    System.in.read();
}

public static AudioFormat getAudioFormat()
{
    AudioFormat.Encoding encoding = AudioFormat.Encoding.PCM_SIGNED;

    float sampleRate = 8000.0f;
    int sampleSizeInBits = 16;
    int channels = 2;
    int frameSize = 4;
    int frameRate = 8000;
    boolean bigEndian = true;

    return new AudioFormat(encoding,
            sampleRate,
            sampleSizeInBits,
            channels,
            frameSize,
            frameRate,
            bigEndian);
}

}

塞子线就是这样:

import java.io.IOException;
import javax.sound.sampled.*;

public class Stopper extends Thread
{
TargetDataLine line = null;
AudioInputStream stream = null;

public Stopper(TargetDataLine line, AudioInputStream stream)
{
    this.line = line;
    this.stream = stream;
}

public void run()
{
    System.out.println("Press [RETURN] to stop capturing...");

    try
    {
        System.in.read();
    }
    catch (IOException e)
    {}

    line.stop();
    try
    {
        stream.close();
    }
    catch (IOException e)
    {}
}
}

我使用的Audioformat被麦克风接受:

默认混音器支持的SourceDataLines(Mikrofon(Creative SB X-Fi)):

接口TargetDataLine支持8种音频格式,以及至少32字节的缓冲区   最大缓冲区大小:-1   最小缓冲区大小:32   支持的音频格式:

PCM_SIGNED unknown sample rate, 16 bit, stereo, 4 bytes/frame, big-endian

0 个答案:

没有答案