这是我用于录制电话的代码。我也在使用异步任务但是当我的文件被记录时手机冻结了。录制呼叫并将文件保存在外部存储中,然后从存储中复制该文件并上传到url fot transaltion,我使用的程序,但我的屏幕冻结了此目的。任何人都可以帮助我摆脱这个问题
public class WavRecorder extends AsyncTask<Void, Double, Void> {
private static final String TAG = "--DEBUG---";
private static final int RECORDER_BPP = 16;
private static final String AUDIO_RECORDER_FILE_EXT_WAV = ".wav";
private static final String AUDIO_RECORDER_FOLDER = "AudioRecorder";
private static final String AUDIO_RECORDER_TEMP_FILE = "record_temp.raw";
FileOutputStream os = null;
int bufferSize;
int frequency = 44100; //8000;
int channelConfiguration = AudioFormat.CHANNEL_IN_MONO;
int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
boolean started = false;
short threshold = 15000;
int noisetime = 1500;
Handler hd;
AudioRecord audioRecord;
private OnRecorderresponse mListener;
public interface OnRecorderresponse {
public void OnAudioFileSaved(String FilePath);
public void OnSpeechToTextRecognized(String Text);
}
public WavRecorder(OnRecorderresponse listener)
{
this.mListener = listener;
}
public void setStarted(boolean started) {
this.started = started;
hd = new Handler();
}
@Override
protected Void doInBackground(Void... arg0) {
Looper.prepare();
Log.e(TAG, "doInBackground");
try {
final String filename = getTempFilename();
try {
os = new FileOutputStream(filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bufferSize = AudioRecord.getMinBufferSize(frequency,
channelConfiguration, audioEncoding);
Log.e("Buffersize",""+bufferSize);
audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, frequency,
channelConfiguration, audioEncoding, bufferSize);
Log.e("Buffersize",""+audioRecord);
short[] buffer = new short[bufferSize];
audioRecord.startRecording();
Runnable sendData = new Runnable() {
public void run() {
Log.e("Running","yes");
copyWaveFile(getTempFilename(), getFilename());
deleteTempFile();
try {
Log.e(TAG,"Check for file :: "+filename);
os = new FileOutputStream(filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
};
while (started) {
int bufferReadResult = audioRecord.read(buffer, 0, bufferSize);
if (AudioRecord.ERROR_INVALID_OPERATION != bufferReadResult) {
//check signal
//put a threshold
int foundPeak = searchThreshold(buffer, threshold);
byte[] byteBuffer = ShortToByte(buffer, bufferReadResult);
try {
os.write(byteBuffer);
} catch (IOException e) {
e.printStackTrace();
}
if (foundPeak > -1) { //found signal
//record signal
hd.removeCallbacks(sendData);
hd.postDelayed(sendData, noisetime);
} else {//count the time
//don't save signal
}
Log.e(TAG, "foundPeak");
}
}
audioRecord.stop();
Log.e(TAG, "Stoped");
//close file
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
copyWaveFile(getTempFilename(), getFilename());
deleteTempFile();
} catch (Throwable t) {
t.printStackTrace();
Log.e("AudioRecord", "Recording Failed");
}
return null;
}
byte[] ShortToByte(short[] input, int elements) {
int short_index, byte_index;
int iterations = elements; //input.length;
byte[] buffer = new byte[iterations * 2];
short_index = byte_index = 0;
for (/*NOP*/; short_index != iterations; /*NOP*/) {
buffer[byte_index] = (byte) (input[short_index] & 0x00FF);
buffer[byte_index + 1] = (byte) ((input[short_index] & 0xFF00) >> 8);
++short_index;
byte_index += 2;
}
return buffer;
}
int searchThreshold(short[] arr, short thr) {
int peakIndex;
int arrLen = arr.length;
for (peakIndex = 0; peakIndex < arrLen; peakIndex++) {
if ((arr[peakIndex] >= thr) || (arr[peakIndex] <= -thr)) {
//se supera la soglia, esci e ritorna peakindex-mezzo kernel.
return peakIndex;
}
}
return -1; //not found
}
private String getFilename() {
Log.e("Tag", "Entered in getfilename");
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath, AUDIO_RECORDER_FOLDER);
if (!file.exists()) {
Log.e("Tag","File is not exist,make dirs");
file.mkdirs();
}
return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + AUDIO_RECORDER_FILE_EXT_WAV);
}
private String getTempFilename() {
Log.e("Tag", "Entered in gettempfilename");
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath, AUDIO_RECORDER_FOLDER);
Log.e("gettempfilename",""+file);
if (!file.exists()) {
file.mkdirs();
}
File tempFile = new File(filepath, AUDIO_RECORDER_TEMP_FILE);
if (tempFile.exists())
tempFile.delete();
return (file.getAbsolutePath() + "/" + AUDIO_RECORDER_TEMP_FILE);
}
private void deleteTempFile() {
File file = new File(getTempFilename());
file.delete();
}
private void copyWaveFile(String inFilename, final String outFilename) {
Log.e("Tag", "Enteredin copywavefile");
FileInputStream in = null;
FileOutputStream out = null;
long totalAudioLen = 0;
long totalDataLen = totalAudioLen + 36;
long longSampleRate = frequency;
int channels = 1;
long byteRate = RECORDER_BPP * frequency * channels / 8;
byte[] data = new byte[bufferSize];
try {
in = new FileInputStream(inFilename);
out = new FileOutputStream(outFilename);
totalAudioLen = in.getChannel().size();
totalDataLen = totalAudioLen + 36;
WriteWaveFileHeader(out, totalAudioLen, totalDataLen,
longSampleRate, channels, byteRate);
while (in.read(data) != -1) {
out.write(data);
}
in.close();
out.close();
// callback
mListener.OnAudioFileSaved(outFilename);
Log.e("ouitputfilename", outFilename);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void WriteWaveFileHeader(
FileOutputStream out, long totalAudioLen,
long totalDataLen, long longSampleRate, int channels,
long byteRate) throws IOException {
Log.e("Tag","Entered in WriteWaveFileHeader");
byte[] header = new byte[44];
header[0] = 'R'; // RIFF/WAVE header
header[1] = 'I';
header[2] = 'F';
header[3] = 'F';
header[4] = (byte) (totalDataLen & 0xff);
header[5] = (byte) ((totalDataLen >> 8) & 0xff);
header[6] = (byte) ((totalDataLen >> 16) & 0xff);
header[7] = (byte) ((totalDataLen >> 24) & 0xff);
header[8] = 'W';
header[9] = 'A';
header[10] = 'V';
header[11] = 'E';
header[12] = 'f'; // 'fmt ' chunk
header[13] = 'm';
header[14] = 't';
header[15] = ' ';
header[16] = 16; // 4 bytes: size of 'fmt ' chunk
header[17] = 0;
header[18] = 0;
header[19] = 0;
header[20] = 1; // format = 1
header[21] = 0;
header[22] = (byte) channels;
header[23] = 0;
header[24] = (byte) (longSampleRate & 0xff);
header[25] = (byte) ((longSampleRate >> 8) & 0xff);
header[26] = (byte) ((longSampleRate >> 16) & 0xff);
header[27] = (byte) ((longSampleRate >> 24) & 0xff);
header[28] = (byte) (byteRate & 0xff);
header[29] = (byte) ((byteRate >> 8) & 0xff);
header[30] = (byte) ((byteRate >> 16) & 0xff);
header[31] = (byte) ((byteRate >> 24) & 0xff);
header[32] = (byte) (channels * 16 / 8); // block align
header[33] = 0;
header[34] = RECORDER_BPP; // bits per sample
header[35] = 0;
header[36] = 'd';
header[37] = 'a';
header[38] = 't';
header[39] = 'a';
header[40] = (byte) (totalAudioLen & 0xff);
header[41] = (byte) ((totalAudioLen >> 8) & 0xff);
header[42] = (byte) ((totalAudioLen >> 16) & 0xff);
header[43] = (byte) ((totalAudioLen >> 24) & 0xff);
out.write(header, 0, 44);
}
}