tuttelikz

SnoringRecordFragment [Old Branch]

Dec 17th, 2017
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 13.97 KB | None | 0 0
  1. package com.example.iptea.hearingclub.fragments;
  2.  
  3.  
  4. import android.Manifest;
  5. import android.content.Context;
  6. import android.media.MediaPlayer;
  7. import android.media.MediaRecorder;
  8. import android.os.Bundle;
  9. import android.support.v4.app.ActivityCompat;
  10. import android.support.v4.app.Fragment;
  11. import android.util.Log;
  12. import android.view.LayoutInflater;
  13. import android.view.View;
  14. import android.view.ViewGroup;
  15. import android.widget.Button;
  16. import android.widget.LinearLayout;
  17.  
  18. import com.cleveroad.audiovisualization.AudioVisualization;
  19. import com.cleveroad.audiovisualization.DbmHandler;
  20. import com.example.iptea.hearingclub.Audiorecorder;
  21. import com.example.iptea.hearingclub.Complex;
  22. import com.example.iptea.hearingclub.FFT;
  23. import com.example.iptea.hearingclub.R;
  24. import com.example.iptea.hearingclub.SnoringFrequencies;
  25.  
  26. import java.io.IOException;
  27. import java.util.Arrays;
  28. import java.util.Date;
  29.  
  30. import io.realm.Realm;
  31.  
  32. /**
  33.  * A simple {@link Fragment} subclass.
  34.  */
  35. public class SnoringRecordFragment extends Fragment {
  36.  
  37.     private static final String LOG_TAG = "AudioRecordTest";
  38.     private static String mFileName = null;
  39.     private String [] permissions = {Manifest.permission.RECORD_AUDIO};
  40.     private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
  41.     //private RecordButton mRecordButton = null;
  42.     private MediaRecorder mRecorder = null;
  43.     //private PlayButton mPlayButton = null;
  44.     private MediaPlayer mPlayer = null;
  45.     int[] range = new int[4];
  46.     private AudioRecordingDbmHandler handler;
  47.     private Audiorecorder audioRecorder;
  48.     Button startRecBtn, stopRecBtn, playRecBtn, stopPlay, saveRec;
  49.     private boolean mStartRecording;
  50.     private boolean mStartPlaying;
  51.  
  52.     public SnoringRecordFragment() {
  53.         // Required empty public constructor
  54.     }
  55.  
  56.     private void onRecord(boolean start) {
  57.         if (start) {
  58.             startRecording();
  59.         } else {
  60.             stopRecording();
  61.         }
  62.     }
  63.  
  64.     private void stopRecording() {
  65.         mRecorder.stop();
  66.         mRecorder.release();
  67.         mRecorder = null;
  68.     }
  69.  
  70.     private void startRecording() {
  71.         mRecorder = new MediaRecorder();
  72.         mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
  73.         mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
  74.         mRecorder.setOutputFile(mFileName);
  75.         mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
  76.  
  77.         try {
  78.             mRecorder.prepare();
  79.         } catch (IOException e) {
  80.             Log.e(LOG_TAG, "prepare() failed");
  81.         }
  82.  
  83.         mRecorder.start();
  84.     }
  85.  
  86.     private void onPlay(boolean start) {
  87.         if (start) {
  88.             startPlaying();
  89.         } else {
  90.             stopPlaying();
  91.         }
  92.     }
  93.  
  94.     private void startPlaying() {
  95.         mPlayer = new MediaPlayer();
  96.         try {
  97.             mPlayer.setDataSource(mFileName);
  98.             mPlayer.prepare();
  99.             mPlayer.start();
  100.         } catch (IOException e) {
  101.             Log.e(LOG_TAG, "prepare() failed");
  102.         }
  103.     }
  104.  
  105.     private void stopPlaying() {
  106.         mPlayer.release();
  107.         mPlayer = null;
  108.     }
  109.  
  110.     /*class PlayButton extends android.support.v7.widget.AppCompatButton {
  111.         boolean mStartPlaying = true;
  112.  
  113.         OnClickListener clicker = new OnClickListener() {
  114.             public void onClick(View v) {
  115.                 onPlay(mStartPlaying);
  116.                 if (mStartPlaying) {
  117.                     setText("Stop playing");
  118.                 } else {
  119.                     setText("Start playing");
  120.                 }
  121.                 mStartPlaying = !mStartPlaying;
  122.             }
  123.         };
  124.  
  125.         public PlayButton(Context ctx) {
  126.             super(ctx);
  127.             setText("Start playing");
  128.             setOnClickListener(clicker);
  129.         }
  130.     }
  131.  
  132.     class RecordButton extends android.support.v7.widget.AppCompatButton {
  133.         boolean mStartRecording = true;
  134.  
  135.         OnClickListener clicker = new OnClickListener() {
  136.             public void onClick(View v) {
  137.                 onRecord(mStartRecording);
  138.                 if (mStartRecording) {
  139.                     setText("Stop recording");
  140.                 } else {
  141.                     setText("Start recording");
  142.                 }
  143.                 mStartRecording = !mStartRecording;
  144.             }
  145.         };
  146.  
  147.         public RecordButton(Context ctx) {
  148.             super(ctx);
  149.             setText("Start recording");
  150.             setOnClickListener(clicker);
  151.         }
  152.     }*/
  153.  
  154.     @Override
  155.     public View onCreateView(LayoutInflater inflater, ViewGroup container,
  156.                              Bundle savedInstanceState) {
  157.         // Inflate the layout for this fragment
  158.  
  159.         final View root = inflater.inflate(R.layout.fragment_snoring_record,container,false);
  160.         //audioVisualization = (AudioVisualization) view.findViewById(R.id.visualizer_view);
  161.  
  162.         mFileName = getActivity().getExternalCacheDir().getAbsolutePath();
  163.         mFileName += "/audiorecordtest.3gp";
  164.  
  165.         ActivityCompat.requestPermissions(getActivity(), permissions, REQUEST_RECORD_AUDIO_PERMISSION);
  166.  
  167.  
  168.  
  169. /*        LinearLayout ll = new LinearLayout(getActivity());
  170.         mRecordButton = new RecordButton(getActivity());
  171.  
  172.         ll.addView(mRecordButton,
  173.                 new LinearLayout.LayoutParams(
  174.                         ViewGroup.LayoutParams.WRAP_CONTENT,
  175.                         ViewGroup.LayoutParams.WRAP_CONTENT,
  176.                         0));
  177.         mPlayButton = new PlayButton(getActivity());
  178.         ll.addView(mPlayButton,
  179.                 new LinearLayout.LayoutParams(
  180.                         ViewGroup.LayoutParams.WRAP_CONTENT,
  181.                         ViewGroup.LayoutParams.WRAP_CONTENT,
  182.                         0));
  183.         getActivity().setContentView(ll);*/
  184.  
  185.  
  186.         ///////////////////////////////////////////////////////
  187.         audioRecorder = new Audiorecorder();
  188.         handler = new AudioRecordingDbmHandler();
  189.         audioRecorder.recordingCallback(handler);
  190.         //audioVisualization.linkTo(handler);
  191.  
  192.         //////////////////////////////////////////////////////
  193.  
  194.         startRecBtn = root.findViewById(R.id.startRecBtn);
  195.         stopRecBtn = root.findViewById(R.id.stopRecBtn);
  196.         playRecBtn = root.findViewById(R.id.playRecBtn);
  197.         stopPlay = root.findViewById(R.id.stopPlay);
  198.         saveRec = root.findViewById(R.id.saveRec);
  199.  
  200.  
  201.  
  202.  
  203.  
  204.         startRecBtn.setOnClickListener(new View.OnClickListener() {
  205.  
  206.             @Override
  207.             public void onClick(View view) {
  208.                 mStartRecording = true;
  209.                 onRecord(mStartRecording);
  210.                 //audioRecorder.startRecord(); //////////
  211.             }
  212.         });
  213.  
  214.         stopRecBtn.setOnClickListener(new View.OnClickListener() {
  215.             @Override
  216.             public void onClick(View view) {
  217.                 mStartRecording = false;
  218.                 onRecord(mStartRecording);
  219.                 //audioRecorder.finishRecord(); ///////
  220.                 //handler.stop(); //////////
  221.             }
  222.         });
  223.  
  224.         playRecBtn.setOnClickListener(new View.OnClickListener() {
  225.             @Override
  226.             public void onClick(View view) {
  227.                 mStartPlaying = true;
  228.                 onPlay(mStartPlaying);
  229.             }
  230.         });
  231.  
  232.  
  233.         stopPlay.setOnClickListener(new View.OnClickListener() {
  234.             @Override
  235.             public void onClick(View view) {
  236.                 mStartPlaying = false;
  237.                 onPlay(mStartPlaying);
  238.             }
  239.         });
  240.  
  241.  
  242.  
  243.         return root;
  244.     }
  245.  
  246.  
  247.  
  248.  
  249.  
  250.  
  251.     @Override
  252.     public void onStop() {
  253.         super.onStop();
  254.         if (mRecorder != null) {
  255.             mRecorder.release();
  256.             mRecorder = null;
  257.         }
  258.  
  259.         if (mPlayer != null) {
  260.             mPlayer.release();
  261.             mPlayer = null;
  262.         }
  263.     }
  264.  
  265.  
  266.  
  267.  
  268.  
  269.  
  270.  
  271.  
  272.     private class AudioRecordingDbmHandler extends DbmHandler<byte[]> implements Audiorecorder.RecordingCallback{
  273.  
  274.         private static final float MAX_DB_VALUE = 170;
  275.  
  276.         private float[] dbs;
  277.         private float[] allAmps;
  278.  
  279.         float dBmArrayFirst = 0;
  280.         float dBmArraySecond = 0;
  281.         float dBmArrayThird = 0;
  282.         float dBmArrayFourth = 0;
  283.  
  284.         int fcnCallCounter = 0;
  285.  
  286.  
  287.         @Override
  288.         protected void onDataReceivedImpl(byte[] bytes, int layersCount, float[] dBmArray, float[] ampsArray) {
  289.             layersCount = 4;
  290.             fcnCallCounter++;
  291.             final int bytesPerSample = 2; // As it is 16bit PCM
  292.             final double amplification = 100.0; // choose a number as you like
  293.             Complex[] fft = new Complex[bytes.length / bytesPerSample];
  294.             for (int index = 0, floatIndex = 0; index < bytes.length - bytesPerSample + 1; index += bytesPerSample, floatIndex++) {
  295.                 double sample = 0;
  296.                 for (int b = 0; b < bytesPerSample; b++) {
  297.                     int v = bytes[index + b];
  298.                     if (b < bytesPerSample - 1) {
  299.                         v &= 0xFF;
  300.                     }
  301.                     sample += v << (b * 8);
  302.                 }
  303.                 double sample32 = amplification * (sample / 32768.0);
  304.                 fft[floatIndex] = new Complex(sample32, 0);
  305.             }
  306.             fft = FFT.fft(fft);
  307.  
  308.             int dataSize = fft.length / 2 - 1;
  309.  
  310.             Log.d("ADebugTag", "bytesPerSample: " + bytesPerSample); //2
  311.             Log.d("ADebugTag", "bytes.length: " + bytes.length); //2048
  312.             Log.d("ADebugTag", "dataSize: " + dataSize);        //511
  313.             Log.d("ADebugTag", "fft.length: " + fft.length);     //1024
  314.  
  315.             if (dbs == null || dbs.length != dataSize) {
  316.                 dbs = new float[dataSize];
  317.             }
  318.  
  319.             if (allAmps == null || allAmps.length != dataSize) {
  320.                 allAmps = new float[dataSize];
  321.             }
  322.  
  323.             for (int i = 0; i < dataSize; i++) { //511
  324.                 dbs[i] = (float) fft[i].abs();  //1
  325.                 float k = 1;
  326.                 if (i == 0 || i == dataSize - 1) {
  327.                     k = 2;
  328.                 }
  329.                 float re = (float) fft[2 * i].re();
  330.                 float im = (float) fft[2 * i + 1].im();
  331.                 float sqMag = re * re + im * im;
  332.                 allAmps[i] = (float) (k * Math.sqrt(sqMag) / dataSize);
  333.             }
  334.  
  335.             int size = dbs.length / layersCount;  //128
  336.             for (int i = 0; i < layersCount; i++) { //4
  337.                 int index = (int) ((i + 0.5f) * size);  //1*128 256  378  4*128
  338.                 float db = dbs[index]; //128  256  378  512
  339.                 float amp = allAmps[index];  //128 //
  340.                 dBmArray[i] = db > MAX_DB_VALUE ? 1 : db / MAX_DB_VALUE;
  341.                 ampsArray[i] = amp;
  342.                 Log.d("ADebugTag", "index: " + index);     //1024
  343.                 range[i] = index;
  344.             }
  345.  
  346.             Log.d("ADebugTag", "dBmArray: " + Arrays.toString(dBmArray));
  347.  
  348.             dBmArrayFirst = dBmArrayFirst + dBmArray[0];
  349.             dBmArraySecond = dBmArraySecond + dBmArray[1];
  350.             dBmArrayThird = dBmArrayThird + dBmArray[2];
  351.             dBmArrayFourth = dBmArrayFourth + dBmArray[3];
  352.         }
  353.  
  354.         public void stop() {
  355.             float avgArrayFirst;
  356.             float avgArraySecond;
  357.             float avgArrayThird;
  358.             float avgArrayFourth;
  359.             int indexOfLargest;
  360.             int indexOfSmallest;
  361.             float hearingRange;
  362.  
  363.             ///////////Realm.init(getActivity());//////////////////////////////////
  364.             ///////////realm = Realm.getDefaultInstance();
  365.  
  366.             //////////////////////////////////////////////////calmDownAndStopRendering();
  367.             avgArrayFirst = dBmArrayFirst / fcnCallCounter;
  368.             avgArraySecond = dBmArraySecond / fcnCallCounter;
  369.             avgArrayThird = dBmArrayThird / fcnCallCounter;
  370.             avgArrayFourth = dBmArrayFourth / fcnCallCounter;
  371.  
  372. /*            avgArrayValues[0] = avgArrayFirst;
  373.             avgArrayValues[1] = avgArraySecond;
  374.             avgArrayValues[2] = avgArrayThird;
  375.             avgArrayValues[3] = avgArrayFourth;*/
  376.  
  377. /*            indexOfLargest = getIndexOfLargest(avgArrayValues);
  378.             indexOfSmallest = getIndexOfSmallest(avgArrayValues);*/
  379.  
  380. /*            hearingRange = Math.abs((indexOfLargest - indexOfSmallest) * 128);*/
  381.  
  382. /*            Log.d("ADebugTag", "Index with max average amplitude: " + indexOfLargest);     //1024
  383.             Log.d("ADebugTag", "Index with min average amplitude: " + indexOfSmallest);
  384.             Log.d("ADebugTag", "Hearing Ranges: " + hearingRange);
  385.  
  386.             realm.beginTransaction();
  387.  
  388.             SnoringFrequencies obj = realm.createObject(SnoringFrequencies.class);
  389.  
  390.             obj.setId(new Date().toString());
  391.             obj.setFreq1(Float.toString(avgArrayFirst));
  392.             obj.setFreq2(Float.toString(avgArraySecond));
  393.             obj.setFreq3(Float.toString(avgArrayThird));
  394.             obj.setFreq4(Float.toString(avgArrayFourth));
  395.  
  396.             realm.commitTransaction();*/
  397.         }
  398.  
  399.         @Override
  400.         public void onDataReady(byte[] data) {
  401.             onDataReceived(data);
  402.         }
  403.     }
  404.  
  405.     public int getIndexOfLargest( float[] array )
  406.     {
  407.         if ( array == null || array.length == 0 ) return -1; // null or empty
  408.  
  409.         int largest = 0;
  410.         for ( int i = 1; i < array.length; i++ )
  411.         {
  412.             if ( array[i] > array[largest] ) largest = i;
  413.         }
  414.         return largest; // position of the first largest found
  415.     }
  416.  
  417.     public int getIndexOfSmallest( float[] array )
  418.     {
  419.         if ( array == null || array.length == 0 ) return -1; // null or empty
  420.  
  421.         int smallest = 0;
  422.         for ( int i = 1; i < array.length; i++ )
  423.         {
  424.             if ( array[i] < array[smallest] ) smallest = i;
  425.         }
  426.         return smallest; // position of the first largest found
  427.     }
  428.  
  429.  
  430.  
  431. }
Advertisement
Add Comment
Please, Sign In to add comment