In this video it shows the steps to build your own AI (ChatGPT) based voice assistant Android App.
In this demo it refers the code from programmer world’s below 3 pages:
https://programmerworld.co/android/how-to-integrate-open-ai-chat-gpt-model-gpt-3-5-turbo-in-your-android-app/
https://programmerworld.co/android/how-to-convert-text-to-speech-in-your-android-app-complete-source-code/
https://programmerworld.co/android/how-to-create-a-personal-voice-assistant-android-app-to-create-a-text-file-complete-source-code/
Some of the questions prompted for AI/ ChatGPT tool demo were:
– Who won the last football World Cup?
– How do you define God?
– Which is the best place to visit in Europe?
I hope you like this video. For any questions, suggestions or appreciation please contact us at: https://programmerworld.co/contact/ or email at: programmerworld1990@gmail.com
Complete source code and other details:
package com.programmerworld.voicebasedassistantaitool_chatgpt;
import static android.Manifest.permission.RECORD_AUDIO;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private EditText editText;
private String stringURLEndPoint = "https://api.openai.com/v1/chat/completions";
private String stringAPIKey = "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";
private String stringOutput = "";
private TextToSpeech textToSpeech;
private SpeechRecognizer speechRecognizer;
private Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(this,
new String[]{RECORD_AUDIO},
PackageManager.PERMISSION_GRANTED);
textView = findViewById(R.id.textView);
editText = findViewById(R.id.editText);
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int i) {
textToSpeech.setSpeechRate((float) 0.8);
}
});
intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
speechRecognizer.setRecognitionListener(new RecognitionListener() {
@Override
public void onReadyForSpeech(Bundle bundle) {
}
@Override
public void onBeginningOfSpeech() {
}
@Override
public void onRmsChanged(float v) {
}
@Override
public void onBufferReceived(byte[] bytes) {
}
@Override
public void onEndOfSpeech() {
}
@Override
public void onError(int i) {
}
@Override
public void onResults(Bundle bundle) {
ArrayList<String> matches = bundle.getStringArrayList(speechRecognizer.RESULTS_RECOGNITION);
String string = "";
textView.setText("");
if (matches != null) {
string = matches.get(0);
editText.setText(string);
chatGPTModel(string);
}
}
@Override
public void onPartialResults(Bundle bundle) {
}
@Override
public void onEvent(int i, Bundle bundle) {
}
});
}
public void buttonAssist(View view){
if (textToSpeech.isSpeaking()){
textToSpeech.stop();
return;
}
stringOutput = "";
speechRecognizer.startListening(intent);
}
private void chatGPTModel(String stringInput){
textView.setText("In Progress ...");
textToSpeech.speak("In Progress", TextToSpeech.QUEUE_FLUSH, null,null);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("model", "gpt-3.5-turbo");
JSONArray jsonArrayMessage = new JSONArray();
JSONObject jsonObjectMessage = new JSONObject();
jsonObjectMessage.put("role", "user");
jsonObjectMessage.put("content", stringInput);
jsonArrayMessage.put(jsonObjectMessage);
jsonObject.put("messages", jsonArrayMessage);
} catch (JSONException e) {
throw new RuntimeException(e);
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
stringURLEndPoint, jsonObject, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
String stringText = null;
try {
stringText = response.getJSONArray("choices")
.getJSONObject(0)
.getJSONObject("message")
.getString("content");
} catch (JSONException e) {
throw new RuntimeException(e);
}
stringOutput = stringOutput + stringText;
textView.setText(stringOutput);
textToSpeech.speak(stringOutput, TextToSpeech.QUEUE_FLUSH, null,null);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> mapHeader = new HashMap<>();
mapHeader.put("Authorization", "Bearer " + stringAPIKey);
mapHeader.put("Content-Type", "application/json");
return mapHeader;
}
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
return super.parseNetworkResponse(response);
}
};
int intTimeoutPeriod = 60000; // 60 seconds timeout duration defined
RetryPolicy retryPolicy = new DefaultRetryPolicy(intTimeoutPeriod,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jsonObjectRequest.setRetryPolicy(retryPolicy);
Volley.newRequestQueue(getApplicationContext()).add(jsonObjectRequest);
}
}
<?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"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="368dp"
android:layout_height="411dp"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.496"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.603" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="136dp"
android:layout_marginTop="105dp"
android:onClick="buttonAssist"
android:text="Assist"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/editText"
android:layout_width="334dp"
android:layout_height="69dp"
android:layout_marginStart="38dp"
android:layout_marginTop="16dp"
android:ems="10"
android:hint="Input here ..."
android:inputType="text"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.VoiceBasedAssistantAIToolChatgpt"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
plugins {
id("com.android.application")
}
android {
namespace = "com.programmerworld.voicebasedassistantaitool_chatgpt"
compileSdk = 34
defaultConfig {
applicationId = "com.programmerworld.voicebasedassistantaitool_chatgpt"
minSdk = 34
targetSdk = 34
versionCode = 1
versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
}
dependencies {
implementation("androidx.appcompat:appcompat:1.6.1")
implementation("com.google.android.material:material:1.9.0")
implementation("androidx.constraintlayout:constraintlayout:2.1.4")
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test.ext:junit:1.1.5")
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
implementation("com.android.volley:volley:1.2.1")
}
Screenshots: