package com.example.helloaquestalk;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import aquestalk.AquesTalk;	// AquesTalkクラス 別途libAquesTalk.soが必要

public class MainActivity extends AppCompatActivity {
    AudioTrack audioTrack;
    private static final int FS = 16000;	//[Hz]

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        String koe = "ゆっくりしていってね？";
        AquesTalk.setDevKey("xxx-xxx-xxx"); // 開発ライセンスキーを指定
        AquesTalk.setUsrKey("zzz-zzz-zzz"); // 使用ライセンスキーを指定
        // 音声合成
        AquesTalk aquestalk = new AquesTalk(AquesTalk.PRESET.F1);
        aquestalk.spd = 90;
        byte[] wav = aquestalk.synthe(koe);

        if(wav.length==1){//生成エラー時には,長さ１で、先頭にエラーコードが返される
            Log.v("AQTKAPP", "AquesTalk2 Synthe ERROR:"+wav[0]);
        }
        else {
            //音声データを再生出力
            if(audioTrack!=null) {// インスタンスがあれば停止/解放
                audioTrack.stop();
                audioTrack.release();
            }
            audioTrack = new AudioTrack(
                    AudioManager.STREAM_MUSIC,
                    FS,
                    AudioFormat.CHANNEL_OUT_MONO,
                    AudioFormat.ENCODING_PCM_16BIT,
                    wav.length-44,
                    AudioTrack.MODE_STATIC);
            audioTrack.write(wav, 44, wav.length-44);// 44:wavのヘッダサイズ
            audioTrack.play();
        }
        TextView textView = findViewById(R.id.text_view);
        textView.setText("音声記号列："+koe);
    }

    @Override
    public void onDestroy() {
        if(audioTrack!=null) audioTrack.release();
        super.onDestroy();
    }
}