Java Code Examples for android.media.AudioRecord#startRecording()

The following examples show how to use android.media.AudioRecord#startRecording() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RecordAudioTester.java    From PermissionAgent with Apache License 2.0 6 votes vote down vote up
@Override
public boolean test() throws Throwable {
    AudioRecord audioRecord = findAudioRecord();
    try {
        if (audioRecord != null) {
            audioRecord.startRecording();
        } else {
            return !existMicrophone(mContext);
        }
    } catch (Throwable e) {
        return !existMicrophone(mContext);
    } finally {
        if (audioRecord != null) {
            audioRecord.stop();
            audioRecord.release();
        }
    }
    return true;
}
 
Example 2
Source File: AndroidRecorder.java    From LingoRecorder with Apache License 2.0 6 votes vote down vote up
@Override
public void startRecording() throws Exception {
    int buffSize = getBufferSize();

    recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, recorderProperty.getSampleRate(),
            channels, audioFormat, buffSize);

    if (recorder.getState() != AudioRecord.STATE_INITIALIZED) {
        throw new RecorderInitException();
    }

    payloadSize = 0;
    recorder.startRecording();

    if (recorder.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING) {
        throw new RecorderStartException();
    }
}
 
Example 3
Source File: MainActivity.java    From snips-platform-android-demo with Apache License 2.0 6 votes vote down vote up
private void runStreaming() {
    Log.d(TAG, "starting audio streaming");
    final int minBufferSizeInBytes = AudioRecord.getMinBufferSize(FREQUENCY, CHANNEL, ENCODING);
    Log.d(TAG, "minBufferSizeInBytes: " + minBufferSizeInBytes);

    recorder = new AudioRecord(MIC, FREQUENCY, CHANNEL, ENCODING, minBufferSizeInBytes);
    recorder.startRecording();

    while (continueStreaming) {
        short[] buffer = new short[minBufferSizeInBytes / 2];
        recorder.read(buffer, 0, buffer.length);
        if (client != null) {
            client.sendAudioBuffer(buffer);
        }
    }
    recorder.stop();
    Log.d(TAG, "audio streaming stopped");
}
 
Example 4
Source File: VoiceCaptureActor.java    From actor-platform with GNU Affero General Public License v3.0 6 votes vote down vote up
protected void onStartMessage(String fileName) {
    if (state == STATE_STARTED) {
        return;
    }

    int minBufferSize = AudioRecord.getMinBufferSize(16000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
    bufferSize = 16 * minBufferSize;
    audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, 16000, AudioFormat.CHANNEL_IN_MONO,
            AudioFormat.ENCODING_PCM_16BIT, bufferSize);
    audioRecord.startRecording();
    opusActor = system().actorOf(Props.create(new ActorCreator() {
        @Override
        public OpusEncoderActor create() {
            return new OpusEncoderActor();
        }
    }), "actor/opus_encoder");
    opusActor.send(new OpusEncoderActor.Start(fileName));
    state = STATE_STARTED;
    playStartTime = SystemClock.uptimeMillis();
    vibrate(context);
    self().send(new Iterate());
}
 
Example 5
Source File: AACEncodeConsumer.java    From AndroidUSBCamera with Apache License 2.0 6 votes vote down vote up
private void initAudioRecord(){
    if(DEBUG)
        Log.d(TAG,"AACEncodeConsumer-->开始采集音频");
    // 设置进程优先级
    Process.setThreadPriority(Process.THREAD_PRIORITY_AUDIO);
    int bufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO,
            AudioFormat.ENCODING_PCM_16BIT);
    for (final int src: AUDIO_SOURCES) {
        try {
            mAudioRecord = new AudioRecord(src,
                    SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);
            if (mAudioRecord != null) {
                if (mAudioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
                    mAudioRecord.release();
                    mAudioRecord = null;
                }
            }
        } catch (final Exception e) {
            mAudioRecord = null;
        }
        if (mAudioRecord != null) {
            break;
        }
    }
    mAudioRecord.startRecording();
}
 
Example 6
Source File: MicrophoneSource.java    From media-for-mobile with Apache License 2.0 5 votes vote down vote up
@Override
public void start() {
    recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, this.sampleRate, androidChannels, audioEncoding, minBufferSize * 4);

    int state = recorder.getState();

    if (state != AudioRecord.STATE_INITIALIZED) {
        throw new IllegalStateException("Failed to start AudioRecord! Used by another application?");
    }

    recorder.startRecording();

    super.start();
}
 
Example 7
Source File: ExtAudioCapture.java    From PLDroidRTCStreaming with Apache License 2.0 5 votes vote down vote up
public boolean startCapture(int audioSource, int sampleRateInHz, int channelConfig, int audioFormat) {
    if (mIsCaptureStarted) {
        Log.e(TAG, "Capture already started !");
        return false;
    }

    int minBufferSize = AudioRecord.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat);
    if (minBufferSize == AudioRecord.ERROR_BAD_VALUE) {
        Log.e(TAG, "Invalid parameter !");
        return false;
    }

    mAudioRecord = new AudioRecord(audioSource, sampleRateInHz, channelConfig, audioFormat, minBufferSize * 4);
    if (mAudioRecord.getState() == AudioRecord.STATE_UNINITIALIZED) {
        Log.e(TAG, "AudioRecord initialize fail !");
        return false;
    }

    mAudioRecord.startRecording();

    mIsLoopExit = false;
    mCaptureThread = new Thread(new AudioCaptureRunnable());
    mCaptureThread.start();

    mIsCaptureStarted = true;

    Log.d(TAG, "Start audio capture success !");

    return true;
}
 
Example 8
Source File: PullableSource.java    From OmRecorder with Apache License 2.0 5 votes vote down vote up
@Override
public AudioRecord preparedToBePulled() {
  final AudioRecord audioRecord = audioRecord();
  audioRecord.startRecording();
  isEnableToBePulled(true);
  return audioRecord;
}
 
Example 9
Source File: CameraRecorder.java    From AAVT with Apache License 2.0 5 votes vote down vote up
public void startRecord() throws IOException {
        synchronized (REC_LOCK){
            isRecordStarted=true;
            MediaFormat audioFormat=mConfig.getAudioFormat();
            mAudioEncoder=MediaCodec.createEncoderByType(audioFormat.getString(MediaFormat.KEY_MIME));
            mAudioEncoder.configure(audioFormat,null,null,MediaCodec.CONFIGURE_FLAG_ENCODE);
            MediaFormat videoFormat=mConfig.getVideoFormat();
            mVideoEncoder=MediaCodec.createEncoderByType(videoFormat.getString(MediaFormat.KEY_MIME));
            //此处不能用mOutputSurface,会configure失败
            mVideoEncoder.configure(videoFormat,null,null,MediaCodec.CONFIGURE_FLAG_ENCODE);
            mEncodeSurface=mVideoEncoder.createInputSurface();

            mAudioEncoder.start();
            mVideoEncoder.start();
            mMuxer=new MediaMuxer(mOutputPath,MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
            mRecordBufferSize = AudioRecord.getMinBufferSize(mRecordSampleRate,
                    mRecordChannelConfig, mRecordAudioFormat)*2;
//        buffer=new byte[bufferSize];
            mAudioRecord=new AudioRecord(MediaRecorder.AudioSource.MIC,mRecordSampleRate,mRecordChannelConfig,
                    mRecordAudioFormat,mRecordBufferSize);

            mAudioThread=new Thread(new Runnable() {
                @Override
                public void run() {
                    mAudioRecord.startRecording();
                    while (!audioEncodeStep(isTryStopAudio)){};
                    mAudioRecord.stop();
                }
            });
            mAudioThread.start();
            isRecordAudioStarted=true;
        }
    }
 
Example 10
Source File: SoundFile.java    From MusicPlayer with GNU General Public License v3.0 5 votes vote down vote up
private void RecordAudio() {
    if (mProgressListener ==  null) {
        // A progress listener is mandatory here, as it will let us know when to stop recording.
        return;
    }
    mInputFile = null;
    mFileType = "raw";
    mFileSize = 0;
    mSampleRate = 44100;
    mChannels = 1;  // record mono audio.
    short[] buffer = new short[1024];  // buffer contains 1 mono frame of 1024 16 bits samples
    int minBufferSize = AudioRecord.getMinBufferSize(
            mSampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
    // make sure minBufferSize can contain at least 1 second of audio (16 bits sample).
    if (minBufferSize < mSampleRate * 2) {
        minBufferSize = mSampleRate * 2;
    }
    AudioRecord audioRecord = new AudioRecord(
            MediaRecorder.AudioSource.DEFAULT,
            mSampleRate,
            AudioFormat.CHANNEL_IN_MONO,
            AudioFormat.ENCODING_PCM_16BIT,
            minBufferSize
            );

    // Allocate memory for 20 seconds first. Reallocate later if more is needed.
    mDecodedBytes = ByteBuffer.allocate(20 * mSampleRate * 2);
    mDecodedBytes.order(ByteOrder.LITTLE_ENDIAN);
    mDecodedSamples = mDecodedBytes.asShortBuffer();
    audioRecord.startRecording();
    while (true) {
        // check if mDecodedSamples can contain 1024 additional samples.
        if (mDecodedSamples.remaining() < 1024) {
            // Try to allocate memory for 10 additional seconds.
            int newCapacity = mDecodedBytes.capacity() + 10 * mSampleRate * 2;
            ByteBuffer newDecodedBytes = null;
            try {
                newDecodedBytes = ByteBuffer.allocate(newCapacity);
            } catch (OutOfMemoryError oome) {
                break;
            }
            int position = mDecodedSamples.position();
            mDecodedBytes.rewind();
            newDecodedBytes.put(mDecodedBytes);
            mDecodedBytes = newDecodedBytes;
            mDecodedBytes.order(ByteOrder.LITTLE_ENDIAN);
            mDecodedBytes.rewind();
            mDecodedSamples = mDecodedBytes.asShortBuffer();
            mDecodedSamples.position(position);
        }
        // TODO(nfaralli): maybe use the read method that takes a direct ByteBuffer argument.
        audioRecord.read(buffer, 0, buffer.length);
        mDecodedSamples.put(buffer);
        // Let the progress listener know how many seconds have been recorded.
        // The returned value tells us if we should keep recording or stop.
        if (!mProgressListener.reportProgress(
                (float)(mDecodedSamples.position()) / mSampleRate)) {
            break;
        }
    }
    audioRecord.stop();
    audioRecord.release();
    mNumSamples = mDecodedSamples.position();
    mDecodedSamples.rewind();
    mDecodedBytes.rewind();
    mAvgBitRate = mSampleRate * 16 / 1000;

    // Temporary hack to make it work with the old version.
    mNumFrames = mNumSamples / getSamplesPerFrame();
    if (mNumSamples % getSamplesPerFrame() != 0){
        mNumFrames++;
    }
    mFrameGains = new int[mNumFrames];
    mFrameLens = null;  // not needed for recorded audio
    mFrameOffsets = null;  // not needed for recorded audio
    int i, j;
    int gain, value;
    for (i=0; i<mNumFrames; i++){
        gain = -1;
        for(j=0; j<getSamplesPerFrame(); j++) {
            if (mDecodedSamples.remaining() > 0) {
                value = java.lang.Math.abs(mDecodedSamples.get());
            } else {
                value = 0;
            }
            if (gain < value) {
                gain = value;
            }
        }
        mFrameGains[i] = (int)Math.sqrt(gain);  // here gain = sqrt(max value of 1st channel)...
    }
    mDecodedSamples.rewind();
    // DumpSamples();  // Uncomment this line to dump the samples in a TSV file.
}
 
Example 11
Source File: ExtAudioCapture.java    From PLDroidMediaStreaming with Apache License 2.0 5 votes vote down vote up
public boolean startCapture(int audioSource, int sampleRateInHz, int channelConfig, int audioFormat) {
    if (mIsCaptureStarted) {
        Log.e(TAG, "Capture already started !");
        return false;
    }

    int minBufferSize = AudioRecord.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat);
    if (minBufferSize == AudioRecord.ERROR_BAD_VALUE) {
        Log.e(TAG, "Invalid parameter !");
        return false;
    }

    mAudioRecord = new AudioRecord(audioSource, sampleRateInHz, channelConfig, audioFormat, minBufferSize * 4);
    if (mAudioRecord.getState() == AudioRecord.STATE_UNINITIALIZED) {
        Log.e(TAG, "AudioRecord initialize fail !");
        return false;
    }

    mAudioRecord.startRecording();

    mIsLoopExit = false;
    mCaptureThread = new Thread(new AudioCaptureRunnable());
    mCaptureThread.start();

    mIsCaptureStarted = true;

    Log.d(TAG, "Start audio capture success !");

    return true;
}
 
Example 12
Source File: MicOpusRecorder.java    From DeviceConnect-Android with MIT License 4 votes vote down vote up
/**
 * 音声をレコードして、MediaCodec に渡します.
 */
private void recordAudio() throws NativeInterfaceException {
    int samplingRate = mSamplingRate.getValue();
    int channels = mChannels == 1 ? AudioFormat.CHANNEL_IN_MONO : AudioFormat.CHANNEL_IN_STEREO;
    int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
    int bufferSize = AudioRecord.getMinBufferSize(samplingRate, channels, audioFormat) * 4;
    int oneFrameDataCount = mSamplingRate.getValue() / mFrameSize.getFps();

    mAudioRecord = new AudioRecord(MediaRecorder.AudioSource.DEFAULT,
            samplingRate,
            channels,
            audioFormat,
            bufferSize);

    if (mAudioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
        if (mAudioRecordCallback != null) {
            mAudioRecordCallback.onEncoderError();
        }
        return;
    }

    if (mUseAEC && AcousticEchoCanceler.isAvailable()) {
        // ノイズキャンセラー
        mEchoCanceler = AcousticEchoCanceler.create(mAudioRecord.getAudioSessionId());
        if (mEchoCanceler != null) {
            int ret = mEchoCanceler.setEnabled(true);
            if (ret != AudioEffect.SUCCESS) {
                if (DEBUG) {
                    Log.w(TAG, "AcousticEchoCanceler is not supported.");
                }
            }
        }
    }

    OpusEncoder opusEncoder = null;

    try {
        opusEncoder = new OpusEncoder(mSamplingRate, mChannels, mFrameSize, mBitRate, mApplication);

        mAudioRecord.startRecording();

        short[] emptyBuffer = new short[oneFrameDataCount];
        short[] pcmBuffer = new short[oneFrameDataCount];
        byte[] opusFrameBuffer = opusEncoder.bufferAllocate();
        while (!mStopFlag) {
            int readSize = mAudioRecord.read(pcmBuffer, 0, oneFrameDataCount);
            if (readSize > 0) {
                int opusFrameBufferLength;
                if (isMute()) {
                    opusFrameBufferLength = opusEncoder.encode(emptyBuffer, readSize, opusFrameBuffer);
                } else {
                    opusFrameBufferLength = opusEncoder.encode(pcmBuffer, readSize, opusFrameBuffer);
                }

                if (opusFrameBufferLength > 0 && mAudioRecordCallback != null) {
                    mAudioRecordCallback.onPeriodicNotification(opusFrameBuffer, opusFrameBufferLength);
                }
            } else if (readSize == AudioRecord.ERROR_INVALID_OPERATION) {
                if (DEBUG) {
                    Log.e(TAG, "Invalid operation error.");
                }
                break;
            } else if (readSize == AudioRecord.ERROR_BAD_VALUE) {
                if (DEBUG) {
                    Log.e(TAG, "Bad value error.");
                }
                break;
            } else if (readSize == AudioRecord.ERROR) {
                if (DEBUG) {
                    Log.e(TAG, "Unknown error.");
                }
                break;
            }
        }
    } finally {
        if (mEchoCanceler != null) {
            mEchoCanceler.release();
            mEchoCanceler = null;
        }

        if (opusEncoder != null) {
            opusEncoder.release();
        }
    }
}
 
Example 13
Source File: PermissionUtil.java    From AlbumCameraRecorder with MIT License 4 votes vote down vote up
/**
 * 用于检测是否具有录音权限
 *
 * @return 状态:是否具有
 */
public static int getRecordState() {
    int minBuffer = AudioRecord.getMinBufferSize(44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat
            .ENCODING_PCM_16BIT);
    AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, 44100, AudioFormat
            .CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, (minBuffer * 100));
    short[] point = new short[minBuffer];
    int readSize;
    try {

        audioRecord.startRecording();//检测是否可以进入初始化状态
    } catch (Exception e) {
        if (audioRecord != null) {
            audioRecord.release();
            audioRecord = null;
        }
        return STATE_NO_PERMISSION;
    }
    if (audioRecord.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING) {
        //6.0以下机型都会返回此状态,故使用时需要判断bulid版本
        //检测是否在录音中
        if (audioRecord != null) {
            audioRecord.stop();
            audioRecord.release();
            Log.d("CheckAudioPermission", "录音机被占用");
        }
        return STATE_RECORDING;
    } else {
        //检测是否可以获取录音结果

        readSize = audioRecord.read(point, 0, point.length);


        if (readSize <= 0) {
            if (audioRecord != null) {
                audioRecord.stop();
                audioRecord.release();

            }
            Log.d("CheckAudioPermission", "录音的结果为空");
            return STATE_NO_PERMISSION;

        } else {
            if (audioRecord != null) {
                audioRecord.stop();
                audioRecord.release();

            }

            return STATE_SUCCESS;
        }
    }
}
 
Example 14
Source File: MonitorActivity.java    From protect-baby-monitor with GNU General Public License v3.0 4 votes vote down vote up
private void serviceConnection(Socket socket) throws IOException
{
    MonitorActivity.this.runOnUiThread(new Runnable()
    {
        @Override
        public void run()
        {
            final TextView statusText = (TextView) findViewById(R.id.textStatus);
            statusText.setText(R.string.streaming);
        }
    });

    final int frequency = 11025;
    final int channelConfiguration = AudioFormat.CHANNEL_IN_MONO;
    final int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;

    final int bufferSize = AudioRecord.getMinBufferSize(frequency, channelConfiguration, audioEncoding);
    final AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
            frequency, channelConfiguration,
            audioEncoding, bufferSize);

    final int byteBufferSize = bufferSize*2;
    final byte[] buffer = new byte[byteBufferSize];

    try
    {
        audioRecord.startRecording();

        final OutputStream out = socket.getOutputStream();

        socket.setSendBufferSize(byteBufferSize);
        Log.d(TAG, "Socket send buffer size: " + socket.getSendBufferSize());

        while (socket.isConnected() && Thread.currentThread().isInterrupted() == false)
        {
            final int read = audioRecord.read(buffer, 0, bufferSize);
            out.write(buffer, 0, read);
        }
    }
    finally
    {
        audioRecord.stop();
    }
}
 
Example 15
Source File: CheckPermission.java    From imsdk-android with MIT License 4 votes vote down vote up
/**
 * 用于检测是否具有录音权限
 *
 * @return
 */
public static int getRecordState() {
    int minBuffer = AudioRecord.getMinBufferSize(44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat
            .ENCODING_PCM_16BIT);
    AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, 44100, AudioFormat
            .CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, (minBuffer * 100));
    short[] point = new short[minBuffer];
    int readSize = 0;
    try {

        audioRecord.startRecording();//检测是否可以进入初始化状态
    } catch (Exception e) {
        if (audioRecord != null) {
            audioRecord.release();
            audioRecord = null;
        }
        return STATE_NO_PERMISSION;
    }
    if (audioRecord.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING) {
        //6.0以下机型都会返回此状态,故使用时需要判断bulid版本
        //检测是否在录音中
        if (audioRecord != null) {
            audioRecord.stop();
            audioRecord.release();
            audioRecord = null;
            Log.d("CheckAudioPermission", "录音机被占用");
        }
        return STATE_RECORDING;
    } else {
        //检测是否可以获取录音结果

        readSize = audioRecord.read(point, 0, point.length);


        if (readSize <= 0) {
            if (audioRecord != null) {
                audioRecord.stop();
                audioRecord.release();
                audioRecord = null;

            }
            Log.d("CheckAudioPermission", "录音的结果为空");
            return STATE_NO_PERMISSION;

        } else {
            if (audioRecord != null) {
                audioRecord.stop();
                audioRecord.release();
                audioRecord = null;

            }

            return STATE_SUCCESS;
        }
    }
}
 
Example 16
Source File: SoundRecorder.java    From AAVT with Apache License 2.0 4 votes vote down vote up
public void start(){
    if(!isStarted){
        stopFlag=false;

        mRecordBufferSize = AudioRecord.getMinBufferSize(mRecordSampleRate,
                mRecordChannelConfig, mRecordAudioFormat)*2;
        mRecord=new AudioRecord(MediaRecorder.AudioSource.MIC,mRecordSampleRate,mRecordChannelConfig,
                mRecordAudioFormat,mRecordBufferSize);
        mRecord.startRecording();
        try {
            MediaFormat format=convertAudioConfigToFormat(mConfig.mAudio);
            mAudioEncoder=MediaCodec.createEncoderByType(format.getString(MediaFormat.KEY_MIME));
            mAudioEncoder.configure(format,null,null,MediaCodec.CONFIGURE_FLAG_ENCODE);
            mAudioEncoder.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {
                while (!stopFlag&&!audioEncodeStep(false)){};
                audioEncodeStep(true);
                Log.e("wuwang","audio stop");
                if(isStarted){
                    mRecord.stop();
                    mRecord.release();
                    mRecord=null;
                }
                if(mAudioEncoder!=null){
                    mAudioEncoder.stop();
                    mAudioEncoder.release();
                    mAudioEncoder=null;
                }
                isStarted=false;
            }
        });
        thread.start();
        startTime=SystemClock.elapsedRealtimeNanos();
        isStarted=true;
    }
}
 
Example 17
Source File: CheckPermission.java    From imsdk-android with MIT License 4 votes vote down vote up
/**
 * 用于检测是否具有录音权限
 *
 * @return
 */
public static int getRecordState() {
    int minBuffer = AudioRecord.getMinBufferSize(44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat
            .ENCODING_PCM_16BIT);
    AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, 44100, AudioFormat
            .CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, (minBuffer * 100));
    short[] point = new short[minBuffer];
    int readSize = 0;
    try {

        audioRecord.startRecording();//检测是否可以进入初始化状态
    } catch (Exception e) {
        if (audioRecord != null) {
            audioRecord.release();
            audioRecord = null;
        }
        return STATE_NO_PERMISSION;
    }
    if (audioRecord.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING) {
        //6.0以下机型都会返回此状态,故使用时需要判断bulid版本
        //检测是否在录音中
        if (audioRecord != null) {
            audioRecord.stop();
            audioRecord.release();
            audioRecord = null;
            Log.d("CheckAudioPermission", "录音机被占用");
        }
        return STATE_RECORDING;
    } else {
        //检测是否可以获取录音结果

        readSize = audioRecord.read(point, 0, point.length);


        if (readSize <= 0) {
            if (audioRecord != null) {
                audioRecord.stop();
                audioRecord.release();
                audioRecord = null;

            }
            Log.d("CheckAudioPermission", "录音的结果为空");
            return STATE_NO_PERMISSION;

        } else {
            if (audioRecord != null) {
                audioRecord.stop();
                audioRecord.release();
                audioRecord = null;

            }

            return STATE_SUCCESS;
        }
    }
}
 
Example 18
Source File: CheckPermission.java    From PictureSelector with Apache License 2.0 4 votes vote down vote up
/**
 * 用于检测是否具有录音权限
 *
 * @return
 */
public static int getRecordState() {
    int minBuffer = AudioRecord.getMinBufferSize(44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat
            .ENCODING_PCM_16BIT);
    AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, 44100, AudioFormat
            .CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, (minBuffer * 100));
    short[] point = new short[minBuffer];
    int readSize = 0;
    try {

        audioRecord.startRecording();//检测是否可以进入初始化状态
    } catch (Exception e) {
        if (audioRecord != null) {
            audioRecord.release();
            audioRecord = null;
        }
        return STATE_NO_PERMISSION;
    }
    if (audioRecord.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING) {
        //6.0以下机型都会返回此状态,故使用时需要判断bulid版本
        //检测是否在录音中
        if (audioRecord != null) {
            audioRecord.stop();
            audioRecord.release();
            audioRecord = null;
        }
        return STATE_RECORDING;
    } else {
        //检测是否可以获取录音结果

        readSize = audioRecord.read(point, 0, point.length);


        if (readSize <= 0) {
            if (audioRecord != null) {
                audioRecord.stop();
                audioRecord.release();
                audioRecord = null;

            }
            return STATE_NO_PERMISSION;

        } else {
            if (audioRecord != null) {
                audioRecord.stop();
                audioRecord.release();
                audioRecord = null;

            }

            return STATE_SUCCESS;
        }
    }
}
 
Example 19
Source File: MainActivity.java    From android-fskmodem with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
	
	/// INIT FSK CONFIG
	
	try {
		mConfig = new FSKConfig(FSKConfig.SAMPLE_RATE_44100, FSKConfig.PCM_16BIT, FSKConfig.CHANNELS_MONO, FSKConfig.SOFT_MODEM_MODE_4, FSKConfig.THRESHOLD_20P);
	} catch (IOException e1) {
		e1.printStackTrace();
	}

	/// INIT FSK DECODER
	
	mDecoder = new FSKDecoder(mConfig, new FSKDecoderCallback() {
		
		@Override
		public void decoded(byte[] newData) {
			
			final String text = new String(newData);
			
			runOnUiThread(new Runnable() {
				public void run() {
					
					TextView view = ((TextView) findViewById(R.id.result));
					
					view.setText(view.getText()+text);
				}
			});
		}
	});
	
	///
	
	//make sure that the settings of the recorder match the settings of the decoder
	//most devices cant record anything but 44100 samples in 16bit PCM format...
	mBufferSize = AudioRecord.getMinBufferSize(FSKConfig.SAMPLE_RATE_44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
	
	//scale up the buffer... reading larger amounts of data
	//minimizes the chance of missing data because of thread priority
	mBufferSize *= 10;
	
	//again, make sure the recorder settings match the decoder settings
	mRecorder = new AudioRecord(AudioSource.MIC, FSKConfig.SAMPLE_RATE_44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, mBufferSize);

	if (mRecorder.getState() == AudioRecord.STATE_INITIALIZED) {
		mRecorder.startRecording();
		
		//start a thread to read the audio data
		Thread thread = new Thread(mRecordFeed);
		thread.setPriority(Thread.MAX_PRIORITY);
		thread.start();
	}
	else {
		Log.i("FSKDecoder", "Please check the recorder settings, something is wrong!");
	}
}
 
Example 20
Source File: AudioSource.java    From science-journal with Apache License 2.0 4 votes vote down vote up
private void start() {
  // FYI: the current thread holds lockAudioReceivers.
  // Use VOICE_COMMUNICATION to filter out audio coming from the speakers
  final AudioRecord audioRecord =
      new AudioRecord(
          MediaRecorder.AudioSource.VOICE_COMMUNICATION,
          SAMPLE_RATE_IN_HZ,
          CHANNEL_CONFIG,
          AUDIO_FORMAT,
          minBufferSizeInBytes);
  if (audioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
    audioRecord.release();
    return;
  }

  audioRecord.startRecording();
  // AudioRecord.startRecording() logs an error but it has no return value and
  // doesn't throw an exception when someone else is using the mic.
  if (audioRecord.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING) {
    audioRecord.release();
    return;
  }

  running.set(true);
  future =
      executorService.submit(
          () -> {
            short[] buffer = new short[minBufferSizeInBytes / 2];
            int offset = 0;
            boolean goodDataRead = false;

            while (running.get()) {
              int readShorts = audioRecord.read(buffer, offset, buffer.length - offset);
              // On some devices (Moto E, for example) we get a bunch of zeros when we first
              // start reading. Ignore those zeros.
              if (!goodDataRead) {
                int countLeadingZeros = 0;
                while (countLeadingZeros < readShorts && buffer[countLeadingZeros] == 0) {
                  countLeadingZeros++;
                }
                if (countLeadingZeros > 0) {
                  if (readShorts > countLeadingZeros) {
                    System.arraycopy(
                        buffer, countLeadingZeros, buffer, 0, readShorts - countLeadingZeros);
                  }
                  readShorts -= countLeadingZeros;
                }
                goodDataRead = (readShorts > 0);
              }
              offset += readShorts;
              // If the buffer is full, call the Receivers.
              if (offset == buffer.length) {
                synchronized (lockAudioReceivers) {
                  for (AudioReceiver audioReceiver : audioReceivers) {
                    audioReceiver.onReceiveAudio(buffer);
                  }
                }
                offset = 0;
              }
            }

            audioRecord.stop();
            audioRecord.release();
          });
}