Advertisement
Guest User

Untitled

a guest
Sep 22nd, 2015
660
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.82 KB | None | 0 0
  1. package com.varma.samples.audiorecorder;
  2.  
  3. import java.io.BufferedInputStream;
  4. import java.io.BufferedOutputStream;
  5. import java.io.DataInputStream;
  6. import java.io.DataOutputStream;
  7. import java.io.File;
  8. import java.io.FileInputStream;
  9. import java.io.FileNotFoundException;
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.io.InputStream;
  13.  
  14. import android.app.Activity;
  15. import android.media.AudioFormat;
  16. import android.media.AudioManager;
  17. import android.media.AudioRecord;
  18. import android.media.AudioTrack;
  19. import android.media.MediaRecorder;
  20. import android.os.Bundle;
  21. import android.os.Environment;
  22. import android.util.Log;
  23. import android.view.View;
  24. import android.widget.Button;
  25. import android.widget.TextView;
  26. import android.widget.Toast;
  27.  
  28. public class RecorderActivity extends Activity {
  29.  
  30. private static final int RECORDER_BPP = 16;
  31. private static final String AUDIO_RECORDER_FILE_EXT_WAV = ".wav";
  32. private static final String AUDIO_RECORDER_FOLDER = "AudioRecorder";
  33. private static final String AUDIO_RECORDER_TEMP_FILE = "record_temp.raw";
  34. private static final int RECORDER_SAMPLERATE = 44100;//44100; //18000
  35. private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_STEREO;
  36. private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
  37.  
  38. String store;
  39. private AudioRecord recorder = null;
  40. private int bufferSize = 0;
  41. private Thread recordingThread = null;
  42. private boolean isRecording = false;
  43.  
  44. int sample;
  45. double sampleRate;
  46. double duration;
  47. //double duration2;
  48. double time;
  49. double f1;
  50. double f2;
  51. double amplitude1;
  52. double amplitude2;
  53. double sineWave1;
  54. double sineWave2;
  55. float[] buffer1;
  56. float[] buffer2;
  57. byte[] byteBuffer1;
  58. byte[] byteBuffer2;
  59. byte[] byteBufferFinal;
  60. int bufferIndex;
  61. short x;
  62. short y;
  63. AudioTrack audioTrack;
  64.  
  65. byte[] leftChannelAudioData;
  66. byte [] rightChannelAudioData;
  67.  
  68. Button btnPlay;
  69.  
  70. private static final String TAG = RecorderActivity.class.getSimpleName();
  71.  
  72. @Override
  73. public void onCreate(Bundle savedInstanceState) {
  74. super.onCreate(savedInstanceState);
  75. setContentView(R.layout.main);
  76. // Log.d(TAG, "Hello");
  77. //Toast.makeText(getApplicationContext(), "TEST", Toast.LENGTH_LONG).show();
  78. setButtonHandlers();
  79. enableButtons(false);
  80.  
  81. btnPlay = (Button)findViewById(R.id.btnPlay);
  82.  
  83. bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,RECORDER_CHANNELS,RECORDER_AUDIO_ENCODING);
  84.  
  85. sampleRate = 44100.0;
  86. duration = 13.0;
  87. f1 = 1400.0; //100.0;
  88. //f1 = 18000.0;
  89. amplitude1= 1;
  90. f2 = 500.0;
  91. //f2 = 0;//19000.0;
  92. amplitude2 = 1;
  93.  
  94. /* Original */
  95. buffer1 = new float[(int)(duration*sampleRate)];
  96. buffer2 = new float[(int)(duration*sampleRate)];
  97.  
  98. //buffer1 = new float[(int)(sampleRate)];
  99. //buffer2 = new float[(int)(sampleRate)];
  100.  
  101. for(sample = 0; sample < buffer1.length; sample ++){
  102. time = sample / sampleRate;
  103. buffer1[sample] = (float)(amplitude1*Math.sin(2*Math.PI*f1*time));
  104. buffer2[sample] = (float)(amplitude2*Math.sin(2*Math.PI*f2*time));
  105. //Toast.makeText(getApplicationContext(), "IN", Toast.LENGTH_LONG).show();
  106. }
  107.  
  108. byteBuffer1 = new byte[buffer1.length*2]; //two bytes per audio frame, 16 bits
  109.  
  110. for(int i = 0, bufferIndex=0; i < byteBuffer1.length; i++){
  111. x = (short) (buffer1[bufferIndex++]*32767.0); // [2^16 - 1]/2 = 32767.0
  112. byteBuffer1[i] = (byte) x; // low byte
  113. byteBuffer1[++i] = (byte) (x >>> 8); // high byte
  114. }
  115.  
  116.  
  117. byteBuffer2 = new byte[buffer2.length*2];
  118.  
  119. for(int j = 0, bufferIndex=0; j < byteBuffer2.length; j++){
  120. y = (short) (buffer2[bufferIndex++]*32767.0);
  121. byteBuffer2[j] = (byte) y; // low byte
  122. byteBuffer2[++j] = (byte) (y >>> 8); // high byte
  123.  
  124. }
  125.  
  126. byteBufferFinal = new byte[byteBuffer1.length*2];
  127. //LL RR LL RR LL RR
  128. for(int k = 0, index = 0; index < byteBufferFinal.length - 4; k=k+2){
  129. byteBufferFinal[index] = byteBuffer1[k]; // LEFT {0,1/4,5/8,9/12,13;...}
  130. byteBufferFinal[index+1] = byteBuffer1[k+1];
  131. index = index + 2;
  132. byteBufferFinal[index] = byteBuffer2[k]; // RIGHT {2,3/6,7/10,11;...}
  133. byteBufferFinal[index+1] = byteBuffer2[k+1];
  134. index = index + 2;
  135. }
  136.  
  137.  
  138. /* int stereo=audioTrack.setStereoVolume(0.0f, 0.1f);
  139. Log.d("GREC", "Stereo vol: "+stereo);
  140. System.out.println("LOOK HERE " +stereo);
  141. final String promptStartRecord =
  142. "startRecord123()\n";
  143. Toast.makeText(RecorderActivity.this,
  144. promptStartRecord,
  145. Toast.LENGTH_LONG).show();
  146. */
  147. //recorder = new AudioRecord(MediaRecorder.AudioSource.CAMCORDER,
  148. // RECORDER_SAMPLERATE, RECORDER_CHANNELS,RECORDER_AUDIO_ENCODING, bufferSize);
  149. }
  150.  
  151.  
  152.  
  153. private void setButtonHandlers() {
  154. ((Button)findViewById(R.id.btnStart)).setOnClickListener(btnClick);
  155. ((Button)findViewById(R.id.btnStop)).setOnClickListener(btnClick);
  156. ((Button)findViewById(R.id.btnPlay)).setOnClickListener(btnClick);
  157. }
  158.  
  159. private void enableButton(int id,boolean isEnable){
  160. ((Button)findViewById(id)).setEnabled(isEnable);
  161. }
  162.  
  163. private void enableButtons(boolean isRecording) {
  164. enableButton(R.id.btnStart,!isRecording);
  165. enableButton(R.id.btnStop,isRecording);
  166. enableButton(R.id.btnPlay, isRecording);
  167. }
  168.  
  169.  
  170.  
  171. private String getFilename(){
  172. String filepath = Environment.getExternalStorageDirectory().getPath();
  173. File file = new File(filepath,AUDIO_RECORDER_FOLDER);
  174.  
  175. if(!file.exists()){
  176. file.mkdirs();
  177. }
  178. store = file.getAbsolutePath() + "/" + System.currentTimeMillis() + AUDIO_RECORDER_FILE_EXT_WAV;
  179. //return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + AUDIO_RECORDER_FILE_EXT_WAV);
  180. return store;
  181. }
  182.  
  183. private String getTempFilename(){
  184. String filepath = Environment.getExternalStorageDirectory().getPath();
  185. File file = new File(filepath,AUDIO_RECORDER_FOLDER);
  186.  
  187. if(!file.exists()){
  188. file.mkdirs();
  189. }
  190.  
  191. File tempFile = new File(filepath,AUDIO_RECORDER_TEMP_FILE);
  192.  
  193. if(tempFile.exists())
  194. tempFile.delete();
  195.  
  196. return (file.getAbsolutePath() + "/" + AUDIO_RECORDER_TEMP_FILE);
  197. }
  198.  
  199.  
  200.  
  201.  
  202. private void startRecording(){
  203.  
  204. recorder = new AudioRecord(MediaRecorder.AudioSource.CAMCORDER,
  205. RECORDER_SAMPLERATE, RECORDER_CHANNELS,RECORDER_AUDIO_ENCODING, bufferSize);
  206.  
  207. /* AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
  208. (int) RECORDER_SAMPLERATE,AudioFormat.CHANNEL_OUT_STEREO,
  209. AudioFormat.ENCODING_PCM_16BIT, bufferSize,
  210. AudioTrack.MODE_STREAM);
  211. */
  212. audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
  213. (int) sampleRate,AudioFormat.CHANNEL_OUT_STEREO,
  214. AudioFormat.ENCODING_PCM_16BIT,byteBufferFinal.length,
  215. AudioTrack.MODE_STATIC);
  216.  
  217. // int stereo=audioTrack.setStereoVolume(0.0f, 1.0f);
  218. //Log.d("SIAN", "STEREO IS " + stereo);
  219. audioTrack.write(byteBufferFinal, 0, byteBufferFinal.length);
  220. audioTrack.play();
  221.  
  222. audioTrack.setPlaybackRate(RECORDER_SAMPLERATE);
  223.  
  224.  
  225. final byte[] buffer = new byte[bufferSize];
  226.  
  227.  
  228.  
  229. recorder.startRecording();
  230. /*byte[] byteBufferFinal = new byte[bufferSize*2];
  231.  
  232. recorder.read(buffer, 0, bufferSize);
  233.  
  234. for(int k = 0, index = 0; index < byteBufferFinal.length - 4; k=k+2){
  235. byteBufferFinal[index] = buffer[k]; // LEFT {0,1/4,5/8,9/12,13;...}
  236. // System.out.println(byteBufferFinal[index]);
  237. byteBufferFinal[index+1] = buffer[k+1];
  238. // System.out.println(byteBufferFinal[index+1]);
  239. index = index + 2;
  240. byteBufferFinal[index] =0; //byteBuffer2[k]; // RIGHT {2,3/6,7/10,11;...}
  241. // System.out.println(byteBufferFinal[index]);
  242. byteBufferFinal[index+1] =0;// byteBuffer2[k+1];
  243. // System.out.println(byteBufferFinal[index+1]);
  244. index = index + 2;
  245. }
  246. */
  247. /*
  248. audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
  249. (int) RECORDER_SAMPLERATE,AudioFormat.CHANNEL_OUT_STEREO,
  250. AudioFormat.ENCODING_PCM_16BIT,byteBufferFinal.length,
  251. AudioTrack.MODE_STATIC);
  252. audioTrack.write( byteBufferFinal, 0, bufferSize*2);
  253. audioTrack.play();
  254. */
  255.  
  256. isRecording = true;
  257.  
  258. recordingThread = new Thread(new Runnable() {
  259.  
  260. @Override
  261. public void run() {
  262. try {
  263. writeAudioDataToFile();
  264. } catch (IOException e) {
  265. // TODO Auto-generated catch block
  266. e.printStackTrace();
  267. }
  268. }
  269. },"AudioRecorder Thread");
  270.  
  271. recordingThread.start();
  272.  
  273. }
  274.  
  275.  
  276. @SuppressWarnings("null")
  277. private void writeAudioDataToFile() throws IOException{
  278. int read = 0;
  279. byte data[] = new byte[bufferSize];
  280. //short[] shortData = new short[bufferSize];
  281. String filename = getTempFilename();
  282. FileOutputStream os = null;
  283.  
  284. try {
  285. os = new FileOutputStream(filename);
  286. } catch (FileNotFoundException e) {
  287. // TODO Auto-generated catch block
  288. e.printStackTrace();
  289. }
  290.  
  291.  
  292.  
  293. if(null != os){
  294. while(isRecording){
  295.  
  296. read = recorder.read(data, 0, bufferSize);
  297.  
  298. /* Self Added */
  299. /*
  300. for(int i = 0; i < read/2; i = i + 2)
  301. {
  302. leftChannelAudioData[i] = data[2*i];
  303. leftChannelAudioData[i+1] = data[2*i+1];
  304. rightChannelAudioData[i] = data[2*i+2];
  305. rightChannelAudioData[i+1] = data[2*i+3];
  306. }
  307. */
  308. /*
  309. File rawLeftChannelDataFile = new File("leftChannel.txt");
  310. File rawRightChannelDataFile = new File("rightChannel.txt");
  311. FileOutputStream leftChannelFos = new FileOutputStream(rawLeftChannelDataFile);
  312. FileOutputStream rightChannelFos = new FileOutputStream(rawRightChannelDataFile);
  313. BufferedOutputStream leftChannelBos = new BufferedOutputStream(leftChannelFos);
  314. BufferedOutputStream rightChannelBos = new BufferedOutputStream(rightChannelFos);
  315. DataOutputStream leftChannelDos = new DataOutputStream(leftChannelBos);
  316. DataOutputStream rightChannelDos = new DataOutputStream(rightChannelBos);
  317. leftChannelDos.write(leftChannelAudioData);
  318. rightChannelDos.write(rightChannelAudioData);
  319.  
  320.  
  321. */
  322. /* End of self-added */
  323.  
  324. if(AudioRecord.ERROR_INVALID_OPERATION != read){
  325. try {
  326. os.write(data);
  327. } catch (IOException e) {
  328. e.printStackTrace();
  329. }
  330. }
  331. }
  332.  
  333. try {
  334. os.close();
  335. } catch (IOException e) {
  336. e.printStackTrace();
  337. }
  338. }
  339. }
  340.  
  341. private void stopRecording(){
  342. if(null != recorder){
  343. isRecording = false;
  344.  
  345. recorder.stop();
  346. recorder.release();
  347.  
  348. recorder = null;
  349. recordingThread = null;
  350. }
  351.  
  352.  
  353. copyWaveFile(getTempFilename(),getFilename());
  354. deleteTempFile();
  355. }
  356.  
  357.  
  358.  
  359. private void deleteTempFile() {
  360. File file = new File(getTempFilename());
  361. file.delete();
  362. }
  363.  
  364.  
  365. private void copyWaveFile(String inFilename,String outFilename){
  366. FileInputStream in = null;
  367. FileOutputStream out = null;
  368. long totalAudioLen = 0;
  369. long totalDataLen = totalAudioLen + 36;
  370. long longSampleRate = RECORDER_SAMPLERATE;
  371. int channels = 2;
  372. long byteRate = RECORDER_BPP * RECORDER_SAMPLERATE * channels/8;
  373. Log.d("LOOK HERE", "Byte Rate is " + byteRate);
  374. byte[] data = new byte[bufferSize];
  375.  
  376.  
  377. try {
  378. in = new FileInputStream(inFilename);
  379. out = new FileOutputStream(outFilename);
  380. totalAudioLen = in.getChannel().size();
  381. totalDataLen = totalAudioLen + 36;
  382.  
  383. AppLog.logString("File size: " + totalDataLen);
  384.  
  385. WriteWaveFileHeader(out, totalAudioLen, totalDataLen,
  386. longSampleRate, channels, byteRate);
  387.  
  388. while(in.read(data) != -1){
  389. out.write(data);
  390. }
  391.  
  392. in.close();
  393. out.close();
  394. } catch (FileNotFoundException e) {
  395. e.printStackTrace();
  396. } catch (IOException e) {
  397. e.printStackTrace();
  398. }
  399. }
  400.  
  401.  
  402. void stop()
  403. {
  404. Log.d("TEST", "THIS IS INSIDE STOP FUNCTION");
  405. isRecording = true;
  406. audioTrack.flush();
  407. audioTrack.stop();
  408. audioTrack.release();
  409. }
  410.  
  411. void testPlay()
  412. {
  413. Log.d("TEST", "THIS IS INSIDE TESTPLAY FUNCTION");
  414. audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
  415. (int) sampleRate,AudioFormat.CHANNEL_OUT_STEREO,
  416. AudioFormat.ENCODING_PCM_16BIT,byteBufferFinal.length,
  417. AudioTrack.MODE_STATIC);
  418.  
  419. audioTrack.write(byteBufferFinal, 0, byteBufferFinal.length);
  420. audioTrack.play();
  421. }
  422.  
  423. private void playWaveFile(){
  424.  
  425. // define the buffer size for audio track
  426. int minBufferSize = AudioTrack.getMinBufferSize(8000, AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT);
  427. int bufferSize = 512;
  428. //audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 8000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, minBufferSize, AudioTrack.MODE_STREAM);
  429. audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
  430. (int) RECORDER_SAMPLERATE,AudioFormat.CHANNEL_OUT_STEREO,
  431. AudioFormat.ENCODING_PCM_16BIT, bufferSize,
  432. AudioTrack.MODE_STREAM);
  433.  
  434. //String filepath = "File Path";
  435. String filepath = store;
  436.  
  437. int count = 0;
  438. byte[] data = new byte[bufferSize];
  439. try {
  440. FileInputStream fileInputStream = new FileInputStream(filepath);
  441. DataInputStream dataInputStream = new DataInputStream(fileInputStream);
  442. audioTrack.play();
  443.  
  444. while((count = dataInputStream.read(data, 0, bufferSize)) > -1){
  445. audioTrack.write(data, 0, count);
  446. }
  447. audioTrack.stop();
  448. audioTrack.release();
  449. dataInputStream.close();
  450. fileInputStream.close();
  451.  
  452. } catch (FileNotFoundException e) {
  453. e.printStackTrace();
  454. } catch (IOException e) {
  455. e.printStackTrace();
  456. }
  457. }
  458.  
  459. private void WriteWaveFileHeader(
  460. FileOutputStream out, long totalAudioLen,
  461. long totalDataLen, long longSampleRate, int channels,
  462. long byteRate) throws IOException {
  463.  
  464. byte[] header = new byte[44];
  465.  
  466. header[0] = 'R'; // RIFF/WAVE header
  467. header[1] = 'I';
  468. header[2] = 'F';
  469. header[3] = 'F';
  470. header[4] = (byte) (totalDataLen & 0xff);
  471. header[5] = (byte) ((totalDataLen >> 8) & 0xff);
  472. header[6] = (byte) ((totalDataLen >> 16) & 0xff);
  473. header[7] = (byte) ((totalDataLen >> 24) & 0xff);
  474. header[8] = 'W';
  475. header[9] = 'A';
  476. header[10] = 'V';
  477. header[11] = 'E';
  478. header[12] = 'f'; // 'fmt ' chunk
  479. header[13] = 'm';
  480. header[14] = 't';
  481. header[15] = ' ';
  482. header[16] = 16; // 4 bytes: size of 'fmt ' chunk
  483. header[17] = 0;
  484. header[18] = 0;
  485. header[19] = 0;
  486. header[20] = 1; // format = 1
  487. header[21] = 0;
  488. header[22] = (byte) channels;
  489. header[23] = 0;
  490. header[24] = (byte) (longSampleRate & 0xff);
  491. header[25] = (byte) ((longSampleRate >> 8) & 0xff);
  492. header[26] = (byte) ((longSampleRate >> 16) & 0xff);
  493. header[27] = (byte) ((longSampleRate >> 24) & 0xff);
  494. header[28] = (byte) (byteRate & 0xff);
  495. header[29] = (byte) ((byteRate >> 8) & 0xff);
  496. header[30] = (byte) ((byteRate >> 16) & 0xff);
  497. header[31] = (byte) ((byteRate >> 24) & 0xff);
  498. header[32] = (byte) (2 * 16 / 8); // block align
  499. header[33] = 0;
  500. header[34] = RECORDER_BPP; // bits per sample
  501. header[35] = 0;
  502. header[36] = 'd';
  503. header[37] = 'a';
  504. header[38] = 't';
  505. header[39] = 'a';
  506. header[40] = (byte) (totalAudioLen & 0xff);
  507. header[41] = (byte) ((totalAudioLen >> 8) & 0xff);
  508. header[42] = (byte) ((totalAudioLen >> 16) & 0xff);
  509. header[43] = (byte) ((totalAudioLen >> 24) & 0xff);
  510.  
  511. out.write(header, 0, 44);
  512. }
  513.  
  514.  
  515. private View.OnClickListener btnClick = new View.OnClickListener() {
  516. @Override
  517. public void onClick(View v) {
  518. switch(v.getId()){
  519. case R.id.btnStart:{
  520. AppLog.logString("Start Recording");
  521. Log.d("LOOK HERE", "IN PLAY BTN START");
  522. enableButtons(true);
  523. btnPlay.setEnabled(false);
  524. startRecording();
  525.  
  526. break;
  527. }
  528. case R.id.btnStop:{
  529. AppLog.logString("Stop Recording");
  530. enableButtons(false);
  531. btnPlay.setEnabled(true);
  532. stopRecording();
  533. stop();
  534. break;
  535. }
  536. case R.id.btnPlay:{
  537. Log.d("LOOK HERE", "IN PLAY ONCLICKLISTENER");
  538. //playRecording();
  539. btnPlay.setEnabled(true);
  540. playWaveFile();
  541. //testPlay();
  542. break;
  543. }
  544.  
  545. }
  546. }
  547. };
  548. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement