Code example for RandomAccessFile

Methods: setLength, writeBytes, writeInt, writeShort

0
	public void prepare() { 
		try { 
			if (state == State.INITIALIZING) {
				if ((audioRecorder.getState() == AudioRecord.STATE_INITIALIZED) & (filePath != null)) {
					// write file header 
					randomAccessWriter = new RandomAccessFile(filePath, "rw");
					randomAccessWriter.setLength(0); // Set file length to 0, to prevent unexpected behavior in case the file already existed
					randomAccessWriter.writeBytes("RIFF");
					randomAccessWriter.writeInt(0); // Final file size not known yet, write 0 
					randomAccessWriter.writeBytes("WAVE");
					randomAccessWriter.writeBytes("fmt ");
					randomAccessWriter.writeInt(Integer.reverseBytes(16)); // Sub-chunk size, 16 for PCM
					randomAccessWriter.writeShort(Short.reverseBytes((short) 1)); // AudioFormat, 1 for PCM
					randomAccessWriter.writeShort(Short.reverseBytes(nChannels));// Number of channels, 1 for mono, 2 for stereo
					randomAccessWriter.writeInt(Integer.reverseBytes(sRate)); // Sample rate
					randomAccessWriter.writeInt(Integer.reverseBytes(sRate*nChannels*mBitsPersample/8)); // Byte rate, SampleRate*NumberOfChannels*mBitsPersample/8
					randomAccessWriter.writeShort(Short.reverseBytes((short)(nChannels*mBitsPersample/8))); // Block align, NumberOfChannels*mBitsPersample/8
					randomAccessWriter.writeShort(Short.reverseBytes(mBitsPersample)); // Bits per sample
					randomAccessWriter.writeBytes("data");
					randomAccessWriter.writeInt(0); // Data chunk size not known yet, write 0
					buffer = new byte[mPeriodInFrames*mBitsPersample/8*nChannels];
					state = State.READY;
				} else { 
					Log.e(WavAudioRecorder.class.getName(), "prepare() method called on uninitialized recorder");
					state = State.ERROR;