Voice Recognition Android Часть 3

MainActivity.java

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;


import java.util.ArrayList;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
private TextView textTest;
private ImageView imMain;
private SoundPool sounds;
private int sound_sirena;
private TextToSpeech textToSpeech;


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


}
private void init()
{
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR)
{
textToSpeech.setLanguage(Locale.getDefault());
}
}
});
textTest = findViewById(R.id.textTest);
imMain = findViewById(R.id.imMain);
createSoundPool();
loadSounds();
}
public void onClickMic(View view)
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
startActivityForResult(intent, 10);
}



@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && data != null)
{
switch (requestCode)
{
case 10:
ArrayList<String> text = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
textCommand(text.get(0));
break;

}
}
}

private void textCommand(String text)
{
switch (text)
{
case "яблоко":
imMain.setImageResource(R.drawable.manzana_lista);
break;
case "дыня":
imMain.setImageResource(R.drawable.melon_listo);
break;
case "арбуз":
imMain.setImageResource(R.drawable.sandia_listo);
break;
case "корова":
imMain.setImageResource(R.drawable.vaca_lista);
break;
case "протокол самоуничтожения":
protocolDist();
break;
case "Какой самый лучший канал на Ютюбе":
textToSpeech.speak("Лучший ютуб канал это конечно канал НЭКО, и не забудь подписаться!! Вот такие дела? Еще что нибудь? Ну тогда пока!",
TextToSpeech.QUEUE_FLUSH, null);
break;
case "конец":
textToSpeech.speak("Всем спасибо за внимание, ставь палец вверх и подписывайся, увидимся на следующем видео!",
TextToSpeech.QUEUE_FLUSH, null);
break;
}
}
private void protocolDist()
{
sounds.play(sound_sirena,1.0f,1.0f,1,0,1);
new Thread(new Runnable()
{
@Override
public void run()
{
for(int i = 0; i < 6; i++)
{
try
{
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

final int finalI = 5 - i;
textTest.post(new Runnable()
{
@Override
public void run()
{
textTest.setText(String.valueOf(finalI));
}
});
}
runOnUiThread(new Runnable()
{
@Override
public void run()
{
imMain.setImageResource(R.drawable.calavera);
}
});
}
}).start();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
protected void createNewSoundPool(){
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_GAME)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
sounds = new SoundPool.Builder()
.setAudioAttributes(attributes)
.build();
}

@SuppressWarnings("deprecation")
protected void createOldSoundPool(){

sounds = new SoundPool(5, AudioManager.STREAM_MUSIC,0);
}
protected void createSoundPool() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
createNewSoundPool();
} else {
createOldSoundPool();
}
}
private void loadSounds()
{
sound_sirena = sounds.load(this,R.raw.sirena, 1);
}
}



activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/black"
tools:context=".MainActivity">

<TextView
android:id="@+id/textTest"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_marginTop="48dp"
android:background="@drawable/circle_bg"
android:gravity="center"
android:text="5"
android:textColor="@color/green"
android:textSize="100sp"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="36dp"
android:background="@drawable/oval_button"
android:onClick="onClickMic"
android:text="Mic"
android:textColor="@color/green"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent" />

<ImageView
android:id="@+id/imMain"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_marginTop="48dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textTest"
app:srcCompat="@drawable/manzana_lista" />

</androidx.constraintlayout.widget.ConstraintLayout>

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#424242</color>
<color name="colorPrimaryDark">#404040</color>
<color name="colorAccent">#D81B60</color>
<color name="green">#7FEC21</color>
<color name="black">#323232</color>
</resources>

styles.xml

<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:windowFullscreen">true</item>
</style>

</resources>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.neco_desarrollo.voicecommander_1">
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

circle_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<corners android:radius="100dp"/>
<stroke android:color="@color/green" android:width="2dp"/>

</shape>

oval_button.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:topRightRadius="10dp" android:bottomRightRadius="10dp"
android:topLeftRadius="10dp" android:bottomLeftRadius="10dp"/>
<stroke android:color="@color/green" android:width="2dp"/>

</shape>

2 комментария для “Voice Recognition Android Часть 3”

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *