Skip to content

Commit

Permalink
Merge pull request #122 from Dimowner/fix_wav_header
Browse files Browse the repository at this point in the history
When start WAV recording write an empty header at the beginning of the file
  • Loading branch information
Dimowner authored Jun 2, 2024
2 parents ae64ebb + d226fa8 commit 86c8696
Showing 1 changed file with 15 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,11 @@
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Handler;

import com.dimowner.audiorecorder.AppConstants;
import com.dimowner.audiorecorder.exception.InvalidOutputFile;
import com.dimowner.audiorecorder.exception.RecorderInitException;
import com.dimowner.audiorecorder.exception.RecordingException;
import com.dimowner.audiorecorder.util.AndroidUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
Expand All @@ -35,10 +33,9 @@
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.concurrent.atomic.AtomicBoolean;

import timber.log.Timber;

import static com.dimowner.audiorecorder.AppConstants.RECORDING_VISUALIZATION_INTERVAL;
import androidx.annotation.RequiresPermission;

public class WavRecorder implements RecorderContract.Recorder {

Expand Down Expand Up @@ -86,6 +83,7 @@ public void setRecorderCallback(RecorderContract.RecorderCallback callback) {
}

@Override
@RequiresPermission(value = "android.permission.RECORD_AUDIO")
public void startRecording(String outputFile, int channelCount, int sampleRate, int bitrate) {
this.sampleRate = sampleRate;
// this.framesPerVisInterval = (int)((VISUALIZATION_INTERVAL/1000f)/(1f/sampleRate));
Expand Down Expand Up @@ -211,6 +209,7 @@ private void writeAudioDataToFile() {
fos = null;
}
if (null != fos) {
writeEmptyHeader(fos);
int chunksCount = 0;
ByteBuffer shortBuffer = ByteBuffer.allocate(2);
shortBuffer.order(ByteOrder.LITTLE_ENDIAN);
Expand Down Expand Up @@ -242,6 +241,7 @@ private void writeAudioDataToFile() {
}

try {
fos.flush();
fos.close();
} catch (IOException e) {
Timber.e(e);
Expand All @@ -251,7 +251,7 @@ private void writeAudioDataToFile() {
}

private void setWaveFileHeader(File file, int channels) {
long fileSize = file.length() - 8;
long fileSize = file.length() - 44;
long totalSize = fileSize + 36;
long byteRate = sampleRate * channels * (RECORDER_BPP/8); //2 byte per 1 sample for 1 channel.

Expand All @@ -267,6 +267,16 @@ private void setWaveFileHeader(File file, int channels) {
}
}

private void writeEmptyHeader(FileOutputStream fos) {
try {
byte[] header = new byte[44];
fos.write(header);
fos.flush();
} catch (IOException e) {
Timber.e(e);
}
}

private RandomAccessFile randomAccessFile(File file) {
RandomAccessFile randomAccessFile;
try {
Expand Down

0 comments on commit 86c8696

Please sign in to comment.