I have a function that records audio and saves it to a file. Here is what it looks like:
private void startRecord(){ File file = new File(Environment.getExternalStorageDirectory(), "test.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 minBufferSize = AudioRecord.getMinBufferSize(sampleFreq, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT); short[] audioData = new short[minBufferSize]; AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleFreq, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, minBufferSize); audioRecord.startRecording(); while(recording){ int numberOfShort = audioRecord.read(audioData, 0, minBufferSize); for(int i = 0; i < numberOfShort; i++){ dataOutputStream.writeShort(audioData[i]); } } audioRecord.stop(); dataOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } }
I have another function called playrecord that plays the recorded sound:
void playRecord(){ File file = new File(Environment.getExternalStorageDirectory(), "test.pcm"); int shortSizeInBytes = Short.SIZE/Byte.SIZE; int bufferSizeInBytes = (int)(file.length()/shortSizeInBytes); short[] audioData = new short[bufferSizeInBytes]; try { InputStream inputStream = new FileInputStream(file); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); DataInputStream dataInputStream = new DataInputStream(bufferedInputStream); int i = 0; while(dataInputStream.available() > 0){ audioData[i] = dataInputStream.readShort(); i++; } dataInputStream.close(); int sampleFreq = (Integer)spFrequency.getSelectedItem(); AudioTrack audioTrack = new AudioTrack( AudioManager.STREAM_MUSIC, sampleFreq, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSizeInBytes, AudioTrack.MODE_STREAM); audioTrack.play(); audioTrack.write(audioData, 0, bufferSizeInBytes); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
These two functions work fine. If I call startRecord () and then call playRecord, I can hear the sound. But I want to reproduce the sound in REAL time, i.e. as soon as I start recording, I want the sound to play. What should I do for this?
source share