Android开发之PCM录音实时播放的实现方法 | 边录音边播放 |PCM录音播放无延迟 | 录音无杂音 | 录音无噪音

先说下录音得开启录音权限

然后录音和播放得开启线程,防止录制和播放pcm流阻塞UI线程,我这边使用线程池

ThreadPoolExecutor mExecutorService = new ThreadPoolExecutor(
            3, 5,
            1, TimeUnit.MINUTES,
            new LinkedBlockingDeque<>(10),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy());

开始线程并且录音实时播放

/**
     * 44.1Khz采集率
     */
    int sampleRateInHz = 44100;
    /**
     * 格式 ,单双声道
     */
    int channelConfiguration = AudioFormat.CHANNEL_OUT_STEREO;
    /**
     * 16Bit 音频编码格式
     */
    int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;


mExecutorService.execute(() -> {
        Log.e(TAG, "开始录音");
        try {
            int bufferSize = AudioRecord.getMinBufferSize(sampleRateInHz, AudioFormat.CHANNEL_IN_STEREO, audioEncoding);
            AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRateInHz, AudioFormat.CHANNEL_IN_STEREO, audioEncoding, bufferSize);
            AudioTrack player = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRateInHz, channelConfiguration, audioEncoding, bufferSize, AudioTrack.MODE_STREAM);
            player.play();
            byte[] buffer = new byte[bufferSize];
            audioRecord.startRecording();
            Log.e(TAG, "开始录音");
            long startTime = System.currentTimeMillis();
            //如果需要控制停止录音播放,可以将下面的循环true定义一个boolean值,
            //true代表录音播放,false代表不读取不写入也就不会录音播放了,
            //需要完整代码可以到文章底部下载源码
            while (true) {
                int bufferReadResult = audioRecord.read(buffer, 0, bufferSize);
                player.write(buffer, 0, bufferReadResult);
            }
            audioRecord.stop();
            long endTime = System.currentTimeMillis();
            float recordTime = (endTime - startTime) / 1000f;
            Log.e(TAG, "录音总时长:" + recordTime + "s");
        } catch (Throwable t) {
            Log.e(TAG, "录音失败");
        }
                });

需要的可以下载源码查看:pcm边录音边播放源码下载

你可能感兴趣的:(Android音视频,PCM录音,播放pcm,android播放pcm流,android边录音边播放,pcm录音后播放)