package com.zatackcoder.audiorecorder;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    TextView notificationTV;
    Button startB;
    Button stopB;
    Button playB;
    MediaRecorder recorder;
    File audiofile;
    Boolean recording = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        notificationTV = (TextView)findViewById(R.id.notificationTV);
        startB = (Button)findViewById(R.id.startB);
        stopB = (Button)findViewById(R.id.stopB);
        playB = (Button)findViewById(R.id.playB);

        startB.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if(recording){
                    Toast.makeText(getApplicationContext(), "Already recording stop first", Toast.LENGTH_LONG).show();
                    return;
                }
                recorder = new MediaRecorder();
                try {
                    audiofile = File.createTempFile("sound", ".amr", Environment.getExternalStorageDirectory());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
                recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                recorder.setOutputFile(audiofile.getAbsolutePath());
                Toast.makeText(getApplicationContext(), audiofile.getAbsolutePath(), Toast.LENGTH_LONG).show();
                try {
                    recorder.prepare();
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
                    return;
                }
                recorder.start();   // Recording is now started
                recording = true;
                notificationTV.setText("Recording...");
                Toast.makeText(getApplicationContext(), "Recording started!", Toast.LENGTH_LONG).show();
            }
        });

        stopB.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if(!recording){
                    Toast.makeText(getApplicationContext(), "Recording not started yet!", Toast.LENGTH_LONG).show();
                    return;
                }
                recorder.stop();
                recorder.reset();   // You can reuse the object by going back to setAudioSource() step
                recorder.release(); // Now the object cannot be reused
                recording = false;
                notificationTV.setText("Recording stopped!");
                Toast.makeText(getApplicationContext(), "Recording stopped!", Toast.LENGTH_LONG).show();
                addRecordingToMediaLibrary();
            }
        });

        playB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(audiofile == null){
                    Toast.makeText(getApplicationContext(), "Not recorded yet!", Toast.LENGTH_LONG).show();
                    return;
                }
                MediaPlayer mp=new MediaPlayer();
                try{
                    mp.setDataSource(audiofile.getAbsolutePath());//Write your location here
                    mp.prepare();
                    mp.start();
                }catch(Exception e){
                    Toast.makeText(getApplicationContext(), "Problem occurred while playing!", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    protected void addRecordingToMediaLibrary() {
        //creating content values of size 4
        ContentValues values = new ContentValues(4);
        long current = System.currentTimeMillis();
        values.put(MediaStore.Audio.Media.TITLE, audiofile.getName());
        values.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000));
        values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/amr");
        values.put(MediaStore.Audio.Media.DATA, audiofile.getAbsolutePath());

        //creating content resolver and storing it in the external content uri
        ContentResolver contentResolver = getContentResolver();
        Uri base = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        Uri newUri = contentResolver.insert(base, values);

        //sending broadcast message to scan the media file so that it can be available
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, newUri));
        Toast.makeText(this, "File Added to Media Library" + newUri, Toast.LENGTH_LONG).show();
    }
}
