如何以其他方法停止录制音频线?

时间:2017-03-18 22:25:08

标签: java

无论如何我可以阻止该行在stopCapture方法中捕获(line.stop)吗?

public class Ouvir extends NewJFrame{
    AudioFormat audioFormat;
    TargetDataLine targetDataLine;

    void captureAudio(){
        Stop.setEnabled(true);
        try{
            audioFormat = getAudioFormat();
            DataLine.Info info = new DataLine.Info(TargetDataLine.class, audioFormat);
            TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
            AudioSystem.getLine(info);
            line.open();
            line.start();
        }
        catch (LineUnavailableException e) {}
    }

    void stopCapture(){ 
    }

    private AudioFormat getAudioFormat(){
        float samplerate = 48000f;
        return new AudioFormat(samplerate,8,1,true,true);
    }
}

1 个答案:

答案 0 :(得分:0)

我猜你想在line.stop();方法中调用stopCapture()或类似的东西。如果是这样,那么TargetDataLine line变量必须是类的实例字段而不是局部变量。您还需要在字段上调用stop()之前测试null。

如,

public class Ouvir extends NewJFrame{
    AudioFormat audioFormat;
    TargetDataLine targetDataLine;
    private TargetDataLine line; // **add this field**. It starts out  null

    void captureAudio(){
        Stop.setEnabled(true);
        try{
            audioFormat = getAudioFormat();
            DataLine.Info info = new DataLine.Info(TargetDataLine.class, audioFormat);

            // change the code below 
            // TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info); // from this
            line = (TargetDataLine) AudioSystem.getLine(info);  // to this

            AudioSystem.getLine(info);
            line.open();
            line.start();
        }
        catch (LineUnavailableException e) {}
    }

    void stopCapture(){ 
        if (line != null && line.isRunning()) {
            // here you call your stop method, if one exists
            line.stop(); // ??? perhaps ???
            // perhaps this would need to be called within a try/catch block as well, not sure
        }
    }

旁注:这看起来很危险:

catch (LineUnavailableException e) {}

你不应该忽略异常,而应该在异常发生时处理它们。

其他问题:这看起来是Swing GUI的一部分,如果是这样,您可能需要考虑Swing线程问题,以便您没有任何长时间运行的代码阻止Swing事件线程,冻结你的GUI。