Code example for RandomAccessFile

Methods: setLength, writeBytes, writeInt, writeShort

0
		try { 
			if (mState == State.INITIALIZING) {
				if ((mRecorder.getState() == AudioRecord.STATE_INITIALIZED) && (mPath != null)) {
					// write file header 
 
					mRAFile = new RandomAccessFile(mPath, "rw");
 
					// Set file length to 0, to prevent unexpected behavior in case the file already existed 
					mRAFile.setLength(0);
					mRAFile.writeBytes("RIFF");
					mRAFile.writeInt(0); // Final file size not known yet, write 0
					mRAFile.writeBytes("WAVE");
					mRAFile.writeBytes("fmt ");
					mRAFile.writeInt(Integer.reverseBytes(16)); // Sub-chunk size, 16 for PCM
					mRAFile.writeShort(Short.reverseBytes((short) 1)); // AudioFormat, 1 for PCM
					mRAFile.writeShort(Short.reverseBytes(mChannels));// Number of channels, 1 for mono, 2 for stereo
					mRAFile.writeInt(Integer.reverseBytes(mRate)); // Sample rate
					mRAFile.writeInt(Integer.reverseBytes(mRate * (mResolution/8) * mChannels)); // Byte rate, SampleRate*NumberOfChannels*BitsPerSample/8
					mRAFile.writeShort(Short.reverseBytes((short)(mChannels * mResolution/8))); // Block align, NumberOfChannels*BitsPerSample/8
					mRAFile.writeShort(Short.reverseBytes(mResolution)); // Bits per sample
					mRAFile.writeBytes("data");
					mRAFile.writeInt(0); // Data chunk size not known yet, write 0
 
					mBuffer = new byte[mFramePeriod * (mResolution/8) * mChannels];
					mState = State.READY;
				} else { 
					Log.e(LOG_TAG, "prepare() method called on uninitialized recorder");