//package your.package.name;
import android.os.Bundle;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.speech.RecognizerIntent;
import android.widget.Button;
import android.widget.TextView;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private int lang ;
ActivityResultLauncher<Intent> resultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == Activity.RESULT_OK) {
Intent resultData = result.getData();
if (resultData != null) {
// 認識結果を ArrayList で取得
ArrayList candidates =
resultData.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if(candidates.size() > 0) {
// 認識結果候補で一番有力なものを表示
textView.setText( candidates.get(0));
}
}
}
});
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 言語選択 0:日本語、1:英語、2:オフライン、その他:General
lang = 0;
// 認識結果を表示させる
textView = findViewById(R.id.text_view);
Button buttonStart = findViewById(R.id.button_start);
buttonStart.setOnClickListener(v -> {
// 音声認識を開始
speech();
});
}
private void speech(){
// 音声認識の Intent インスタンス
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
if(lang == 0){
// 日本語
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,Locale.JAPAN.toString() );
}
else if(lang == 1){
// 英語
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.ENGLISH.toString() );
}
else if(lang == 2){
// Off line mode
intent.putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, true);
}
else{
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
}
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 100);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "音声を入力");
try {
// インテント発行
resultLauncher.launch(intent);
}
catch (ActivityNotFoundException e) {
e.printStackTrace();
textView.setText(R.string.error);
}
}
}