package com.cooleshow.musictuner;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewbinding.ViewBinding;
import be.tarsos.dsp.AudioDispatcher;
import be.tarsos.dsp.AudioEvent;
import be.tarsos.dsp.AudioProcessor;
import be.tarsos.dsp.io.android.AudioDispatcherFactory;
import be.tarsos.dsp.pitch.PitchDetectionHandler;
import be.tarsos.dsp.pitch.PitchDetectionResult;
import be.tarsos.dsp.pitch.PitchProcessor;

import android.os.Bundle;
import android.view.LayoutInflater;

import com.cooleshow.base.ui.activity.BaseActivity;
import com.cooleshow.musictuner.bean.VoiceToneBean;
import com.cooleshow.musictuner.databinding.ActivityMainBinding;
import com.cooleshow.musictuner.utils.VoiceDataUtils;

public class MusicTunerActivity extends BaseActivity<ActivityMainBinding> {

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

    @Override
    protected void initView() {

    }

    @Override
    protected ActivityMainBinding getLayoutView() {
        return ActivityMainBinding.inflate(getLayoutInflater());
    }

    private void test(){
        AudioDispatcher dispatcher =
                AudioDispatcherFactory.fromDefaultMicrophone(22050, 1024, 0);
        PitchDetectionHandler pdh = new PitchDetectionHandler() {
            @Override
            public void handlePitch(PitchDetectionResult res, AudioEvent e) {
                final float pitchInHz = res.getPitch();
                final float probability = res.getProbability();
                VoiceToneBean voiceToneBean = VoiceDataUtils.getInstance().searchTarget(pitchInHz);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        mTvResult.setText(pitchInHz + "Hz");
//                        if (voiceToneBean != null) {
//                            mTvResultVoiceTones.setText(voiceToneBean.name);
//                            mBeforeResultVoiceTones.setText(voiceToneBean.beforeName);
//                            mAfterResultVoiceTones.setText(voiceToneBean.afterName);
//                            mTvDifference.setText(voiceToneBean.difference);
//                        }
                    }
                });
//                Log.i("pq", "pitchInHz:" + pitchInHz);
//                Log.i("pq", "probability:" + probability);
            }
        };
        AudioProcessor p = new PitchProcessor(PitchProcessor.PitchEstimationAlgorithm.FFT_YIN, 22050, 1024, pdh);
        dispatcher.addAudioProcessor(p);
        new Thread(dispatcher, "Audio Dispatcher").start();
    }
}