First you need to know that the wav file has its own format - the header. therefore, you cannot just write clean data to a .wav file.
Secondly, the wav file header includes the length of the file. so you need to write a headline after recording.
My solution: AudioRecorder user writes pcm file.
byte[] audiodata = new byte[bufferSizeInBytes]; FileOutputStream fos = null; int readsize = 0; try { fos = new FileOutputStream(pcmFileName, true); } catch (FileNotFoundException e) { Log.e("AudioRecorder", e.getMessage()); } status = Status.STATUS_START; while (status == Status.STATUS_START && audioRecord != null) { readsize = audioRecord.read(audiodata, 0, bufferSizeInBytes); if (AudioRecord.ERROR_INVALID_OPERATION != readsize && fos != null) { if (readsize > 0 && readsize <= audiodata.length) fos.write(audiodata, 0, readsize); } catch (IOException e) { Log.e("AudioRecorder", e.getMessage()); } } } try { if (fos != null) { fos.close(); } } catch (IOException e) { Log.e("AudioRecorder", e.getMessage()); }
then convert it to a wav file.
byte buffer[] = null; int TOTAL_SIZE = 0; File file = new File(pcmPath); if (!file.exists()) { return false; } TOTAL_SIZE = (int) file.length(); WaveHeader header = new WaveHeader(); header.fileLength = TOTAL_SIZE + (44 - 8); header.FmtHdrLeth = 16; header.BitsPerSample = 16; header.Channels = 1; header.FormatTag = 0x0001; header.SamplesPerSec = 8000; header.BlockAlign = (short) (header.Channels * header.BitsPerSample / 8); header.AvgBytesPerSec = header.BlockAlign * header.SamplesPerSec; header.DataHdrLeth = TOTAL_SIZE; byte[] h = null; try { h = header.getHeader(); } catch (IOException e1) { Log.e("PcmToWav", e1.getMessage()); return false; } if (h.length != 44) return false; File destfile = new File(destinationPath); if (destfile.exists()) destfile.delete(); try { buffer = new byte[1024 * 4]; // Length of All Files, Total Size InputStream inStream = null; OutputStream ouStream = null; ouStream = new BufferedOutputStream(new FileOutputStream( destinationPath)); ouStream.write(h, 0, h.length); inStream = new BufferedInputStream(new FileInputStream(file)); int size = inStream.read(buffer); while (size != -1) { ouStream.write(buffer); size = inStream.read(buffer); } inStream.close(); ouStream.close(); } catch (FileNotFoundException e) { Log.e("PcmToWav", e.getMessage()); return false; } catch (IOException ioe) { Log.e("PcmToWav", ioe.getMessage()); return false; } if (deletePcmFile) { file.delete(); } Log.i("PcmToWav", "makePCMFileToWAVFile success!" + new SimpleDateFormat("yyyy-MM-dd hh:mm").format(new Date())); return true;
Joyie
source share