1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.speechrecorder; 18 19import java.io.IOException; 20import java.io.InputStream; 21 22import android.media.AudioRecord; 23 24import static android.media.AudioFormat.CHANNEL_IN_MONO; 25import static android.media.AudioFormat.ENCODING_PCM_16BIT; 26import static android.media.MediaRecorder.AudioSource.VOICE_RECOGNITION; 27 28/** 29 * Provides an InputStream like API over {@code android.media.AudioRecord}. 30 * 31 * <b>Not thread safe.</b> 32 */ 33public final class MicrophoneInputStream extends InputStream { 34 35 private final int mSampleRate; 36 private final int mBufferSize; 37 private final AudioRecord mAudioRecord; 38 39 private boolean mRecording; 40 41 public MicrophoneInputStream(int sampleRate) throws IOException { 42 mSampleRate = sampleRate; 43 mBufferSize = AudioRecord.getMinBufferSize(sampleRate, 44 CHANNEL_IN_MONO, ENCODING_PCM_16BIT); 45 mAudioRecord = createAudioRecord(); 46 mRecording = false; 47 } 48 49 private AudioRecord createAudioRecord() throws IOException { 50 AudioRecord ar = new AudioRecord(VOICE_RECOGNITION, 51 mSampleRate, CHANNEL_IN_MONO, ENCODING_PCM_16BIT, mBufferSize); 52 53 if (ar.getState() != AudioRecord.STATE_INITIALIZED) { 54 ar.release(); 55 throw new IOException("Unable to create AudioRecord"); 56 } 57 58 return ar; 59 } 60 61 private void maybeStartRecording() throws IOException { 62 if (mRecording) { 63 return; 64 } 65 66 mAudioRecord.startRecording(); 67 68 int recordingState = mAudioRecord.getRecordingState(); 69 if (recordingState != AudioRecord.RECORDSTATE_RECORDING) { 70 throw new IOException("Unexpected recordingState: " + recordingState); 71 } 72 mRecording = true; 73 } 74 75 @Override 76 public int read() throws IOException { 77 throw new UnsupportedOperationException("Single byte read."); 78 } 79 80 @Override 81 public int read(byte[] b, int offset, int length) throws IOException { 82 maybeStartRecording(); 83 84 final int ret = mAudioRecord.read(b, offset, length); 85 if (ret == AudioRecord.ERROR_INVALID_OPERATION || 86 ret == AudioRecord.ERROR_BAD_VALUE) { 87 throw new IOException("AudioRecord.read returned: " + ret); 88 } 89 90 return ret; 91 } 92 93 @Override 94 public void close() throws IOException { 95 mAudioRecord.stop(); 96 mAudioRecord.release(); 97 } 98} 99