I am using the audiodispatcher from the TarsosDSPlibrary.
The pitchdetection is used to detect sounds from the mic. Once detected, it switches to the next activity (which is a Maths quiz). After completing the quiz on the next activity, it returns to this activity and starts the process all over again.
What is bugging me is that my APP is working 90% of the time when using the pitchdetection function. However, sometimes it doesn't work and throws an error as follows:
E/AudioRecord: start() status -38
and the app no longers switches to the next activity.
package com.humanfactorsandappliedcognitionlab.research.mathsapp;
import android.content.Context;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.IBinder;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import java.util.HashMap;
import java.util.Locale;
import java.util.concurrent.RunnableFuture;
import be.tarsos.dsp.AudioDispatcher;
import be.tarsos.dsp.AudioEvent;
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;
public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener {
MediaPlayer notifySound;
MediaPlayer endSound;
AudioDispatcher dispatcherMAIN;
PitchProcessor pitchProcessorMAIN;
public boolean isListening = false;
TextToSpeech tts;
private int sensitivity = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notifySound = MediaPlayer.create(this, R.raw.samsung);
endSound = MediaPlayer.create(this, R.raw.ding);
OPTION = dbHandler.getOPTION();
tts = new TextToSpeech(this, this);
tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
runOnUiThread(new Runnable() {
#Override
public void run(){
}
});
}
#Override
public void onDone(String utteranceId) {
runOnUiThread(new Runnable() {
#Override
public void run(){
startListenToTalk();
}
});
}
#Override
public void onError(String utteranceId) {
}
});
}
private void speakOut() {
Log.e("TTS", "SPEAKING...");
String text = "Please Say Continue to Proceed ";
HashMap<String, String> map = new HashMap<String, String>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "");
tts.speak(text, TextToSpeech.QUEUE_FLUSH, map);
}
private void startListenToTalk() {
dispatcherMAIN = AudioDispatcherFactory.fromDefaultMicrophone(22050, 1024, 0);
pitchProcessorMAIN = new PitchProcessor(PitchProcessor.PitchEstimationAlgorithm.FFT_YIN, 22050, 1024, new PitchDetectionHandler() {
#Override
public void handlePitch(PitchDetectionResult pitchDetectionResult,
AudioEvent audioEvent) {
final float pitchInHz = pitchDetectionResult.getPitch();
runOnUiThread(new Runnable() {
#Override
public void run() {
ImageButton buttonOK = (ImageButton) findViewById(R.id.buttonOK);
TextView textINPUT = (TextView)findViewById(R.id.textINPUT);
if (pitchInHz > sensitivity) {
Log.e("pitch : ", pitchInHz + "");
if (isListening) {
try {
dispatcherMAIN.stop();
Intent gotoMaths = new Intent(MainActivity.this, MathsActivity.class);
startActivity(gotoMaths);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
});
}
});
dispatcherMAIN.addAudioProcessor(pitchProcessorMAIN);
new Thread(dispatcherMAIN, "Audio Dispatcher").start();
isListening = true;
}
#Override
protected void onPause() {
super.onPause();
if (notifySound != null) {
notifySound.release();
}
if (endSound != null) {
endSound.release();
}
if (isListening) {
try {
dispatcherMAIN.stop();
} catch (Exception e) {
e.printStackTrace();
}
isListening = false;
}
finish();
}
#Override
public void onStop(){
super.onStop();
if (tts != null) {
tts.shutdown();
}
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
if(OPTION == "3") {
speakOut();
}
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
Related
I am facing a problem, I have implemented a code, it is showing me message in Logs correctly but it doesn't update the TextView's text. Here i have tried this version. How i can update it? I tried it using threads as well but in vain.
I have seen many solution over this StackOverflow platform but i could not find my any solution for my problem.
package com.example.yousafmoh.seizuredetection;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.AsyncTask;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
public class ledControl extends AppCompatActivity {
// Button btnOn, btnOff, btnDis;
ImageButton On, Off, Discnt, Abt;
TextView txtMessage;
String address = null;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
//SPP UUID. Look for it
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent newint = getIntent();
address = newint.getStringExtra(DeviceList.EXTRA_ADDRESS); //receive the address of the bluetooth device
//view of the ledControl
setContentView(R.layout.activity_led_control);
//call the widgets
On = (ImageButton)findViewById(R.id.on);
Off = (ImageButton)findViewById(R.id.off);
Discnt = (ImageButton)findViewById(R.id.discnt);
Abt = (ImageButton)findViewById(R.id.abt);
txtMessage = (TextView) findViewById(R.id.txtMessage);
new ConnectBT().execute(); //Call the class to connect
//myBluetoothThread();
//commands to be sent to bluetooth
On.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
turnOnLed(); //method to turn on
}
});
Off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
turnOffLed(); //method to turn off
}
});
Discnt.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Disconnect(); //close connection
}
});
}
private void myBluetoothThread() {
while(true)
{
if (btSocket!=null)
{
try
{
if(isBtConnected) {
InputStream inputStream = btSocket.getInputStream();
for (int i = 0; i <= inputStream.available(); i++) {
//Log.d("data", inputStream.read() + " "+"ok");
int val = inputStream.read();
if (val == 49) // seizure detected
{
this.runOnUiThread(new Runnable() {
#Override
public void run() {
txtMessage.setText("Seizure Detected!!!");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
Log.d("Message", " Detected");
}
});
Log.d("Message", " Detected");
} else if (val == 48) // no detection
{
this.runOnUiThread(new Runnable() {
#Override
public void run() {
txtMessage.setText("Normal Condition");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_blue_dark));
Log.d("Message", "not Detected");
}
});
Log.d("Message", "not Detected");
//, Toast.LENGTH_SHORT).show();
}
}
}
}
catch (IOException e)
{
msg("Error");
}
}
}
}
private void Disconnect()
{
if (btSocket!=null) //If the btSocket is busy
{
try
{
btSocket.close(); //close connection
}
catch (IOException e)
{ msg("Error");}
}
finish(); //return to the first layout
}
private void turnOffLed()
{
if (btSocket!=null)
{
try
{
InputStream inputStream = btSocket.getInputStream();
for(int i = 0 ; i <= inputStream.available();i++)
{
Log.d("data",inputStream.read()+" ");
}
Log.d("Bytes available off",String.valueOf(inputStream.available()));
Log.d("Message off",String.valueOf(inputStream.read()));
//btSocket.getOutputStream().write("0".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
private void turnOnLed()
{
if (btSocket!=null)
{
try
{
InputStream inputStream = btSocket.getInputStream();
Log.d("Bytes available on",String.valueOf(inputStream.available()));
Log.d("Message on",String.valueOf(inputStream.read()));
Log.d("Message on",inputStream.toString());
btSocket.getOutputStream().write("1".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
// fast way to call Toast
private void msg(String s)
{
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
public void about(View v)
{
if(v.getId() == R.id.abt)
{
Intent i = new Intent(this, AboutActivity.class);
startActivity(i);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_led_control, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
#Override
protected void onPreExecute()
{
progress = ProgressDialog.show(ledControl.this, "Connecting...", "Please wait!!!"); //show a progress dialog
}
#Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try
{
if (btSocket == null || !isBtConnected)
{
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
progress.dismiss();
}
}
catch (IOException e)
{
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
#Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
msg("Connection Failed. Is it a SPP Bluetooth? Try again.");
finish();
}
else
{
msg("Connected.");
isBtConnected = true;
}
if(progress!=null)
progress.dismiss();
if(isBtConnected)
{
myBluetoothThread();
}
}
}
}
Try using this if its a fragment class
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
txtMessage.setText("Normal Condition");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_blue_dark));
}
});
and this is its an activity
this.runOnUiThread(new Runnable() {
#Override
public void run() {
txtMessage.setText("Normal Condition");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_blue_dark));
}
});
Another solution u can try is.
You can use handler
Handler handler = new Handler();
handler.post(new Runnable() {
public void run() {
txtMessage.setText("Seizure Detected!!!");
txtMessage.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
}
});
I have read some article somewhere that you should not update your textview directly inside the Runnable Thread. So what I did is i created a function that updates the textview then the Runnable run method calls that function. So It look like this.
public class SampleActivity extends AppCompatActivity {
TextView sample;
int counter = 0;
Handler handler;
Runnable runnable;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample);
sample = findViewById(R.id.sample);
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
counter++;
updateTextView("Counter: " + counter);
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(runnable, 1000);
}
public void updateTextView(String message) {
sample.setText(message);
}
But I tried it calling the sample.setText("Counter: "+counter) inside the Runnable Thread, it still works though.
Btw here is my sample.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/sample"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="SAWSAW"
android:textColor="#000"
android:textSize="32dp" />
</LinearLayout>
I am writing a text-to-speech android application. I am refactoring the code and trying to separate TextToSpeech class from an activity to a service so the UI can be updated without blocking, while the audio is playing in the background. However I am not able to wait for the TTS engine to initialize.
When I use
while(isInit==false)
Thread.sleep(1000);
the service never calls the onServiceConnected method.
If anybody knows how to wait for initialization of the TTS engine to complete, and avoid blocking the UI for too long (which causes the application to crash), help would be greatly appreciated!
Here is my service
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import java.util.HashMap;
import java.util.Locale;
public class MyTTSService extends Service {
private static final String TAG = "Class-MyTTSService";
private TextToSpeech tts;
private boolean isInit = false;
private final IBinder myBinder = new MyBinder();
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "Creating TTS Service");
Context context = this.getApplicationContext();
this.tts = new TextToSpeech(context, onInitListener);
this.tts.setOnUtteranceProgressListener(utteranceProgressListener);
Log.d(TAG, "TTS Service Created");
// why is this blocking everything?
while(!isInitComplete()){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.d(TAG, e.toString());
}
}
}
public boolean isInitComplete(){
return isInit;
}
#Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
public void waitToFinishSpeaking() {
while (tts.isSpeaking()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Log.d(TAG, e.toString());
}
}
}
public void speak(String text, AppCompatActivity appCompatActivity) {
Log.d(TAG, "Speak" + text);
appCompatActivity.setVolumeControlStream(AudioManager.STREAM_MUSIC);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
HashMap<String, String> param = new HashMap<>();
param.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_MUSIC));
tts.speak(text, TextToSpeech.QUEUE_ADD, null);
} else {
String utteranceId=this.hashCode() + "";
Bundle bundle = new Bundle();
bundle.putInt(TextToSpeech.Engine.KEY_PARAM_STREAM, AudioManager.STREAM_MUSIC);
tts.speak(text, TextToSpeech.QUEUE_ADD, null, null);
}
}
private UtteranceProgressListener utteranceProgressListener = new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
}
#Override
public void onDone(String utteranceId) {
}
#Override
public void onError(String utteranceId) {
Log.e(TAG, "Error while trying to synthesize sample text");
}
};
private TextToSpeech.OnInitListener onInitListener = new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
//init success
isInit = true;
Log.d(TAG, "TTS Initialized.");
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
};
#Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "Binding TTS Service");
return myBinder;
}
public class MyBinder extends Binder {
MyTTSService getService() {
return MyTTSService.this;
}
}
#Override
public boolean onUnbind(Intent intent) {
return false;
}
}
And here is my activity
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
public class ReaderActivity extends AppCompatActivity {
private static final String TAG = "Class-ReaderActivity";
EditText textBox;
ArrayList<String> sentences = new ArrayList<String>();
MyTTSService tts;
boolean isBound = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reader);
textBox = (EditText) findViewById(R.id.readerTextArea);
Intent intentExtras = getIntent();
Bundle extrasBundle = intentExtras.getExtras();
sentences = extrasBundle.getStringArrayList("sentences");
textBox.setText(sentences.toString(), TextView.BufferType.NORMAL);
textBox.setKeyListener(null);
}
#Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, MyTTSService.class);
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
Log.d(TAG, "Waiting to bind to service");
}
public void readSentences(){
for(String sentence : sentences){
Log.d(TAG +"Sencence", sentence);
//updateUI(sentence);
tts.speak(sentence, this);
tts.waitToFinishSpeaking();
}
}
private ServiceConnection serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MyTTSService.MyBinder binder = (MyTTSService.MyBinder) service;
tts = binder.getService();
isBound = true;
readSentences();
}
#Override
public void onServiceDisconnected(ComponentName name) {
isBound = false;
}
};
}
I found the solution. Remove the existing wait loop from MyTTSService.onCreate().
Place the following at the end of the onServiceConnected method
new Thread(new Runnable() {
public void run(){
readSentences();
}
}).start();
Then add a method to MyTTSService
public boolean isInit(){
return isInit;
}
In some circumstances the tts module may need to be reinitialised. Add the following to TextToSpeech.OnInitListener.OnInit in the cases where initialisation is unsuccessful.
isInit = false;
Then finally add the following to the readsentences method
while(!tts.isInit()){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.d(TAG, e.toString());
}
}
tts.speak(sentence, this);
With these changes the TTS module initialises, audio works, the Activity loads and the UI can be refreshed while audio is playing.
This should finally put the issue (which has been asked several times but never resolved) to bed for good.
I am very new to android. Following is my code and I am getting these errors.
Cannot resolve symbol params.
Variable "blinkDelay" never assigned.
When i hover the mouse over "Parameters". it says "android.hardware.Camera.Parameters Alt+Enter".
In the following code:
blinkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String myString = "0101010101";
long blinkDelay 50;
for (int i = 0; i < myString.length(); i++) {
if (myString.charAt(i) == '0') {
params.setFlashMode(Parameters.FLASH_MODE_ON);
} else {
params.setFlashMode(Parameters.FLASH_MODE_OFF);
}
try {
Thread.sleep(blinkDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Here is my full MainActivity.java
package com.fusion.flashlight;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
public class MainActivity extends AppCompatActivity {
private CameraManager mCameraManager;
private String mCameraId;
private ImageButton mTorchOnOffButton;
private ImageButton firstButton;
private Button blinkButton;
private Boolean isTorchOn;
private MediaPlayer media;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("MainActivity", "onCreate()");
setContentView(R.layout.activity_main);
mTorchOnOffButton = (ImageButton) findViewById(R.id.btnSwitch);
firstButton = (ImageButton) findViewById(R.id.btn1Switch);
blinkButton = (Button) findViewById(R.id.blinking);
isTorchOn = false;
Boolean isFlashAvailable = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!isFlashAvailable) {
AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
.create();
alert.setTitle("Error !!");
alert.setMessage("Your device doesn't support flash light!");
alert.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// closing the application
finish();
System.exit(0);
}
});
alert.show();
return;
}
mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
mCameraId = mCameraManager.getCameraIdList()[0];
} catch (CameraAccessException e) {
e.printStackTrace();
}
mTorchOnOffButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (isTorchOn) {
turnOffFlashLight();
isTorchOn = false;
} else {
turnOnFlashLight();
isTorchOn = true;
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
blinkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String myString = "0101010101";
long blinkDelay 50;
for (int i = 0; i < myString.length(); i++) {
if (myString.charAt(i) == '0') {
params.setFlashMode(Parameters.FLASH_MODE_ON);
} else {
params.setFlashMode(Parameters.FLASH_MODE_OFF);
}
try {
Thread.sleep(blinkDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
public void turnOnFlashLight() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, true);
playOnOffSound();
mTorchOnOffButton.setImageResource(R.drawable.btn_on);
firstButton.setImageResource(R.drawable.btn11_on);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void turnOffFlashLight() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, false);
playOnOffSound();
mTorchOnOffButton.setImageResource(R.drawable.btn_off);
firstButton.setImageResource(R.drawable.btn11_off);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void playOnOffSound(){
media = MediaPlayer.create(MainActivity.this, R.raw.light_switch_on);
media.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
//TODO Auto-generated method stub
mp.release();
}
});
media.start();
}
#Override
protected void onStop() {
super.onStop();
if(isTorchOn){
turnOffFlashLight();
}
}
#Override
protected void onPause() {
super.onPause();
if(isTorchOn){
turnOffFlashLight();
}
}
#Override
protected void onResume() {
super.onResume();
if(isTorchOn){
turnOnFlashLight();
}
}
}
For blinkDelay, you are missing an equal symbol when assigning,
For params, I cant see where do you create that variable.
And the other, alt+Enter is for autoImporting the Parameters class by Android Studio.
Cannot resolve symbol params. params not define
Variable "blinkDelay" never assigned. blinkDelay having no initial value
long blinkDelay =50;
When i hover the mouse over "Parameters". it says
"android.hardware.Camera.Parameters Alt+Enter". Alt+Enter for import
Below is my code.I am unable to hear the voice in my kitkat device.Toast is appearing but voice is not playing.I am following this tutorial
https://www.tutorialspoint.com/android/android_text_to_speech.htm
package com.example.insert;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Locale;
import android.widget.Toast;
import android.util.Log;
import java.lang.Object;
public class SecondActivity extends AppCompatActivity {
TextToSpeech t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
String emailid;
emailid = "Hi,say your email id";
t1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = t1.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(getApplicationContext(), "This language is not supported", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "Initialization failed", Toast.LENGTH_SHORT).show();
}
}
});
// Toast.makeText(getApplicationContext(), emailid, Toast.LENGTH_SHORT).show();
t1.speak(emailid, TextToSpeech.QUEUE_FLUSH, null);
}
#Override
protected void onDestroy() {
super.onDestroy();
// Don't forget to shutdown tts!
if (t1 != null) {
Log.e("TTS","speech on destroy");
t1.stop();
t1.shutdown();
}
}
}
I have followed this post on stackoverflow.
Android TTS doesn't speak
But i didn't understand gameover,line and definition_string.
guys help me
Here is my code. this code works on Nexus9.(Locale is Japan)
public class MainActivity extends AppCompatActivity{
static final String TAG = "TTS";
TextToSpeech mTts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String emailid;
emailid = "こんにちは";
mTts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = mTts.setLanguage(Locale.JAPAN);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(getApplicationContext(), "This language is not supported", Toast.LENGTH_SHORT).show();
}
else{
Log.v("TTS","onInit succeeded");
speak(emailid);
}
} else {
Toast.makeText(getApplicationContext(), "Initialization failed", Toast.LENGTH_SHORT).show();
}
}
});
setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
void speak(String s){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Log.v(TAG, "Speak new API");
Bundle bundle = new Bundle();
bundle.putInt(TextToSpeech.Engine.KEY_PARAM_STREAM, AudioManager.STREAM_MUSIC);
mTts.speak(s, TextToSpeech.QUEUE_FLUSH, bundle, null);
} else {
Log.v(TAG, "Speak old API");
HashMap<String, String> param = new HashMap<>();
param.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_MUSIC));
mTts.speak(s, TextToSpeech.QUEUE_FLUSH, param);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
// Don't forget to shutdown tts!
if (mTts != null) {
Log.v(TAG,"onDestroy: shutdown TTS");
mTts.stop();
mTts.shutdown();
}
}
}
It takes some time to initialise. Put the speak code in onClick method. If you trigger that method on button click, it will speak.
someButton.setOnClickListener(new OnClickListener{
onClick(View view){
t1.speak(emailid, TextToSpeech.QUEUE_FLUSH, null);
}
}
I guess problem is with Locale.
Please print logs. try out following code.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Locale;
import android.widget.Toast;
public class SecondActivity extends AppCompatActivity {
TextToSpeech t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
String emailid;
emailid="Hi,say your email id";
t1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status == TextToSpeech.SUCCESS) {
t1.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.d(TAG, "This Language is not supported");
}
}else{
Log.d(TAG, "Initilization Failed!");
}
}
});
Toast.makeText(getApplicationContext(), emailid,Toast.LENGTH_SHORT).show();
t1.speak(emailid, TextToSpeech.QUEUE_FLUSH, null);
}
#Override
protected void onDestroy() {
super.onDestroy();
// Don't forget to shutdown tts!
if (mTextToSpeech != null) {
Log.d(TAG, "speach on destroy");
t1.stop();
t1.shutdown();
}
}
I don't understand why didn't you implement your main Activity class from TextToSpeech.OnInitListener...!
Here's your answer:
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class AndroidTextToSpeechActivity extends Activity implements
TextToSpeech.OnInitListener {
/** Called when the activity is first created. */
private TextToSpeech tts;
private Button btnSpeak;
private EditText txtText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tts = new TextToSpeech(this, this);
btnSpeak = (Button) findViewById(R.id.btnSpeak);
txtText = (EditText) findViewById(R.id.txtText);
// button on click event
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
speakOut();
}
});
}
#Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
btnSpeak.setEnabled(true);
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void speakOut() {
String text = txtText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
I am trying to get the Android TTS API to read my "utterance" and then call the onUtteranceCompleted() listener unsuccessfully. I've registered my TTS object and it returns SUCCESS, so I can't figure out for the life of me why my callback isn't getting called.
I've tried searching for help, but it seems others have difficulty with this too. Am I missing something simple?
Thanks for any help you can offer.
package com.test.mytts;
import java.util.HashMap;
import android.app.Activity;
import android.media.AudioManager;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.widget.TextView;
import android.widget.Toast;
public class MyTTS extends Activity implements OnInitListener, OnUtteranceCompletedListener
{
TextView tv;
private TextToSpeech _tts;
#Override
public void onCreate(Bundle savedInstanceState)
{
tv = new TextView(this);
tv.setText("MyTTS: ");
super.onCreate(savedInstanceState);
setContentView(tv);
_tts = new TextToSpeech(this, this);
}
#Override
public void onInit(int status)
{
HashMap<String, String> myHashAlarm = new HashMap<String, String>();
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_NOTIFICATION));
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "test");
if (status == TextToSpeech.SUCCESS)
{
Toast.makeText(this, "Trying to speak...", Toast.LENGTH_SHORT).show();
int result = _tts.setOnUtteranceCompletedListener(this);
tv.append(String.valueOf(result));
_tts.setSpeechRate((float) .5);
_tts.speak("Testing one, two, three", TextToSpeech.QUEUE_ADD, myHashAlarm);
}
else
Toast.makeText(this, "Failed to initialize TTS.", Toast.LENGTH_SHORT).show();
}
#Override
public void onUtteranceCompleted(String utteranceId)
{
Toast.makeText(this, "onUtteranceCompleted", Toast.LENGTH_SHORT).show();
}
#Override
public void onDestroy()
{
super.onDestroy();
_tts.shutdown();
}
}
Call the setOnUtteranceCompletedListener inside the onInit function of the tts object.
If you want to make any changes to the UI on the call of the onUtteranceCompleted function, add the code inside a runOnUIThread method.
And do remember to add the Hashmap param value while calling the speak() function
Example :
TextToSpeech tts= new TextToSpeech(context, new OnInitListener() {
#Override
public void onInit(int status) {
mTts.setOnUtteranceCompletedListener(new OnUtteranceCompletedListener() {
#Override
public void onUtteranceCompleted(String utteranceId) {
runOnUiThread(new Runnable() {
#Override
public void run() {
//UI changes
}
});
}
});
}
});
HashMap<String, String> params = new HashMap<String, String>();
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"stringId");
tts.speak("Text to Speak",TextToSpeech.QUEUE_FLUSH, params);
I believe that unless you specify an utterance with an id, like:
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, utteranceid);
your utterance completed method will not be called.
in this case, map is the Hashmap you pass to the engine when you speak.
this will work for you on API Level >=15
import java.util.HashMap;
import java.util.Locale;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.UtteranceProgressListener;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements OnInitListener{
private static final int CHECK_TTS_DATA = 0X123;
protected static final String TAG = MainActivity.class.getSimpleName();
private TextToSpeech textToSpeech;
private Button buttonSayIt;
private EditText editTextTts;
String tts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonSayIt=(Button) findViewById(R.id.buttonSayIt);
editTextTts=(EditText) findViewById(R.id.editTextTts);
buttonSayIt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tts=editTextTts.getText().toString();
Log.d(TAG, tts);
speach(tts,"you_utterance_id");
}
});
//check for TTs data
Intent checkTtsDataIntent=new Intent();
checkTtsDataIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTtsDataIntent, CHECK_TTS_DATA);
}
protected void speach(String tts,String utteranceId) {
HashMap<String, String> params = new HashMap<String, String>();
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,utteranceId);
textToSpeech.speak(tts,TextToSpeech.QUEUE_FLUSH,params);
}
#Override
public void onInit(int status) {
if(status==TextToSpeech.SUCCESS){
if(textToSpeech.isLanguageAvailable(Locale.US)==TextToSpeech.LANG_AVAILABLE){
textToSpeech.setLanguage(Locale.US);
}
}else if(status==TextToSpeech.ERROR){
Toast.makeText(this, "Sorry Text To Speach faild", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==CHECK_TTS_DATA){
if(resultCode==TextToSpeech.Engine.CHECK_VOICE_DATA_PASS){
textToSpeech=new TextToSpeech(this, this);
textToSpeech.setOnUtteranceProgressListener(utteranceProgressListener);
}else{
Intent installTtsIntent=new Intent();
installTtsIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installTtsIntent);
}
}
}
UtteranceProgressListener utteranceProgressListener=new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
Log.d(TAG, "onStart ( utteranceId :"+utteranceId+" ) ");
}
#Override
public void onError(String utteranceId) {
Log.d(TAG, "onError ( utteranceId :"+utteranceId+" ) ");
}
#Override
public void onDone(String utteranceId) {
Log.d(TAG, "onDone ( utteranceId :"+utteranceId+" ) ");
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
in case anybody is still finding it difficult
Code Snippet
textToSpeech=new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status==TextToSpeech.SUCCESS){
int result=textToSpeech.setLanguage(Locale.ENGLISH);
if (result==TextToSpeech.LANG_MISSING_DATA||result==TextToSpeech.LANG_NOT_SUPPORTED){
Log.i("TextToSpeech","Language Not Supported");
}
textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
Log.i("TextToSpeech","On Start");
}
#Override
public void onDone(String utteranceId) {
Log.i("TextToSpeech","On Done");
}
#Override
public void onError(String utteranceId) {
Log.i("TextToSpeech","On Error");
}
});
}else {
Log.i("TextToSpeech","Initialization Failed");
}
}
});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
textToSpeech.speak(text,TextToSpeech.QUEUE_FLUSH,null,TextToSpeech.ACTION_TTS_QUEUE_PROCESSING_COMPLETED);
}