package com.example.kingway.ptt;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import timber.log.Timber;

import com.stand.standapp.MyApplication;

@SuppressWarnings("ResultOfMethodCallIgnored")
public class AudioRecordManager {
    private final String TAG = "AudioRecordManager";
    private static final int FREQUENCY = 8000;                  //16K采集率
    private AudioRecord mRecorder;
    private Thread recordThread;
    private boolean isStart = false;
    private static AudioRecordManager mInstance;
    private int bufferSize = 320;


    private AudioRecordManager() {
        initAudio();
    }

    public void initAudio() {
        //一、实例化一个AudioRecord类
        int audioSource = MediaRecorder.AudioSource.MIC;
        mRecorder = new AudioRecord(audioSource,
                FREQUENCY,
                AudioFormat.CHANNEL_IN_MONO,
                AudioFormat.ENCODING_PCM_16BIT,
                bufferSize * 2);
        Timber.tag(TAG).d("AudioRecord初始化: source=MIC, freq=%dHz, minBuf=%d", FREQUENCY, bufferSize * 2);
    }

    public void setRecording(){
        Timber.tag(TAG).d("setRecording -> startRecording()");
        if (mRecorder == null) initAudio();
        if(mRecorder.getRecordingState() != 3) mRecorder.startRecording();
    }

    public void stopAudio(){
        Timber.tag(TAG).d("stopAudio -> stop()");
        if (mRecorder != null){
            mRecorder.stop();
        }
    }

    public int getState(){
        if (mRecorder == null) initAudio();
        return mRecorder.getRecordingState();
    }

    public void destroyAudio(){
        Timber.tag(TAG).d("destroyAudio -> 释放AudioRecord");
        if (mRecorder != null){
            mRecorder.stop();
            mRecorder.release();
            mRecorder = null;
        }
    }


    /**
     * 获取单例引用
     */
    public static AudioRecordManager getInstance() {
        if (mInstance == null) {
            synchronized (AudioRecordManager.class) {
                if (mInstance == null) {
                    mInstance = new AudioRecordManager();
                }
            }
        }
        return mInstance;
    }

    /**
     * 销毁线程方法
     */
    private void destroyThread() {
        try {
            if (null != recordThread && Thread.State.RUNNABLE == recordThread.getState()) {
                try {
                    recordThread.interrupt();
                } catch (Exception e) {
                    Timber.tag(TAG).e(e, "录音线程interrupt失败");
                    recordThread = null;
                }
            }
            recordThread = null;
        } catch (Exception e) {
            Timber.tag(TAG).e(e, "destroyThread异常");
        } finally {
            recordThread = null;
        }
    }

    /**
     * 启动录音线程
     */
    private void startThread() {
        Timber.tag(TAG).d("启动录音线程");
        destroyThread();
        isStart = true;
        if (mRecorder == null) {
            initAudio();
        }
        if (recordThread == null) {
            recordThread = new Thread(recordRunnable);
            recordThread.start();
        }
    }

    /**
     * 录音线程
     */
    private Runnable recordRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
                int bytesRecord;
                byte[] tempBuffer = new byte[bufferSize];
                if (mRecorder.getState() != AudioRecord.STATE_INITIALIZED) {
                    Timber.tag(TAG).w("AudioRecord未初始化(state=%d)，终止录音", mRecorder.getState());
                    stopRecord();
                    return;
                }
                mRecorder.startRecording();
                Timber.tag(TAG).d("录音线程: startRecording() 成功");
                int count = 0;
                while (isStart) {
                    if (null != mRecorder) {
                        bytesRecord = mRecorder.read(tempBuffer, 0, bufferSize);
                        if (bytesRecord == AudioRecord.ERROR_INVALID_OPERATION
                                || bytesRecord == AudioRecord.ERROR_BAD_VALUE) {
                            continue;
                        }
                        if (bytesRecord != 0 && bytesRecord != -1) {
                            Timber.tag(TAG).v("录音帧: %d bytes", bytesRecord);
                            MyApplication.getAppInstance().getpNative().pttNativeSendRecordCmd(tempBuffer);
                        } else {
                            Timber.tag(TAG).w("录音循环退出: bytesRecord=%d", bytesRecord);
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                Timber.tag(TAG).e(e, "录音线程异常");
            }
        }

    };

    /**
     * 启动录音
     */
    public void startRecord() {
        Timber.tag(TAG).d("startRecord() 被调用");
        try {
            stopRecord();

            startThread();
        } catch (Exception e) {
            Timber.tag(TAG).e(e, "startRecord异常");
        }
    }

    /**
     * 停止录音
     */
    public void stopRecord() {
        Timber.tag(TAG).d("stopRecord() 被调用");
        try {
            destroyThread();
            if (mRecorder != null) {
                try {
                    if (mRecorder.getState() == AudioRecord.STATE_INITIALIZED) {
                        mRecorder.stop();
                    }
                    mRecorder.release();
                    mRecorder = null;
                } catch (Exception e) { Timber.tag(TAG).e(e, "释放AudioRecord失败"); }
            }
        } catch (Exception e) {
            Timber.tag(TAG).e(e, "stopRecord异常");
        } finally {
        }
    }

}