Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.varma.samples.audiorecorder;
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import android.app.Activity;
- import android.media.AudioFormat;
- import android.media.AudioManager;
- import android.media.AudioRecord;
- import android.media.AudioTrack;
- import android.media.MediaRecorder;
- import android.os.Bundle;
- import android.os.Environment;
- import android.util.Log;
- import android.view.View;
- import android.widget.Button;
- import android.widget.TextView;
- import android.widget.Toast;
- public class RecorderActivity extends Activity {
- 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";
- private static final int RECORDER_SAMPLERATE = 44100;//44100; //18000
- private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_STEREO;
- private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
- String store;
- private AudioRecord recorder = null;
- private int bufferSize = 0;
- private Thread recordingThread = null;
- private boolean isRecording = false;
- int sample;
- double sampleRate;
- double duration;
- //double duration2;
- double time;
- double f1;
- double f2;
- double amplitude1;
- double amplitude2;
- double sineWave1;
- double sineWave2;
- float[] buffer1;
- float[] buffer2;
- byte[] byteBuffer1;
- byte[] byteBuffer2;
- byte[] byteBufferFinal;
- int bufferIndex;
- short x;
- short y;
- AudioTrack audioTrack;
- byte[] leftChannelAudioData;
- byte [] rightChannelAudioData;
- Button btnPlay;
- private static final String TAG = RecorderActivity.class.getSimpleName();
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- // Log.d(TAG, "Hello");
- //Toast.makeText(getApplicationContext(), "TEST", Toast.LENGTH_LONG).show();
- setButtonHandlers();
- enableButtons(false);
- btnPlay = (Button)findViewById(R.id.btnPlay);
- bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,RECORDER_CHANNELS,RECORDER_AUDIO_ENCODING);
- sampleRate = 44100.0;
- duration = 13.0;
- f1 = 1400.0; //100.0;
- //f1 = 18000.0;
- amplitude1= 1;
- f2 = 500.0;
- //f2 = 0;//19000.0;
- amplitude2 = 1;
- /* Original */
- buffer1 = new float[(int)(duration*sampleRate)];
- buffer2 = new float[(int)(duration*sampleRate)];
- //buffer1 = new float[(int)(sampleRate)];
- //buffer2 = new float[(int)(sampleRate)];
- for(sample = 0; sample < buffer1.length; sample ++){
- time = sample / sampleRate;
- buffer1[sample] = (float)(amplitude1*Math.sin(2*Math.PI*f1*time));
- buffer2[sample] = (float)(amplitude2*Math.sin(2*Math.PI*f2*time));
- //Toast.makeText(getApplicationContext(), "IN", Toast.LENGTH_LONG).show();
- }
- byteBuffer1 = new byte[buffer1.length*2]; //two bytes per audio frame, 16 bits
- for(int i = 0, bufferIndex=0; i < byteBuffer1.length; i++){
- x = (short) (buffer1[bufferIndex++]*32767.0); // [2^16 - 1]/2 = 32767.0
- byteBuffer1[i] = (byte) x; // low byte
- byteBuffer1[++i] = (byte) (x >>> 8); // high byte
- }
- byteBuffer2 = new byte[buffer2.length*2];
- for(int j = 0, bufferIndex=0; j < byteBuffer2.length; j++){
- y = (short) (buffer2[bufferIndex++]*32767.0);
- byteBuffer2[j] = (byte) y; // low byte
- byteBuffer2[++j] = (byte) (y >>> 8); // high byte
- }
- byteBufferFinal = new byte[byteBuffer1.length*2];
- //LL RR LL RR LL RR
- for(int k = 0, index = 0; index < byteBufferFinal.length - 4; k=k+2){
- byteBufferFinal[index] = byteBuffer1[k]; // LEFT {0,1/4,5/8,9/12,13;...}
- byteBufferFinal[index+1] = byteBuffer1[k+1];
- index = index + 2;
- byteBufferFinal[index] = byteBuffer2[k]; // RIGHT {2,3/6,7/10,11;...}
- byteBufferFinal[index+1] = byteBuffer2[k+1];
- index = index + 2;
- }
- /* int stereo=audioTrack.setStereoVolume(0.0f, 0.1f);
- Log.d("GREC", "Stereo vol: "+stereo);
- System.out.println("LOOK HERE " +stereo);
- final String promptStartRecord =
- "startRecord123()\n";
- Toast.makeText(RecorderActivity.this,
- promptStartRecord,
- Toast.LENGTH_LONG).show();
- */
- //recorder = new AudioRecord(MediaRecorder.AudioSource.CAMCORDER,
- // RECORDER_SAMPLERATE, RECORDER_CHANNELS,RECORDER_AUDIO_ENCODING, bufferSize);
- }
- private void setButtonHandlers() {
- ((Button)findViewById(R.id.btnStart)).setOnClickListener(btnClick);
- ((Button)findViewById(R.id.btnStop)).setOnClickListener(btnClick);
- ((Button)findViewById(R.id.btnPlay)).setOnClickListener(btnClick);
- }
- private void enableButton(int id,boolean isEnable){
- ((Button)findViewById(id)).setEnabled(isEnable);
- }
- private void enableButtons(boolean isRecording) {
- enableButton(R.id.btnStart,!isRecording);
- enableButton(R.id.btnStop,isRecording);
- enableButton(R.id.btnPlay, isRecording);
- }
- private String getFilename(){
- String filepath = Environment.getExternalStorageDirectory().getPath();
- File file = new File(filepath,AUDIO_RECORDER_FOLDER);
- if(!file.exists()){
- file.mkdirs();
- }
- store = file.getAbsolutePath() + "/" + System.currentTimeMillis() + AUDIO_RECORDER_FILE_EXT_WAV;
- //return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + AUDIO_RECORDER_FILE_EXT_WAV);
- return store;
- }
- private String getTempFilename(){
- String filepath = Environment.getExternalStorageDirectory().getPath();
- File file = new File(filepath,AUDIO_RECORDER_FOLDER);
- 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 startRecording(){
- recorder = new AudioRecord(MediaRecorder.AudioSource.CAMCORDER,
- RECORDER_SAMPLERATE, RECORDER_CHANNELS,RECORDER_AUDIO_ENCODING, bufferSize);
- /* AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
- (int) RECORDER_SAMPLERATE,AudioFormat.CHANNEL_OUT_STEREO,
- AudioFormat.ENCODING_PCM_16BIT, bufferSize,
- AudioTrack.MODE_STREAM);
- */
- audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
- (int) sampleRate,AudioFormat.CHANNEL_OUT_STEREO,
- AudioFormat.ENCODING_PCM_16BIT,byteBufferFinal.length,
- AudioTrack.MODE_STATIC);
- // int stereo=audioTrack.setStereoVolume(0.0f, 1.0f);
- //Log.d("SIAN", "STEREO IS " + stereo);
- audioTrack.write(byteBufferFinal, 0, byteBufferFinal.length);
- audioTrack.play();
- audioTrack.setPlaybackRate(RECORDER_SAMPLERATE);
- final byte[] buffer = new byte[bufferSize];
- recorder.startRecording();
- /*byte[] byteBufferFinal = new byte[bufferSize*2];
- recorder.read(buffer, 0, bufferSize);
- for(int k = 0, index = 0; index < byteBufferFinal.length - 4; k=k+2){
- byteBufferFinal[index] = buffer[k]; // LEFT {0,1/4,5/8,9/12,13;...}
- // System.out.println(byteBufferFinal[index]);
- byteBufferFinal[index+1] = buffer[k+1];
- // System.out.println(byteBufferFinal[index+1]);
- index = index + 2;
- byteBufferFinal[index] =0; //byteBuffer2[k]; // RIGHT {2,3/6,7/10,11;...}
- // System.out.println(byteBufferFinal[index]);
- byteBufferFinal[index+1] =0;// byteBuffer2[k+1];
- // System.out.println(byteBufferFinal[index+1]);
- index = index + 2;
- }
- */
- /*
- audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
- (int) RECORDER_SAMPLERATE,AudioFormat.CHANNEL_OUT_STEREO,
- AudioFormat.ENCODING_PCM_16BIT,byteBufferFinal.length,
- AudioTrack.MODE_STATIC);
- audioTrack.write( byteBufferFinal, 0, bufferSize*2);
- audioTrack.play();
- */
- isRecording = true;
- recordingThread = new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- writeAudioDataToFile();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- },"AudioRecorder Thread");
- recordingThread.start();
- }
- @SuppressWarnings("null")
- private void writeAudioDataToFile() throws IOException{
- int read = 0;
- byte data[] = new byte[bufferSize];
- //short[] shortData = new short[bufferSize];
- String filename = getTempFilename();
- FileOutputStream os = null;
- try {
- os = new FileOutputStream(filename);
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- if(null != os){
- while(isRecording){
- read = recorder.read(data, 0, bufferSize);
- /* Self Added */
- /*
- for(int i = 0; i < read/2; i = i + 2)
- {
- leftChannelAudioData[i] = data[2*i];
- leftChannelAudioData[i+1] = data[2*i+1];
- rightChannelAudioData[i] = data[2*i+2];
- rightChannelAudioData[i+1] = data[2*i+3];
- }
- */
- /*
- File rawLeftChannelDataFile = new File("leftChannel.txt");
- File rawRightChannelDataFile = new File("rightChannel.txt");
- FileOutputStream leftChannelFos = new FileOutputStream(rawLeftChannelDataFile);
- FileOutputStream rightChannelFos = new FileOutputStream(rawRightChannelDataFile);
- BufferedOutputStream leftChannelBos = new BufferedOutputStream(leftChannelFos);
- BufferedOutputStream rightChannelBos = new BufferedOutputStream(rightChannelFos);
- DataOutputStream leftChannelDos = new DataOutputStream(leftChannelBos);
- DataOutputStream rightChannelDos = new DataOutputStream(rightChannelBos);
- leftChannelDos.write(leftChannelAudioData);
- rightChannelDos.write(rightChannelAudioData);
- */
- /* End of self-added */
- if(AudioRecord.ERROR_INVALID_OPERATION != read){
- try {
- os.write(data);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- try {
- os.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- private void stopRecording(){
- if(null != recorder){
- isRecording = false;
- recorder.stop();
- recorder.release();
- recorder = null;
- recordingThread = null;
- }
- copyWaveFile(getTempFilename(),getFilename());
- deleteTempFile();
- }
- private void deleteTempFile() {
- File file = new File(getTempFilename());
- file.delete();
- }
- private void copyWaveFile(String inFilename,String outFilename){
- FileInputStream in = null;
- FileOutputStream out = null;
- long totalAudioLen = 0;
- long totalDataLen = totalAudioLen + 36;
- long longSampleRate = RECORDER_SAMPLERATE;
- int channels = 2;
- long byteRate = RECORDER_BPP * RECORDER_SAMPLERATE * channels/8;
- Log.d("LOOK HERE", "Byte Rate is " + byteRate);
- byte[] data = new byte[bufferSize];
- try {
- in = new FileInputStream(inFilename);
- out = new FileOutputStream(outFilename);
- totalAudioLen = in.getChannel().size();
- totalDataLen = totalAudioLen + 36;
- AppLog.logString("File size: " + totalDataLen);
- WriteWaveFileHeader(out, totalAudioLen, totalDataLen,
- longSampleRate, channels, byteRate);
- while(in.read(data) != -1){
- out.write(data);
- }
- in.close();
- out.close();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- void stop()
- {
- Log.d("TEST", "THIS IS INSIDE STOP FUNCTION");
- isRecording = true;
- audioTrack.flush();
- audioTrack.stop();
- audioTrack.release();
- }
- void testPlay()
- {
- Log.d("TEST", "THIS IS INSIDE TESTPLAY FUNCTION");
- audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
- (int) sampleRate,AudioFormat.CHANNEL_OUT_STEREO,
- AudioFormat.ENCODING_PCM_16BIT,byteBufferFinal.length,
- AudioTrack.MODE_STATIC);
- audioTrack.write(byteBufferFinal, 0, byteBufferFinal.length);
- audioTrack.play();
- }
- private void playWaveFile(){
- // define the buffer size for audio track
- int minBufferSize = AudioTrack.getMinBufferSize(8000, AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT);
- int bufferSize = 512;
- //audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 8000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, minBufferSize, AudioTrack.MODE_STREAM);
- audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
- (int) RECORDER_SAMPLERATE,AudioFormat.CHANNEL_OUT_STEREO,
- AudioFormat.ENCODING_PCM_16BIT, bufferSize,
- AudioTrack.MODE_STREAM);
- //String filepath = "File Path";
- String filepath = store;
- int count = 0;
- byte[] data = new byte[bufferSize];
- try {
- FileInputStream fileInputStream = new FileInputStream(filepath);
- DataInputStream dataInputStream = new DataInputStream(fileInputStream);
- audioTrack.play();
- while((count = dataInputStream.read(data, 0, bufferSize)) > -1){
- audioTrack.write(data, 0, count);
- }
- audioTrack.stop();
- audioTrack.release();
- dataInputStream.close();
- fileInputStream.close();
- } catch (FileNotFoundException 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 {
- 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) (2 * 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);
- }
- private View.OnClickListener btnClick = new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- switch(v.getId()){
- case R.id.btnStart:{
- AppLog.logString("Start Recording");
- Log.d("LOOK HERE", "IN PLAY BTN START");
- enableButtons(true);
- btnPlay.setEnabled(false);
- startRecording();
- break;
- }
- case R.id.btnStop:{
- AppLog.logString("Stop Recording");
- enableButtons(false);
- btnPlay.setEnabled(true);
- stopRecording();
- stop();
- break;
- }
- case R.id.btnPlay:{
- Log.d("LOOK HERE", "IN PLAY ONCLICKLISTENER");
- //playRecording();
- btnPlay.setEnabled(true);
- playWaveFile();
- //testPlay();
- break;
- }
- }
- }
- };
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement