Solution 1 :
I think, you are doing file writing operation in main thread (UI thread), that’s why app freezes. Kindly do your file operation in another thread Eg. AsyncTask.
Keep in mind that “you do not do the operations which takes more than 5seconds & freezes app”.
Here, just sharing the overview of concept to be added:
Add this innerclass inside your activity file.
static class FileAsyncTask extends AsyncTask{
@Override
protected Object doInBackground(Object[] objects) {
// do your file writing stuff here....
return null;
}
@Override
protected void onProgressUpdate(Object[] values) {
super.onProgressUpdate(values);
// update UI - if the file writig is success / failed
}
}
call this async task in your activity file when file need to be written:
new FileAsyncTask().execute(...);
Problem :
I am a beginner in android development and I am stuck. Here, I am recording voice using audiorecorder
instead of mediarecorder
to use noise cancellation feature and I am writing a PCM file from the buffer to an output file and when I include the function for writing the file from the buffer the app just don’t respond. it records and saves the file but freezes.
can somebody tell me what’s wrong?
private void writeAudioDataToFile() {
// Write the output audio in byte
bufferSizeInBytes = AudioRecord.getMinBufferSize(
RECORDER_SAMPLERATE,
RECORDER_CHANNELS,
RECORDER_AUDIO_ENCODING
);
String filePath = "/sdcard/voice8K16bitmono.wav";
short sData[] = new short[bufferSizeInBytese/2];
FileOutputStream os = null;
try {
os = new FileOutputStream(filePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (isRecording) {
// gets the voice output from microphone to byte format
ar.read(sData, 0, bufferSizeInBytese/2);
Log.d("eray","Short wirting to file" + sData.toString());
try {
// // writes the data to file from buffer
// // stores the voice buffer
byte bData[] = short2byte(sData);
os.write(bData, 0, bufferSizeInBytes);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private byte[] short2byte(short[] sData) {
int shortArrsize = sData.length;
byte[] bytes = new byte[shortArrsize * 2];
for (int i = 0; i < shortArrsize; i++) {
bytes[i * 2] = (byte) (sData[i] & 0x00FF);
bytes[(i * 2) + 1] = (byte) (sData[i] >> 8);
sData[i] = 0;
}
return bytes;
}
Comments
Comment posted by pear rose
thank you for the idea but i am not able to get the variable value to the thread class from the main class .I want to get the filepath from main class but in log it shows null.
Comment posted by PushpaSakthi
Please pass filepath using new FileAsyncTask().execute(filepath);. And get that filepath in doInBackground of asynctask.
Comment posted by PushpaSakthi
If you are new to asynctask, pls go through it.
Comment posted by Luis A. Florit
Also a newbie here, but: why is your