Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.iptea.hearingclub.fragments;
- import android.Manifest;
- import android.content.Context;
- import android.media.MediaPlayer;
- import android.media.MediaRecorder;
- import android.os.Bundle;
- import android.support.v4.app.ActivityCompat;
- import android.support.v4.app.Fragment;
- import android.util.Log;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.view.ViewGroup;
- import android.widget.Button;
- import android.widget.LinearLayout;
- import com.cleveroad.audiovisualization.AudioVisualization;
- import com.cleveroad.audiovisualization.DbmHandler;
- import com.example.iptea.hearingclub.Audiorecorder;
- import com.example.iptea.hearingclub.Complex;
- import com.example.iptea.hearingclub.FFT;
- import com.example.iptea.hearingclub.R;
- import com.example.iptea.hearingclub.SnoringFrequencies;
- import java.io.IOException;
- import java.util.Arrays;
- import java.util.Date;
- import io.realm.Realm;
- /**
- * A simple {@link Fragment} subclass.
- */
- public class SnoringRecordFragment extends Fragment {
- private static final String LOG_TAG = "AudioRecordTest";
- private static String mFileName = null;
- private String [] permissions = {Manifest.permission.RECORD_AUDIO};
- private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
- //private RecordButton mRecordButton = null;
- private MediaRecorder mRecorder = null;
- //private PlayButton mPlayButton = null;
- private MediaPlayer mPlayer = null;
- int[] range = new int[4];
- private AudioRecordingDbmHandler handler;
- private Audiorecorder audioRecorder;
- Button startRecBtn, stopRecBtn, playRecBtn, stopPlay, saveRec;
- private boolean mStartRecording;
- private boolean mStartPlaying;
- public SnoringRecordFragment() {
- // Required empty public constructor
- }
- private void onRecord(boolean start) {
- if (start) {
- startRecording();
- } else {
- stopRecording();
- }
- }
- private void stopRecording() {
- mRecorder.stop();
- mRecorder.release();
- mRecorder = null;
- }
- private void startRecording() {
- mRecorder = new MediaRecorder();
- mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
- mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
- mRecorder.setOutputFile(mFileName);
- mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
- try {
- mRecorder.prepare();
- } catch (IOException e) {
- Log.e(LOG_TAG, "prepare() failed");
- }
- mRecorder.start();
- }
- private void onPlay(boolean start) {
- if (start) {
- startPlaying();
- } else {
- stopPlaying();
- }
- }
- private void startPlaying() {
- mPlayer = new MediaPlayer();
- try {
- mPlayer.setDataSource(mFileName);
- mPlayer.prepare();
- mPlayer.start();
- } catch (IOException e) {
- Log.e(LOG_TAG, "prepare() failed");
- }
- }
- private void stopPlaying() {
- mPlayer.release();
- mPlayer = null;
- }
- /*class PlayButton extends android.support.v7.widget.AppCompatButton {
- boolean mStartPlaying = true;
- OnClickListener clicker = new OnClickListener() {
- public void onClick(View v) {
- onPlay(mStartPlaying);
- if (mStartPlaying) {
- setText("Stop playing");
- } else {
- setText("Start playing");
- }
- mStartPlaying = !mStartPlaying;
- }
- };
- public PlayButton(Context ctx) {
- super(ctx);
- setText("Start playing");
- setOnClickListener(clicker);
- }
- }
- class RecordButton extends android.support.v7.widget.AppCompatButton {
- boolean mStartRecording = true;
- OnClickListener clicker = new OnClickListener() {
- public void onClick(View v) {
- onRecord(mStartRecording);
- if (mStartRecording) {
- setText("Stop recording");
- } else {
- setText("Start recording");
- }
- mStartRecording = !mStartRecording;
- }
- };
- public RecordButton(Context ctx) {
- super(ctx);
- setText("Start recording");
- setOnClickListener(clicker);
- }
- }*/
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- // Inflate the layout for this fragment
- final View root = inflater.inflate(R.layout.fragment_snoring_record,container,false);
- //audioVisualization = (AudioVisualization) view.findViewById(R.id.visualizer_view);
- mFileName = getActivity().getExternalCacheDir().getAbsolutePath();
- mFileName += "/audiorecordtest.3gp";
- ActivityCompat.requestPermissions(getActivity(), permissions, REQUEST_RECORD_AUDIO_PERMISSION);
- /* LinearLayout ll = new LinearLayout(getActivity());
- mRecordButton = new RecordButton(getActivity());
- ll.addView(mRecordButton,
- new LinearLayout.LayoutParams(
- ViewGroup.LayoutParams.WRAP_CONTENT,
- ViewGroup.LayoutParams.WRAP_CONTENT,
- 0));
- mPlayButton = new PlayButton(getActivity());
- ll.addView(mPlayButton,
- new LinearLayout.LayoutParams(
- ViewGroup.LayoutParams.WRAP_CONTENT,
- ViewGroup.LayoutParams.WRAP_CONTENT,
- 0));
- getActivity().setContentView(ll);*/
- ///////////////////////////////////////////////////////
- audioRecorder = new Audiorecorder();
- handler = new AudioRecordingDbmHandler();
- audioRecorder.recordingCallback(handler);
- //audioVisualization.linkTo(handler);
- //////////////////////////////////////////////////////
- startRecBtn = root.findViewById(R.id.startRecBtn);
- stopRecBtn = root.findViewById(R.id.stopRecBtn);
- playRecBtn = root.findViewById(R.id.playRecBtn);
- stopPlay = root.findViewById(R.id.stopPlay);
- saveRec = root.findViewById(R.id.saveRec);
- startRecBtn.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- mStartRecording = true;
- onRecord(mStartRecording);
- //audioRecorder.startRecord(); //////////
- }
- });
- stopRecBtn.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- mStartRecording = false;
- onRecord(mStartRecording);
- //audioRecorder.finishRecord(); ///////
- //handler.stop(); //////////
- }
- });
- playRecBtn.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- mStartPlaying = true;
- onPlay(mStartPlaying);
- }
- });
- stopPlay.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- mStartPlaying = false;
- onPlay(mStartPlaying);
- }
- });
- return root;
- }
- @Override
- public void onStop() {
- super.onStop();
- if (mRecorder != null) {
- mRecorder.release();
- mRecorder = null;
- }
- if (mPlayer != null) {
- mPlayer.release();
- mPlayer = null;
- }
- }
- private class AudioRecordingDbmHandler extends DbmHandler<byte[]> implements Audiorecorder.RecordingCallback{
- private static final float MAX_DB_VALUE = 170;
- private float[] dbs;
- private float[] allAmps;
- float dBmArrayFirst = 0;
- float dBmArraySecond = 0;
- float dBmArrayThird = 0;
- float dBmArrayFourth = 0;
- int fcnCallCounter = 0;
- @Override
- protected void onDataReceivedImpl(byte[] bytes, int layersCount, float[] dBmArray, float[] ampsArray) {
- layersCount = 4;
- fcnCallCounter++;
- final int bytesPerSample = 2; // As it is 16bit PCM
- final double amplification = 100.0; // choose a number as you like
- Complex[] fft = new Complex[bytes.length / bytesPerSample];
- for (int index = 0, floatIndex = 0; index < bytes.length - bytesPerSample + 1; index += bytesPerSample, floatIndex++) {
- double sample = 0;
- for (int b = 0; b < bytesPerSample; b++) {
- int v = bytes[index + b];
- if (b < bytesPerSample - 1) {
- v &= 0xFF;
- }
- sample += v << (b * 8);
- }
- double sample32 = amplification * (sample / 32768.0);
- fft[floatIndex] = new Complex(sample32, 0);
- }
- fft = FFT.fft(fft);
- int dataSize = fft.length / 2 - 1;
- Log.d("ADebugTag", "bytesPerSample: " + bytesPerSample); //2
- Log.d("ADebugTag", "bytes.length: " + bytes.length); //2048
- Log.d("ADebugTag", "dataSize: " + dataSize); //511
- Log.d("ADebugTag", "fft.length: " + fft.length); //1024
- if (dbs == null || dbs.length != dataSize) {
- dbs = new float[dataSize];
- }
- if (allAmps == null || allAmps.length != dataSize) {
- allAmps = new float[dataSize];
- }
- for (int i = 0; i < dataSize; i++) { //511
- dbs[i] = (float) fft[i].abs(); //1
- float k = 1;
- if (i == 0 || i == dataSize - 1) {
- k = 2;
- }
- float re = (float) fft[2 * i].re();
- float im = (float) fft[2 * i + 1].im();
- float sqMag = re * re + im * im;
- allAmps[i] = (float) (k * Math.sqrt(sqMag) / dataSize);
- }
- int size = dbs.length / layersCount; //128
- for (int i = 0; i < layersCount; i++) { //4
- int index = (int) ((i + 0.5f) * size); //1*128 256 378 4*128
- float db = dbs[index]; //128 256 378 512
- float amp = allAmps[index]; //128 //
- dBmArray[i] = db > MAX_DB_VALUE ? 1 : db / MAX_DB_VALUE;
- ampsArray[i] = amp;
- Log.d("ADebugTag", "index: " + index); //1024
- range[i] = index;
- }
- Log.d("ADebugTag", "dBmArray: " + Arrays.toString(dBmArray));
- dBmArrayFirst = dBmArrayFirst + dBmArray[0];
- dBmArraySecond = dBmArraySecond + dBmArray[1];
- dBmArrayThird = dBmArrayThird + dBmArray[2];
- dBmArrayFourth = dBmArrayFourth + dBmArray[3];
- }
- public void stop() {
- float avgArrayFirst;
- float avgArraySecond;
- float avgArrayThird;
- float avgArrayFourth;
- int indexOfLargest;
- int indexOfSmallest;
- float hearingRange;
- ///////////Realm.init(getActivity());//////////////////////////////////
- ///////////realm = Realm.getDefaultInstance();
- //////////////////////////////////////////////////calmDownAndStopRendering();
- avgArrayFirst = dBmArrayFirst / fcnCallCounter;
- avgArraySecond = dBmArraySecond / fcnCallCounter;
- avgArrayThird = dBmArrayThird / fcnCallCounter;
- avgArrayFourth = dBmArrayFourth / fcnCallCounter;
- /* avgArrayValues[0] = avgArrayFirst;
- avgArrayValues[1] = avgArraySecond;
- avgArrayValues[2] = avgArrayThird;
- avgArrayValues[3] = avgArrayFourth;*/
- /* indexOfLargest = getIndexOfLargest(avgArrayValues);
- indexOfSmallest = getIndexOfSmallest(avgArrayValues);*/
- /* hearingRange = Math.abs((indexOfLargest - indexOfSmallest) * 128);*/
- /* Log.d("ADebugTag", "Index with max average amplitude: " + indexOfLargest); //1024
- Log.d("ADebugTag", "Index with min average amplitude: " + indexOfSmallest);
- Log.d("ADebugTag", "Hearing Ranges: " + hearingRange);
- realm.beginTransaction();
- SnoringFrequencies obj = realm.createObject(SnoringFrequencies.class);
- obj.setId(new Date().toString());
- obj.setFreq1(Float.toString(avgArrayFirst));
- obj.setFreq2(Float.toString(avgArraySecond));
- obj.setFreq3(Float.toString(avgArrayThird));
- obj.setFreq4(Float.toString(avgArrayFourth));
- realm.commitTransaction();*/
- }
- @Override
- public void onDataReady(byte[] data) {
- onDataReceived(data);
- }
- }
- public int getIndexOfLargest( float[] array )
- {
- if ( array == null || array.length == 0 ) return -1; // null or empty
- int largest = 0;
- for ( int i = 1; i < array.length; i++ )
- {
- if ( array[i] > array[largest] ) largest = i;
- }
- return largest; // position of the first largest found
- }
- public int getIndexOfSmallest( float[] array )
- {
- if ( array == null || array.length == 0 ) return -1; // null or empty
- int smallest = 0;
- for ( int i = 1; i < array.length; i++ )
- {
- if ( array[i] < array[smallest] ) smallest = i;
- }
- return smallest; // position of the first largest found
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment