我有一个Runnable,它可以连接到麦克风,从麦克风读取数据并将其存储在OutputStream中。
当我启动该线程的第一个实例时,它将起作用。
在第一个线程完成后(存在run()方法),我启动了线程的另一个实例,但是这次我得到:

javax.sound.sampled.LineUnavailableException: line with format PCM_SIGNED 44100.0 Hz, 8 bit, stereo, 2 bytes/frame,  not supported.
at com.sun.media.sound.DirectAudioDevice$DirectDL.implOpen(Unknown Source)
at com.sun.media.sound.AbstractDataLine.open(Unknown Source)
at com.sun.media.sound.AbstractDataLine.open(Unknown Source)

我的线程如下所示:
public void run() {
     float sampleRate = 44100.00F;
        //8000,11025,16000,22050,44100
        int sampleSizeInBits = 8;
        //8,16
        int channels = 2;
        //1,2
        boolean signed = true;
        //true,false
        boolean bigEndian = false;
        //true,false
    AudioFormat format = new AudioFormat(sampleRate,
           sampleSizeInBits,
           channels,
           signed,
           bigEndian);

    DataLine.Info info = new DataLine.Info(TargetDataLine.class, format); // format is an AudioFormat object

    // Obtain and open the line.
    try {
        targetLine = (TargetDataLine) AudioSystem.getLine(info);
        targetLine.open(format); //exception is throw here
        targetLine.start();
        ByteArrayOutputStream out  = new ByteArrayOutputStream();
        CountingOutputStream countingOutStream = new CountingOutputStream(out);
        int numBytesRead;
        byte[] data = new byte[targetLine.getBufferSize() / 5];

        File binFile = new File("C:\\audio\\random4.txt");
        FileOutputStream fr = new FileOutputStream(binFile);


        while ( (countingOutStream.getCount()/1024) < targetSizeKB) {
           numBytesRead =  targetLine.read(data, 0, data.length);
           countingOutStream.write(data, 0, numBytesRead);
        }




        fr.write(newByte,0,ii);
        countingOutStream.close();
        fr.close();

       targetLine.flush();
        targetLine.stop();
        targetLine = null;
}

最佳答案

您正在flush上调用stoptargetLine,但是您没有调用close-我怀疑您需要这样做才能正确释放它。 (顺便说一句,不清楚targetLine为什么是一个实例变量-是否需要?)

您还应该在finally块中进行所有清理,以便即使抛出异常也可以关闭流。

07-24 15:44