Text to speech for multiple activities - java

I'm developing an application for workout with multiple activities that has text to speech for instructions.
My problem is that the text to speech takes too long to initialize even though i have it in a helper class and the instruction don't play when the activity starts, i thought maybe i should make a text to speech service, but i don't know how and i didn't find any tutorials.
private TextToSpeech mTts = null;
private boolean isLoaded = false;
public void init(Context context) {
try {
mTts = new TextToSpeech(context, onInitListener);
} catch (Exception e) {
e.printStackTrace();
}
}
private final TextToSpeech.OnInitListener onInitListener = new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
mTts.setLanguage(Locale.getDefault());
isLoaded = true;
}
}
};
public void initQueue(String text) {
if (isLoaded) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mTts.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
} else {
mTts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
else
Log.e("error", "TTS Not Initialized");
}
How i can create a speech service and make it speak instructions from an activity?

Related

Need to add Share button in this library android frames

Currently developing an android app using below library
[enter link description here][1]https://github.com/jahirfiquitiva/Frames/blob/master/library/src/main/java/jahirfiquitiva/libs/frames/activities/base/BaseWallpaperViewerActivity.java
[1]want to add share button in this code can any tell me logic using this code how can i do that.
Want to replace icon info button with share button
private void saveWallpaperAction(final Context context) {
if (downloadDialog != null) {
downloadDialog.dismiss();
}
if (callback != null) {
callback.onSaveAction();
}
final boolean[] enteredDownloadTask = {false};
downloadDialog = new MaterialDialog.Builder(context)
.content(R.string.downloading_wallpaper)
.progress(true, 0)
.cancelable(false)
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction
which) {
if (downloadDialog != null) {
downloadDialog.dismiss();
}
}
})
.show();
Glide.with(context)
.load(item.getURL())
.asBitmap()
.dontAnimate()
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap>
glideAnimation) {
if (resource != null && downloadDialog.isShowing()) {
enteredDownloadTask[0] = true;
try {
saveWallpaper(((Activity) context), item.getName(),
downloadDialog, resource);
} catch (Exception e) {
// Do nothing
}
}
}
});
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
runOnUIThread(context, new Runnable() {
#Override
public void run() {
if (!enteredDownloadTask[0]) {
String newContent = context.getString(R.string.downloading_wallpaper)
+ "\n"
+ context.getString(R.string.download_takes_longer);
downloadDialog.setContent(newContent);
downloadDialog.setActionButton(DialogAction.POSITIVE, android.R
.string.cancel);
}
}
});
}
}, 10000);
}

Android Studio - Sending a Bluetooth PIN automatically

I am looking at the following code by Lorensius W. L. T
I have seen other posts about sending a PIN automatically (e.g. 1234) to the device when it pairs so that there is no user prompt. I can't figure it out how to add their code fragments to get it to work.
How is the following code modified to achieve this?
/**
* Device list.
*
* #author Lorensius W. L. T <lorenz#londatiga.net>
*
*/
public class DeviceListActivity extends Activity {
private ListView mListView;
private DeviceListAdapter mAdapter;
private ArrayList<BluetoothDevice> mDeviceList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_paired_devices);
mDeviceList = getIntent().getExtras().getParcelableArrayList("device.list");
mListView = (ListView) findViewById(R.id.lv_paired);
mAdapter = new DeviceListAdapter(this);
mAdapter.setData(mDeviceList);
mAdapter.setListener(new DeviceListAdapter.OnPairButtonClickListener() {
#Override
public void onPairButtonClick(int position) {
BluetoothDevice device = mDeviceList.get(position);
if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
unpairDevice(device);
} else {
showToast("Pairing...");
pairDevice(device);
}
}
});
mListView.setAdapter(mAdapter);
registerReceiver(mPairReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
}
#Override
public void onDestroy() {
unregisterReceiver(mPairReceiver);
super.onDestroy();
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private void pairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private void unpairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("removeBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
showToast("Paired");
} else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
showToast("Unpaired");
}
mAdapter.notifyDataSetChanged();
}
}
};
}

Text to Speak for Android not working

I'm trying to implement Text to Speech onto my app. I've followed the following guide but my app keeps crashing after the splash screen.
link: http://www.androidhive.info/2012/01/android-text-to-speech-tutorial/
Main Activity Class I have this
String alertMessage = AppResources.ALERT_MSG;
SpeakDemo speak = new SpeakDemo(null, alertMessage);
speak.speakOut();
If I remove the speak.speakOut(); line the app works fine.
App Resources is another class with the following message box
public static String ALERT_MSG = "Welcome!";
The SpeakDemo Class is:
import java.util.Locale;
import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.util.Log;
public class SpeakDemo implements TextToSpeech.OnInitListener{
private TextToSpeech tts;
private Context context;
private String message;
public SpeakDemo(Context context, String message){
this.context = context;
this.message = message;
}
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
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 {
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
public void speakOut(){
tts.speak(message, TextToSpeech.QUEUE_FLUSH, null);
}
}
Any Ideas?
Thanks
You need to instantiate the TextToSpeech.
Change
public SpeakDemo(Context context, String message){
this.context = context;
this.message = message;
tts = new TextToSpeech(context, this);
}
//FOR TEXT TO SPEECH
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
String msg=text.getText().toString();
if(status==TextToSpeech.SUCCESS)
{
tts.setLanguage(Locale.US);
tts.speak(msg,TextToSpeech.QUEUE_FLUSH,null);
}
else
Log.e("TTS","INITILIZATION FAILED");
}
public void onDestroy()
{
if (tts!=null)
{
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
Xml:
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Speak"
android:onClick="TTS"/>
Mainactivity:
TextToSpeech textToSpeech;
textToSpeech=new TextToSpeech(TTSpeech.this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status==TextToSpeech.SUCCESS)
{
result=textToSpeech.setLanguage(Locale.ENGLISH);
}
else
{
Toast.makeText(TTSpeech.this, "speech not work", Toast.LENGTH_SHORT).show();
}
}
});
}
public void TTS(View view) {
switch (view.getId())
{
case R.id.button:
if(result== TextToSpeech.LANG_NOT_SUPPORTED || result==TextToSpeech.LANG_MISSING_DATA)
{
Toast.makeText(TTSpeech.this, "speech not nt work", Toast.LENGTH_SHORT).show();
}
else
{
text=ed.getText().toString();
textToSpeech.speak(text,TextToSpeech.QUEUE_FLUSH,null);
}
break;
}
if you get problem you can comment me.

ringtone manager is not stop ringtone android

i have two class incomingCallRing.java and IncomingCallSlider.java
one class show the UI and 2nd class define the functions.
The problem i m facing is when i click on reject call button the music of incoming call wont stop.Here is the code of both classes.
incomingCallSlider.java
private void RejectCall()
{
m_objBtnRejectCall = (Button) m_objActiveActivity.findViewById(R.id.RejectCallButton);
m_objBtnRejectCall.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0)
{
//Log.e("Reject Call", m_sIncomingCallId);
VaxPhone.m_objVaxVoIP.RejectCall(m_sIncomingCallId);
HideSlider();
if(IncommingCall != null)
IncommingCall.cancel(0);
} }); }
IncomingCallRing.java
public static IncommingCallRing m_objIncommingCallRing;
Ringtone m_objRingtone;
Activity m_objActiveActivity;
public IncommingCallRing()
{
m_objIncommingCallRing = this;
}
public void SetActiveActivity(Activity ReferenceActivity)
{
m_objActiveActivity = ReferenceActivity;
}
private void StartRingtone()
{
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
m_objRingtone = RingtoneManager.getRingtone(m_objActiveActivity.getApplicationContext(), notification);
m_objRingtone.play();
}
private void StopRingtone()
{
if(m_objRingtone == null)
return;
if(m_objRingtone.isPlaying())
m_objRingtone.stop();
}

Getting text to speech to play on start of an activity without button

I am using text to speech in my app and I have been able to get it to work on all of my buttons fine. However, when I try to use the text to speech in my splash activity it crashes the app. It is a nullpointer exception so I know I am just coding it incorrectly. To clarify what I want it to do. I want it to talk during the splash activity. When the splash activity sleeps I want it to talk again to tell the user it is done loading.I have included the java for my splash activity.
public class mainj extends Activity implements OnInitListener {
private TextToSpeech myTTS;
// status check code
private int MY_DATA_CHECK_CODE = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loadscreen);
Thread logoTimer = new Thread() {
public void run() {
try {
try {
sleep(5000);
speakWords("loading");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent menuIntent = new Intent("android.intent.action.MENU");
startActivity(menuIntent);
Intent checkTTSIntent = new Intent();
checkTTSIntent
.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
}
finally {
finish();
}
}
};
logoTimer.start();
}
// speak the user text
private void speakWords(String speech) {
// speak straight away
myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
}
// act on result of TTS data check
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// the user has the necessary data - create the TTS
myTTS = new TextToSpeech(this, this);
} else {
// no data - install it now
Intent installTTSIntent = new Intent();
installTTSIntent
.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installTTSIntent);
}
}
}
// setup TTS
public void onInit(int initStatus) {
// check for successful instantiation
if (initStatus == TextToSpeech.SUCCESS) {
if (myTTS.isLanguageAvailable(Locale.US) == TextToSpeech.LANG_AVAILABLE)
myTTS.setLanguage(Locale.US);
} else if (initStatus == TextToSpeech.ERROR) {
Toast.makeText(this, "Sorry! Text To Speech failed...",
Toast.LENGTH_LONG).show();
}
}
}
Right at the beginning of your thread after you sleep you are calling speakWords. that calls myTTS.speak. At that point looking at your code, the myTTS does not seem to be initialized and is null so will crash with an NPE.
This code should prevent the NPE, but if the initialization of the TTS engine takes too long, then you won't get it to say Loading. Also, I am guessing the 5 second (which is a really long time btw) sleep is to allow for it to get initialized?
public class mainj extends Activity implements OnInitListener {
private TextToSpeech myTTS;
// status check code
private int MY_DATA_CHECK_CODE = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loadscreen);
Intent checkTTSIntent = new Intent();
checkTTSIntent
.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
Thread logoTimer = new Thread() {
public void run() {
try {
try {
sleep(5000);
speakWords("loading");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent menuIntent = new Intent("android.intent.action.MENU");
startActivity(menuIntent);
}
finally {
finish();
}
}
};
logoTimer.start();
}
// speak the user text
private void speakWords(String speech) {
// speak straight away
if(myTTS != null)
{
myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
}
}
// act on result of TTS data check
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// the user has the necessary data - create the TTS
myTTS = new TextToSpeech(this, this);
} else {
// no data - install it now
Intent installTTSIntent = new Intent();
installTTSIntent
.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installTTSIntent);
}
}
}
// setup TTS
public void onInit(int initStatus) {
// check for successful instantiation
if (initStatus == TextToSpeech.SUCCESS) {
if (myTTS.isLanguageAvailable(Locale.US) == TextToSpeech.LANG_AVAILABLE)
myTTS.setLanguage(Locale.US);
} else if (initStatus == TextToSpeech.ERROR) {
Toast.makeText(this, "Sorry! Text To Speech failed...",
Toast.LENGTH_LONG).show();
}
}
}
You would be better calling you're little loading snippet after the TTS engine has been loaded, so you could put the speak in OnActivityResult().
In your code you can't actually tell whether or not myTTS has been initialised when you call speak. Try it this way:
Intent menuIntent = new Intent("android.intent.action.MENU");
startActivity(menuIntent);
Intent checkTTSIntent = new Intent();
checkTTSIntent
.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
try {
sleep(5000);
speakWords("loading");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
There are two things wrong with your approach.
First, your app needs to wait for init() before it tries to speak.
Second, your app needs to handle when the speech libraries are not available.
Use this class or this one to help with the TextToSpeech initialization. It's actually kind of complex and using TextToSpeech.Engine.ACTION_CHECK_TTS_DATA is actually NOT the best way to do it.

Categories