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

The following examples show how to use android.media.AudioRecord#stop() . 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: 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 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: MainActivity.java    From android-apps with MIT License 5 votes vote down vote up
private void startRecord(){
	File file = new File(Environment.getExternalStorageDirectory(), "record.pcm");
	int sampleFreq = (Integer)spFrequency.getSelectedItem();
	
	try{
		file.createNewFile();
		
		OutputStream outputStream = new FileOutputStream(file);
		BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
		DataOutputStream dataOutputStream = new DataOutputStream(bufferedOutputStream);
		
		int minBufferedSize = AudioRecord.getMinBufferSize(sampleFreq, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);
		
		short[] audioData = new short[minBufferedSize];
		
		AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleFreq, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, minBufferedSize);
		audioRecord.startRecording();
		
		while (recording) {
			int numberOfShort = audioRecord.read(audioData, 0, minBufferedSize);
			for(int i = 0; i < numberOfShort; i++){
				dataOutputStream.writeShort(audioData[i]);
			}
		}
		
		audioRecord.stop();
		dataOutputStream.close();
		
	} catch(Exception ex){
		ex.printStackTrace();
	}
}
 
Example 5
Source File: AudioRecordingThread.java    From AndroidRecording with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
	FileOutputStream out = prepareWriting();
	if (out == null) { return; }
	
	AudioRecord record = new AudioRecord(AudioSource.VOICE_RECOGNITION, /*AudioSource.MIC*/
			    			 SAMPLING_RATE,
			    			 AudioFormat.CHANNEL_IN_MONO,
			    			 AudioFormat.ENCODING_PCM_16BIT,
			    			 bufferSize);
 record.startRecording();
	
 int read = 0;
 while (isRecording) {
	    read = record.read(audioBuffer, 0, bufferSize);
    
	    if ((read == AudioRecord.ERROR_INVALID_OPERATION) || 
	    	(read == AudioRecord.ERROR_BAD_VALUE) ||
	    	(read <= 0)) {
	    	continue;
	    }
	    
    	proceed();
	    write(out);
 }
   
 record.stop();
 record.release();
   
 finishWriting(out);
 convertRawToWav();
}
 
Example 6
Source File: Recorder.java    From VideoAndroid with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);

    // Audio
    int bufferSize;
    ShortBuffer audioData;
    int bufferReadResult;

    bufferSize = AudioRecord.getMinBufferSize(sampleAudioRateInHz,
            AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
    mAudioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleAudioRateInHz,
            AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);

    audioData = ShortBuffer.allocate(bufferSize);

    mAudioRecord.startRecording();

    /* ffmpeg_audio encoding loop */
    while (mRunAudioThread) {
        //获取音频数据
        bufferReadResult = mAudioRecord.read(audioData.array(), 0, audioData.capacity());
        audioData.limit(bufferReadResult);
        if (bufferReadResult > 0) {
            if(mFFmpegFrameRecorder != null && mRecording) {
                try {
                    mFFmpegFrameRecorder.recordSamples(audioData);      //写入音频数据
                } catch (FFmpegFrameRecorder.Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /* encoding finish, release recorder */
    if (mAudioRecord != null) {
        mAudioRecord.stop();
        mAudioRecord.release();
    }
}
 
Example 7
Source File: MediaAudioEncoder.java    From UVCCameraZxing with Apache License 2.0 5 votes vote down vote up
@Override
 	public void run() {
 		try {
          final int buf_sz = AudioRecord.getMinBufferSize(
          	SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT) * 4;
          final AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
          	SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, buf_sz);
          try {
          	if (mIsCapturing) {
  				if (DEBUG) Log.v(TAG, "AudioThread:start audio recording");
               final byte[] buf = new byte[buf_sz];
               int readBytes;
               audioRecord.startRecording();
               try {
	    		while (mIsCapturing && !mRequestStop && !mIsEOS) {
	    			// read audio data from internal mic
	    			readBytes = audioRecord.read(buf, 0, buf_sz);
	    			if (readBytes > 0) {
	    			    // set audio data to encoder
	    				encode(buf, readBytes, getPTSUs());
	    				frameAvailableSoon();
	    			}
	    		}
   				frameAvailableSoon();
               } finally {
               	audioRecord.stop();
               }
          	}
          } finally {
          	audioRecord.release();
          }
 		} catch (final Exception e) {
 			Log.e(TAG, "AudioThread#run", e);
 		}
if (DEBUG) Log.v(TAG, "AudioThread:finished");
 	}
 
Example 8
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 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: 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 11
Source File: CheckPermission.java    From EasyPhotos 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;
            LogUtil.d("录音机被占用");
        }
        return STATE_RECORDING;
    } else {
        //检测是否可以获取录音结果

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


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

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

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

            }

            return STATE_SUCCESS;
        }
    }
}
 
Example 12
Source File: MicrophoneCollector.java    From sensordatacollector with GNU General Public License v2.0 4 votes vote down vote up
private void doTask()
{
    // http://stackoverflow.com/questions/10655703/what-does-androids-getmaxamplitude-function-for-the-mediarecorder-actually-gi

    int bufferSize = AudioRecord.getMinBufferSize(44100, AudioFormat.CHANNEL_IN_DEFAULT, AudioFormat.ENCODING_PCM_16BIT);
    // making the buffer bigger....
    bufferSize = bufferSize * 4;
    // AudioRecord recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, 44100, AudioFormat.CHANNEL_IN_DEFAULT, AudioFormat.ENCODING_PCM_16BIT, bufferSize);
    AudioRecord recorder = findAudioRecord();
    if(recorder == null) {
        Activity main = ActivityController.getInstance().get("MainActivity");
        if(main != null) {
            Utils.makeToast2(main, R.string.sensor_microphone_error, Toast.LENGTH_SHORT);
        }

        return;
    }

    short data[] = new short[bufferSize];
    double average = 0.0;
    recorder.startRecording();
    // recording data;
    recorder.read(data, 0, bufferSize);

    recorder.stop();
    for(short s : data) {
        if(s > 0) {
            average += Math.abs(s);
        } else {
            bufferSize--;
        }
    }
    // x=max;
    double x = average / bufferSize;
    recorder.release();
    double db;
    if(x == 0) {
        Log.w("TAG", "Warning no sound captured!");
        return;
    }
    // calculating the pascal pressure based on the idea that the max
    // amplitude (between 0 and 32767) is
    // relative to the pressure
    double pressure = x / 51805.5336; // the value 51805.5336 can be derived
    // from asuming that x=32767=0.6325
    // Pa and x=1 = 0.00002 Pa (the
    // reference value)
    db = (20 * Math.log10(pressure / 0.00002));
    if(db < 0) {
        return;
    }

    // if( mRecorder == null )
    // return;

    // float maxVolume = (float)(20 * Math.log10(mRecorder.getMaxAmplitude()
    // / 2700.0));

    long time = System.currentTimeMillis();
    ContentValues newValues = new ContentValues();
    newValues.put(valueNames[0], db);
    newValues.put(valueNames[1], time);

    if(db == Double.NEGATIVE_INFINITY || db == Double.POSITIVE_INFINITY || db == Double.NaN) {
        return;
    }

    String deviceID = DeviceID.get(SensorDataCollectorService.getInstance());
    MicrophoneCollector.updateLivePlotter(deviceID, new float[]{ (float) db });
    MicrophoneCollector.writeDBStorage(deviceID, newValues);
}
 
Example 13
Source File: TLMediaAudioEncoder.java    From TimeLapseRecordingSample with Apache License 2.0 4 votes vote down vote up
@Override
protected void recordingLoop() {
	android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
	try {
		final int min_buffer_size = AudioRecord.getMinBufferSize(
				mSampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
		int buffer_size = SAMPLES_PER_FRAME * FRAMES_PER_BUFFER;
		if (buffer_size < min_buffer_size)
			buffer_size = ((min_buffer_size / SAMPLES_PER_FRAME) + 1) * SAMPLES_PER_FRAME * 2;

		final AudioRecord audioRecord = new AudioRecord(
			MediaRecorder.AudioSource.MIC, mSampleRate,
			AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, buffer_size);
		try {
			if ((audioRecord.getState() == AudioRecord.STATE_INITIALIZED) && (mIsRunning)) {
				if (DEBUG) Log.v(TAG, "AudioThread:start_from_encoder audio recording");
				final ByteBuffer buf = ByteBuffer.allocateDirect(SAMPLES_PER_FRAME);
				int readBytes;
				audioRecord.startRecording();
				try {
					while (mIsRunning && isRecording()) {
						// read audio data from internal mic
						buf.clear();
						readBytes = audioRecord.read(buf, SAMPLES_PER_FRAME);
						if (readBytes > 0) {
							// set audio data to encoder
							encode(buf, readBytes, getPTSUs());
							frameAvailableSoon();
						}
					}
					frameAvailableSoon();
				} finally {
					audioRecord.stop();
				}
			}
		} finally {
			audioRecord.release();
		}
	} catch (Exception e) {
		Log.e(TAG, "AudioThread#run", e);
	} finally {
		android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_DEFAULT);
	}
}
 
Example 14
Source File: Record.java    From SinVoiceDemo with Apache License 2.0 4 votes vote down vote up
public void start() {
    if (STATE_STOP == mState) {
        mState = STATE_START;

        switch (mChannel) {
        case CHANNEL_1:
            mChannelConfig = AudioFormat.CHANNEL_IN_MONO;
            break;
        case CHANNEL_2:
            mChannelConfig = AudioFormat.CHANNEL_IN_STEREO;
            break;
        }

        switch (mBits) {
        case BITS_8:
            mAudioEncoding = AudioFormat.ENCODING_PCM_8BIT;
            break;

        case BITS_16:
            mAudioEncoding = AudioFormat.ENCODING_PCM_16BIT;
            break;
        }

        int minBufferSize = AudioRecord.getMinBufferSize(mFrequence, mChannelConfig, mAudioEncoding);
        LogHelper.d(TAG, "minBufferSize:" + minBufferSize);

        AudioRecord record = new AudioRecord(MediaRecorder.AudioSource.MIC, mFrequence, mChannelConfig, mAudioEncoding, mBufferSize);
        record.startRecording();
        LogHelper.d(TAG, "record start");

        if (null != mCallback) {
            if (null != mListener) {
                mListener.onStartRecord();
            }

            while (STATE_START == mState) {
                BufferData data = mCallback.getRecordBuffer();
                if (null != data) {
                    if (null != data.byteData) {
                        int bufferReadResult = record.read(data.byteData, 0, mBufferSize);
                        data.setFilledSize(bufferReadResult);

                        mCallback.freeRecordBuffer(data);
                    } else {
                        // end of input
                        LogHelper.d(TAG, "get end input data, so stop");
                        break;
                    }
                } else {
                    LogHelper.d(TAG, "get null data");
                    break;
                }
            }

            if (null != mListener) {
                mListener.onStopRecord();
            }
        }

        record.stop();
        record.release();

        LogHelper.d(TAG, "record stop");
    }
}
 
Example 15
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 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: 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 18
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 19
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 20
Source File: SoundFile.java    From YTPlayer with GNU General Public License v3.0 4 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 = 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.
}