Issue : speak failed:not bound to tts engine
I am implementing textToSpeech functionality. I am getting the exception as speak failed: not bound to tts engine. I am implementing the async task with it. the async task will be reading the mail. And i want to convert the mail body to speech.
package com.example.trynot;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.util.Locale;
import com.example.trynot.MainActivity.ReadMailSample;
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 Notify extends Activity implements TextToSpeech.OnInitListener {
/** Called when the activity is first created. */
public TextToSpeech tts = new TextToSpeech(MainActivity.c, Notify.this);
public Notify()
{
System.out.println("Inside Constructor");
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) {
System.out.println("inside INIT");
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
tts.speak(MainActivity.ReadMailSample.command, TextToSpeech.QUEUE_FLUSH, null);
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!");
}
}
private void speakOut() {
System.out.println("inside SPeak out");
tts.speak(MainActivity.ReadMailSample.command, TextToSpeech.QUEUE_FLUSH, null);
}
}
You should move instatiation of tts engine instance to onCreate, this line:
public TextToSpeech tts = new TextToSpeech(MainActivity.c, Notify.this);
change to:
public TextToSpeech tts;
and add inside your onCreate:
tts = new TextToSpeech(MainActivity.c, Notify.this);
And - whats most important - do not use constructor in Activity derived classes:
public Notify()
{
System.out.println("Inside Constructor");
speakOut();
}
should be your onCreate:
#Override
protected void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//speakOut(); // here tts is not yet initialized, call it in onInit on success
//tts = new TextToSpeech(MainActivity.c, Notify.this); // whats MainActivity.c?
tts = new TextToSpeech(this, this);
}
your google text to speech engine may be disable... once check it on your setting
if it is disable it also shows the same error
Related
I'm trying to write a application that allows me to send messages from my android phone to the console on my PC. I already have code to use sockets to send messages from one PC to another. Right now I am trying to implement the Wifi-Direct on the android phone by following this tutorial:
https://developer.android.com/guide/topics/connectivity/wifip2p.html#creating-app
I have 2 java files:
MainActivity.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.net.wifi.p2p.WifiP2pManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity{
WifiP2pManager mManager;
WifiP2pManager.Channel mChannel;
BroadcastReceiver mReceiver;
IntentFilter mIntentFilter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Log.d("Peers Discovered", "SUCCEEDED");
}
#Override
public void onFailure(int reasonCode) {
Log.d("Peers Discovered", "FAILURE");
}
});
}
/* register the broadcast receiver with the intent values to be matched */
#Override
protected void onResume(){
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
}
/* unregister the broadcast receiver */
#Override
protected void onPause(){
super.onPause();
unregisterReceiver(mReceiver);
}
}
WifiDirectBroadcastReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager;
import android.util.Log;
import android.widget.Toast;
/**
* A BroadcastReceiver that notifies of important Wi-Fi p2p events.
*/
class WiFiDirectBroadcastReceiver extends BroadcastReceiver {
private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private MainActivity mActivity;
public WiFiDirectBroadcastReceiver(WifiP2pManager manager, WifiP2pManager.Channel channel, MainActivity activity) {
super();
this.mManager = manager;
this.mChannel = channel;
this.mActivity = activity;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
WifiP2pManager.PeerListListener myPeerListListener = new WifiP2pManager.PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList wifiP2pDeviceList) {
for (WifiP2pDevice d: wifiP2pDeviceList.getDeviceList()){
Log.d("WIFIP2PDEVICE", "Device d's address: " + d.deviceAddress);
if (d.deviceAddress==""){
//obtain a peer from the WifiP2pDeviceList
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = d.deviceAddress;
mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
//success logic
}
#Override
public void onFailure(int reason) {
//failure logic
}
});
}
}
}
};
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
// Check to see if Wi-Fi is enabled and notify appropriate activity
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
// Wifi P2P is enabled
Toast.makeText(context, "Wi-Fi Direct is enabled", Toast.LENGTH_SHORT).show();
} else {
// Wi-Fi P2P is not enabled
Toast.makeText(context,"Wifi is disabled, please enable to continue", Toast.LENGTH_SHORT);
}
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
// Call WifiP2pManager.requestPeers() to get a list of current peers
// request available peers from the wifi p2p manager. This is an
// asynchronous call and the calling activity is notified with a
// callback on PeerListListener.onPeersAvailable()
if (mManager != null) {
mManager.requestPeers(mChannel, myPeerListListener);
mManager.onPeersAvailable(myPeerListListener); //ERROR HAPPENS HERE
}
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
// Respond to new connection or disconnections
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
// Respond to this device's wifi state changing
}
}
}
The issue I currently have is that I am getting the error:
Cannot resolve method 'onPeersAvailable(android.net.wifi.p2p.WifiP2pManager.PeerListListener)
Why doesn't my code recognise the implementation of onPeersAvailable(...)?
You are trying to call onPeersAvailable(myPeerListListener) directly. That is not how it works (and if you look back into the tutorial you followed, you'll see they are not doing it either). All you need to do is:
register the listener callback with the WifiP2pManager
the manager will then call your listener whenever it is ready (asynchronously)
Remove the offending line, and things should be fine.
This is my code for getting BeaconFence.It's take too much time and not provide accurate information i fetch two fence lost and found
//BeaconFenceActivity.java
import android.Manifest;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.azilen.awarenessapidemo.R;
import com.google.android.gms.awareness.Awareness;
import com.google.android.gms.awareness.fence.AwarenessFence;
import com.google.android.gms.awareness.fence.BeaconFence;
import com.google.android.gms.awareness.fence.FenceState;
import com.google.android.gms.awareness.fence.FenceUpdateRequest;
import com.google.android.gms.awareness.state.BeaconState;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.ResultCallbacks;
import com.google.android.gms.common.api.Status;
import java.util.Arrays;
import java.util.List;
public class BeaconFenceActivity extends AppCompatActivity {
private GoogleApiClient mGoogleApiClient;
private static final int PERMISSION_REQUEST_ACCESS_FINE_LOCATION = 940;
private TextView txtBeacon;
private static final String BEACON_FENCE_KEY = "BEACON_FENCE_KEY";
private static final int BEACON_ZONE_IN = 2;
private static final int BEACON_ZONE_OUT = 1;
private PendingIntent mPendingIntent;
private BeaconFenceReceiver mBeaconFenceReceiver;
private ProgressDialog mProgress;
//Replace this with app's Google project name
private static final List<BeaconState.TypeFilter> BEACON_TYPE_FILTERS = Arrays.asList
(BeaconState.TypeFilter.with("awarenessapidemo-158205", "beacondemo"));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_beacon_fence);
mProgress = new ProgressDialog(BeaconFenceActivity.this);
mProgress.setTitle("Geting Near Beacon");
mProgress.setMessage("Please wait..");
txtBeacon = (TextView) findViewById(R.id.txt_fence_beacon);
mGoogleApiClient = new GoogleApiClient.Builder(BeaconFenceActivity.this).addApi(Awareness.API).build();
mGoogleApiClient.connect();
mBeaconFenceReceiver = new BeaconFenceReceiver();
Intent intent = new Intent(BeaconFenceReceiver.BEACON_FENCE_RECEIVER_ACTION);
mPendingIntent = PendingIntent.getBroadcast(BeaconFenceActivity.this, 1, intent, 0);
}
#Override
protected void onStart() {
super.onStart();
getBeaconDetails();
registerReceiver(mBeaconFenceReceiver, new IntentFilter(BeaconFenceReceiver.BEACON_FENCE_RECEIVER_ACTION));
}
#Override
protected void onStop() {
super.onStop();
unregisterFences();
unregisterReceiver(mBeaconFenceReceiver);
}
private void getBeaconDetails() {
mProgress.show();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSION_REQUEST_ACCESS_FINE_LOCATION);
mProgress.hide();
} else {
AwarenessFence beaconFoundFence = BeaconFence.found(BEACON_TYPE_FILTERS);
AwarenessFence lostFence = BeaconFence.lost(BEACON_TYPE_FILTERS);
AwarenessFence orFence = AwarenessFence.or(lostFence, beaconFoundFence);
Awareness.FenceApi.updateFences(mGoogleApiClient,
new FenceUpdateRequest.Builder()
.addFence(BEACON_FENCE_KEY, orFence, mPendingIntent)
/* .addFence(BEACON_FENCE_KEY, beaconFoundFence, mPendingIntent)
.addFence(BEACON_FENCE_KEY, lostFence, mPendingIntent)
*/
.build()).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
if (status.isSuccess()) {
Toast.makeText(BeaconFenceActivity.this, "Fence Registered", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(BeaconFenceActivity.this, "Fence Not Registered", Toast.LENGTH_SHORT).show();
}
}
});
mProgress.hide();
}
}
private void unregisterFences() {
Awareness.FenceApi.updateFences(
mGoogleApiClient,
new FenceUpdateRequest.Builder()
.removeFence(BEACON_FENCE_KEY)
.build()).setResultCallback(new ResultCallbacks<Status>() {
#Override
public void onSuccess(#NonNull Status status) {
Toast.makeText(BeaconFenceActivity.this, "Fence Removed", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(#NonNull Status status) {
Toast.makeText(BeaconFenceActivity.this, "Fence Not Removed", Toast.LENGTH_SHORT).show();
}
});
}
public void checkRestart(View view) {
getBeaconDetails();
registerReceiver(mBeaconFenceReceiver, new IntentFilter(BeaconFenceReceiver.BEACON_FENCE_RECEIVER_ACTION));
}
public class BeaconFenceReceiver extends BroadcastReceiver {
public static final String BEACON_FENCE_RECEIVER_ACTION = "com.azilen.awarenessapidemo.activities.fence.BeaconFenceReceiver.BEACON_FENCE_RECEIVER_ACTION";
#Override
public void onReceive(Context context, Intent intent) {
Log.e("Recived", "Received a Beacon Fence Broadcast");
FenceState fenceState = FenceState.extract(intent);
Log.e("FenceState Status:-", String.valueOf(fenceState.getFenceKey()));
if (TextUtils.equals(fenceState.getFenceKey(), BEACON_FENCE_KEY)) {
Log.e("FenceState:-", String.valueOf(fenceState.getCurrentState()));
switch (fenceState.getCurrentState()) {
case FenceState.TRUE: {
setBeaconState(BEACON_ZONE_IN);
Toast.makeText(BeaconFenceActivity.this, "You've entered the beacon zone!", Toast.LENGTH_SHORT).show();
Log.e("Beacon", "In Range");
break;
}
case FenceState.FALSE: {
setBeaconState(BEACON_ZONE_OUT);
Log.e("Beacon", "Out of Range");
Toast.makeText(BeaconFenceActivity.this, "You've Out of beacon Range!", Toast.LENGTH_SHORT).show();
break;
}
case FenceState.UNKNOWN: {
setBeaconState(FenceState.UNKNOWN);
Log.e("Beacon", "UNKNOWN");
Toast.makeText(BeaconFenceActivity.this, "Oops, Beacon status is unknown!", Toast.LENGTH_SHORT).show();
break;
}
}
}
}
}
private void setBeaconState(int beaconState) {
if (beaconState == BEACON_ZONE_IN) {
txtBeacon.setText("You've entered the beacon zone!");
} else if (beaconState == BEACON_ZONE_OUT) {
txtBeacon.setText("You're not in the beacon zone..");
} else {
txtBeacon.setText("Oops, Beacon status is unknown!");
}
}
}
I Hope you can understand my question.
Thank you.
I can't tell you why it is taking to much time.
But in case of the accuracy you have to keep in mind,
that your position to the beacons is calculated from
the signal/signalstrength that beacons send and like every signal in
the microwave spectrum it gets reflected, blocked etc.
The environment in which you use your beacons could be
far from ideal to get the accuracy you want with the information
provided by the beacons.
I'm doing a project with ibeacon using Eclipse to build an APP , I import some codes from Android beacon library for detecting UUID , with no error in the codes , I try to open the apk on HTC device, but failed to open the App .
Here is my code. Any help or suggest is appreciated.
package com.example.goooooood;
import org.altbeacon.beacon.BeaconConsumer;
import org.altbeacon.beacon.BeaconManager;
import org.altbeacon.beacon.BeaconParser;
import org.altbeacon.beacon.MonitorNotifier;
import org.altbeacon.beacon.Region;
import android.app.Activity;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
public abstract class MainActivity extends Activity implements BeaconConsumer {
protected static final String TAG = "MonitoringActivity";
private BeaconManager beaconManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
beaconManager.getBeaconParsers().add(new BeaconParser().
setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));
beaconManager = BeaconManager.getInstanceForApplication(this);
// To detect proprietary beacons, you must add a line like below corresponding to your beacon
// type. Do a web search for "setBeaconLayout" to get the proper expression.
// beaconManager.getBeaconParsers().add(new BeaconParser().
// setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));
beaconManager.bind(this);
}
#Override
protected void onDestroy() {
super.onDestroy();
beaconManager.unbind(this);
}
#Override
public void onBeaconServiceConnect() {
beaconManager.setMonitorNotifier(new MonitorNotifier() {
#Override
public void didEnterRegion(Region region) {
Log.i(TAG, "I just saw an beacon for the first time!");
}
#Override
public void didExitRegion(Region region) {
Log.i(TAG, "I no longer see an beacon");
}
#Override
public void didDetermineStateForRegion(int state, Region region) {
Log.i(TAG, "I have just switched from seeing/not seeing beacons: "+state);
}
});
try {
beaconManager.startMonitoringBeaconsInRegion(new Region("myMonitoringUniqueId", null, null, null));
} catch (RemoteException e) { }
}}
Here is the logcat.
logat part 1 of the code
logcat part 2 of the code
I have a text to speech function in my android app that works to an onClick event, there is an issue when the activity starts, the text to speech starts without clicking the button, is there a line of code I can put in to stop this happening, thank you.
package com.androidhive.texttospeech;
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.TextView;
public class AndroidTextToSpeechActivity extends Activity implements
TextToSpeech.OnInitListener {
/** Called when the activity is first created. */
private TextToSpeech tts;
private Button button1;
private TextView txtText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tts = new TextToSpeech(this, this);
button1 = (Button) findViewById(R.id.button1);
txtText = (TextView) findViewById(R.id.txtText);
// button on click event
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
speakOut();
}
});
}
#Override
public void onDestroy() {
// Don't forget to shutdown!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
// tts.setPitch(5); // set pitch level
// tts.setSpeechRate(2); // set speech speed rate
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
button1.setEnabled(true);
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed");
}
}
private void speakOut() {
String text = txtText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
The reason why this happens is because you invoke speakOut# In the onInit() method, remove speakOut():
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
button1.setEnabled(true);
// speakOut();
}
I saw these codes in onInit(), which will be called after the TextToSpeech is instantiated and initialized successfully. See the speakOut() here? That's what causes your problem.
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
button1.setEnabled(true);
speakOut();
}
I am running a Text To Speech code, but now my new requirement is to provide "Pause" facility. I read number of SO questions and found I have to write data into a file and have to use media player class to play the file. Below is my code.
public void speak(String text)
{
HashMap<String,String> map = new HashMap<String,String>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, text);
tts.synthesizeToFile(text, map,"ttsFile.wav");
//tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
Here I have 2 questions.
I do not want to open media player to play the file, file should be played inside the app with the media player controls (just like how you can set videoView.setMediaController(); to VideoView). How can I do this? any example please?
Is there any "Cache" place to save the above file so it will be deleted once the app is closed?
You can do something like this:
Create a video player in your application :
VideoPlayerActivity.java:
package com.camera.manual;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
public class VideoPlayerActivity extends Activity {
private boolean mResumed = false;
private boolean mFocused = false;
private boolean mControlResumed = false;
private VideoView videoView = null;
private int stopPosition = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.Theme_TransparentVideo);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
setContentView(R.layout.video_view);
videoView =(VideoView)findViewById(R.id.myvideoview);
MediaController mediaController= new MediaController(this);
mediaController.setAnchorView(videoView);
Uri uri=Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.slow);
videoView.setMediaController(mediaController);
videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.start();
}
#Override
public void onPause() {
super.onPause();
mResumed = false;
if (mControlResumed) {
if (null != videoView)
videoView.pause();
stopPosition = videoView.getCurrentPosition();
mControlResumed = false;
}
}
#Override
public void onResume() {
super.onResume();
mResumed = true;
if (mFocused && mResumed && !mControlResumed) {
if(null != videoView) {
//videoView.resume();
videoView.seekTo(stopPosition);
videoView.start();
}
mControlResumed = true;
}
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
mFocused = hasFocus;
if (mFocused && mResumed && !mControlResumed) {
if (null != videoView) {
//videoView.resume();
videoView.seekTo(stopPosition);
videoView.start();
}
mControlResumed = true;
}
}
}
You can call it like this:
Intent intent = new Intent();
intent.setClass(mContext, VideoPlayerActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mContext.startActivity(intent);