i am writing a code to record audio input using AudioRecorder a,d stop it automatically after a certain time.
But it doesnt stop, it continues trying to record, and gives a NullPointerException error.
here's the code, plz point out what is wrong with it.
But it doesnt stop, it continues trying to record, and gives a NullPointerException error.
here's the code, plz point out what is wrong with it.
Code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_raw_rec);
try
{
try {
startRecording();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new Timer().schedule(new TimerTask()
{
@Override
public void run()
{
if (null != recorder) {
recordingThread.interrupt();
recordingThread=null;
recorder.stop();
recorder.release();
recorder = null;
}
}
}
,3000);
}//end try
catch(IllegalStateException e) {
e.printStackTrace();
}
}
private void startRecording() throws IOException{
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,RECORDER_SAMPLERATE, RECORDER_CHANNELS,RECORDER_AUDIO_ENCODING, bufferSize);
recorder.startRecording();
isRecording = true;
recordingThread = new Thread(new Runnable() {
public void run() {
writeAudioDataToFile();
}
}, "AudioRecorder Thread");
recordingThread.start();
}
private void writeAudioDataToFile() {
// Write the output audio in byte
String filePath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/recordedSound.wav";
byte[] data= new byte[bufferSize];
while (isRecording) {
try{
recorder.read(data, 0, bufferSize);
}
catch (NullPointerException e)
{
e.printStackTrace();
}
System.out.println("writing to file" + data.toString());
try {
// // writes the data to file from buffer
// // stores the voice buffer
DataOutputStream dd=new DataOutputStream( new FileOutputStream(filePath));
dd.writeBytes("RIFF");
dd.writeInt(0); // Final file size not known yet, write 0
dd.writeBytes("WAVE");
dd.writeBytes("fmt ");
dd.writeInt(Integer.reverseBytes(16)); // Sub-chunk size, 16 for PCM
dd.writeShort(Short.reverseBytes((short) 1)); // AudioFormat, 1 for PCM
dd.writeShort(Short.reverseBytes( (short) myChannels));// Number of channels, 1 for mono, 2 for stereo
dd.writeInt(Integer.reverseBytes(RECORDER_SAMPLERATE)); // Sample rate
dd.writeInt(Integer.reverseBytes( (RECORDER_SAMPLERATE*myBitsPerSample*myChannels/8))); // Byte rate, SampleRate*NumberOfChannels*BitsPerSample/8
dd.writeShort(Short.reverseBytes((short) (myChannels*myBitsPerSample/8))); // Block align, NumberOfChannels*BitsPerSample/8
dd.writeShort(Short.reverseBytes( myBitsPerSample)); // Bits per sample
dd.writeBytes("data");
dd.write(data);
dd.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}