java實現動態錄音,音效卡有聲音進來就自動錄音

來源:互聯網
上載者:User

TargetDataLine是聲音的輸入(麥克風),而SourceDataLine是輸出(音響,耳機).
整個過程,請參見下面的程式.(運行後,即時地從麥克風錄音,即時輸出).

import java.io.*;import javax.sound.sampled.AudioSystem;import javax.sound.sampled.AudioInputStream;import javax.sound.sampled.AudioFormat;import javax.sound.sampled.SourceDataLine;import javax.sound.sampled.DataLine;import javax.sound.sampled.FloatControl;import javax.sound.sampled.TargetDataLine;public class RecordAndPlay {    static volatile boolean stop=false;    public static void main(String[] args) {        Play();    }    //播放音頻檔案    public static void Play() {        try {            AudioFormat audioFormat =//                    new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100F,//                    8, 1, 1, 44100F, false);             new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,44100F, 16, 2, 4,             44100F, true);            DataLine.Info info = new DataLine.Info(TargetDataLine.class, audioFormat); TargetDataLine targetDataLine = (TargetDataLine) AudioSystem.getLine(info);            targetDataLine.open(audioFormat);            final SourceDataLine sourceDataLine;            info = new DataLine.Info(SourceDataLine.class, audioFormat);            sourceDataLine = (SourceDataLine) AudioSystem.getLine(info);            sourceDataLine.open(audioFormat);            targetDataLine.start();            sourceDataLine.start();            FloatControl fc=(FloatControl)sourceDataLine.getControl(FloatControl.Type.MASTER_GAIN);            double value=2;            float dB = (float)                  (Math.log(value==0.0?0.0001:value)/Math.log(10.0)*20.0);            fc.setValue(dB);            int nByte = 0;            final int bufSize=4*100;            byte[] buffer = new byte[bufSize];            while (nByte != -1) {                //System.in.read();                nByte = targetDataLine.read(buffer, 0, bufSize);                sourceDataLine.write(buffer, 0, nByte);            }            sourceDataLine.stop();        } catch (Exception e) {            e.printStackTrace();        }    }}


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.