Android java : Text-to-Speech no sound - java

Hi I'm new in Android Development.
I have doing a lot of research .
Everything go rights however there is no any output sound from the text I entered.
Did I miss out any important part ?
The following bellow is the coding :
public class SpeechTextActivity extends Activity implements OnInitListener {
private int MY_DATA_CHECK_CODE = 0;
private TextToSpeech tts;
private EditText inputText;
private Button speakButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_speech);
inputText = (EditText) findViewById(R.id.edit_speechText);
speakButton = (Button) findViewById(R.id.btn_speechOut);
speakButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String text = inputText.getText().toString();
if (text!=null && text.length()>0) {
Toast.makeText(SpeechTextActivity.this, "Saying: " + text, Toast.LENGTH_LONG).show();
tts.speak(text, TextToSpeech.QUEUE_ADD, null);
}
}
});
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// success, create the TTS instance
tts = new TextToSpeech(this, this);
}
else {
// missing data, install it
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Toast.makeText(SpeechTextActivity.this,
"Text-To-Speech engine is initialized", Toast.LENGTH_LONG).show();
}
else if (status == TextToSpeech.ERROR) {
Toast.makeText(SpeechTextActivity.this,
"Error occurred while initializing Text-To-Speech engine", Toast.LENGTH_LONG).show();
}
}
}
Just now I test in my tablet it work! But in my phone not workable =(

Change the implements OnInitListener to TextToSpeech.OnInitListener.

Try to unplug the USB cable from your phone before testing. TTS is recognized to encountered some issues in debug mode.

Related

Can't get Android text to speech to read on start of an activity without a button using a text or JSon file

Here is what I am trying to do I would like to have TTS ask a question on the activity start to begin a dialog. I have found tons of articles on how to do something similar with user input in EditText and a button but I want to have TTS read from a text file preferably a Json file i'm not sure what I am missing, bare in mind I am not a programmer I pieced this together from a bunch of different articles.
TextToSpeech myTTS;
InputStream stream;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_aibutton);
myTTS=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitActivity() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
myTTS.setLanguage(Locale.US);
}
}
});
stream.setOnActivityListener(new Stream.OnActivityListener() {
#Override
public void OnInitActivity(View v) {
String toSpeak = stream.getText().toString();
InputStream stream = this.getResources().openRawResource(R.raw.stringquestions);
Toast.makeText(getApplicationContext(), toSpeak,Toast.LENGTH_SHORT).show();
myTTS.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}
});
}
public void onPause(){
if(myTTS !=null){
myTTS.stop();
myTTS.shutdown();
}
super.onPause();
}
// act on result of TTS data check
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, 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();
}
}
Move the tts speak code inside onInit code.
The tts speak method works only after onInit has been called.
myTTS=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitActivity() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
myTTS.setLanguage(Locale.US);
stream.setOnActivityListener(new Stream.OnActivityListener() {
#Override
public void OnInitActivity(View v) {
String toSpeak = stream.getText().toString();
InputStream stream =
this.getResources().openRawResource(R.raw.stringquestions);
Toast.makeText(getApplicationContext(), toSpeak,Toast.LENGTH_SHORT).show();
myTTS.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}
});
}
}
});

Android Studio : How to keep variables from one java file to another

I am developping an application which convert scanned data (barcode) to GoogleSheet data, and I am trying to transfer the barcode number (from Page2.java) into another java file (ListItem.java)
I saw that a usual way to do it is to create intents. So I did it.
But the toast I put in ListItem.java gives me "null" instead of the scanned number (for example 0123456789012)
Please, can you tell me where am I wrong ? Thank you so much !
1st Code (Page2.java , where I get "scanContent2", the variable I need) :
public class Page2 extends Activity implements OnClickListener {
#SuppressLint("ClickableViewAccessibility")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.page2);
scanBtn2 = (Button) findViewById(R.id.scan_button2);
scanBtn2.setOnClickListener(this);
}
public Button scanBtn2;
public String scanContent2;
#Override
public void onClick(View v) {
if (v.getId() == R.id.scan_button2) {
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
scanContent2 = scanningResult.getContents();
Intent intenta = new Intent(getApplicationContext(),ListItem.class);
intenta.putExtra("theScanContent2", scanContent2);
startActivity(intenta);
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
}
2nd code (ListItem.java, where I get "null" on the toast) :
public class ListItem extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item);
String scanContent2 = getIntent().getStringExtra("theScanContent");
Toast toast = Toast.makeText(getApplicationContext(),
"BarCode number: " + scanContent2, Toast.LENGTH_SHORT);
toast.show();
}
}
In the Listitem.java in the following line,
String scanContent2 = getIntent().getStringExtra("theScanContent");
You are trying to get String with key theScanContent, while you are putting scanContent2 with key theScanContent2 in Page2.java in line
intent.putExtra("theScanContent2", scanContent2);
Make sure the keys are same for the Intent while putting the data in intent and accessing the data from the intent to avoid getting null Results.

Google Play Games interactive sign-in prompt implementation?

I'm working on a mobile game, and I need the users to log in to their Play Games account to use the leaderboard feature. I want the app to prompt for their account when MainActivity is launched. I followed the steps on the Google developers website and it just doesn't work. The screen dims, as if it was about to prompt for log-in, then it shows a message saying there was an error with the sign-in. Here's my code so far; What am I missing to make it work?
public class MainActivity extends AppCompatActivity {
public int score = 0;
Button newRound;
TextView scoreText, highScore;
MediaPlayer sound = new MediaPlayer();
ColorStateList oldColors;
int hiScore = 0;
SharedPreferences preferences;
SharedPreferences.Editor editor;
ImageButton leaderboards;
int RC_SIGN_IN = 9001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
leaderboards = findViewById(R.id.leaderboards);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
enableTooltips();
}
preferences = PreferenceManager.getDefaultSharedPreferences(this);
editor = preferences.edit();
newRound = findViewById(R.id.button_gen);
scoreText = findViewById(R.id.score_tv);
highScore = findViewById(R.id.highScore);
oldColors = scoreText.getTextColors();
int savedScore = preferences.getInt("score", 0);
int savedHiScore = preferences.getInt("hiScore", 0);
scoreText.setText(""+savedScore);
highScore.setText("High score: "+savedHiScore);
score = savedScore;
hiScore = savedHiScore;
if(score >= 1){
changeColor();
}
newRound.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
newRound();
}
});
startSignInIntent();
}
#Override
protected void onStart() {
super.onStart();
}
private void startSignInIntent() {
GoogleSignInClient signInClient = GoogleSignIn.getClient(this,
GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN);
Intent intent = signInClient.getSignInIntent();
startActivityForResult(intent, RC_SIGN_IN);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// The signed in account is stored in the result.
GoogleSignInAccount signedInAccount = result.getSignInAccount();
} else {
String message = result.getStatus().getStatusMessage();
if (message == null || message.isEmpty()) {
message = "Sign in error";
}
new AlertDialog.Builder(this).setMessage(message)
.setNeutralButton(android.R.string.ok, null).show();
}
}
}
I've had the same problems too you're not alone but it works for default sign in for some reason.

How to stop a VpnService that was called with prepare() and startService()?

I't trying to implement a local VpnService to have my app do some tasks, but I'm a little confused as to how to stop it one it started. The VpnService class and client activity are based on this repo:
https://github.com/hexene/LocalVPN
The caller activity is basically this:
public class MainActivity extends AppCompatActivity {
private static final int VPN_REQUEST_CODE = 0x0F;
private boolean waitingForVPNStart;
private BroadcastReceiver vpnStateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (LocalVPNService.BROADCAST_VPN_STATE.equals(intent.getAction()))
if (intent.getBooleanExtra("running", false))
waitingForVPNStart = false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button vpnButton = (Button)findViewById(R.id.vpn);
vpnButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startVPN();
}
});
final Button vpnStopButton = (Button)findViewById(R.id.stopVpnButton);
vpnStopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopVPN();
}
});
waitingForVPNStart = false;
LocalBroadcastManager.getInstance(this).registerReceiver(vpnStateReceiver,
new IntentFilter(LocalVPNService.BROADCAST_VPN_STATE));
}
private void startVPN() {
Intent vpnIntent = VpnService.prepare(this);
if (vpnIntent != null)
startActivityForResult(vpnIntent, VPN_REQUEST_CODE); //Prepare to establish a VPN connection. This method returns null if the VPN application is already prepared or if the user has previously consented to the VPN application. Otherwise, it returns an Intent to a system activity.
else
onActivityResult(VPN_REQUEST_CODE, RESULT_OK, null);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == VPN_REQUEST_CODE && resultCode == RESULT_OK) {
waitingForVPNStart = true;
startService(new Intent(this, LocalVPNService.class));
enableButton(false);
}
}
What confuses me is: how would I call the service's onDestroy() method or something similar if I don't keep an instance if it in my main activity?
I looked at this answer and this and seen implementations of stopService, but I'm not sure how to handle the Intent, because it's not only used to call startService() but also involved in calling VpnService.prepare().
Edit: I tried
stopService(new Intent(this, LocalVPNService.class)); but it doesn't stop it. I tried stopService(vpnIntent); and IT WORKS, but makes my app crash/close.
In your LocalVPNService class create a new broadcast:
private BroadcastReceiver stopBr = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if ("stop_kill".equals(intent.getAction())) {
stopself();
}
}
};
and in the onCreate method add this:
LocalBroadcastManager lbm =
LocalBroadcastManager.getInstance(this);
lbm.registerReceiver(stopBr, new IntentFilter("stop_kill"));
in your activity:
Intent intent = new Intent("stop_kill");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

Android - MediaPlayer (open failed: ENOENT (No such file or directory)

I asked a question earlier play video in new activity
What I want is when (Button) findViewById(R.id.pickVid); is clicked it calls PICK_VIDEO_REQUEST, then when the video is selected the new activity should open and play the video.
The guy that helped me said that I should use this.mPlayer.setDataSource(mStringFilePath); instead of FileInputStream
PROBLEM:
I am getting a error saying setDataSource failed.: status=0x80000000 with a black screen.
MainActivity
public class MainActivity extends AppCompatActivity {
Uri mMediaUri;
String vidFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button pickVid = (Button) findViewById(R.id.pickVid);
//choose the video
pickVid.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent chooseVideo = new Intent(Intent.ACTION_GET_CONTENT);
chooseVideo.setType("video/*");
startActivityForResult(chooseVideo, PICK_VIDEO_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_VIDEO_REQUEST) {
if (resultCode == RESULT_OK) {
mMediaUri = data.getData();
vidFile = mMediaUri.toString();
Intent playVid = new Intent(MainActivity.this, PlayVideoAct.class);
playVid.putExtra("vidFile", vidFile);
startActivity(playVid);
}
}
}
PlayVideoAct
String mStringFilePath;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playvideo);
mStringFilePath = getIntent().getStringExtra("vidFile");
}
public void surfaceCreated(SurfaceHolder holder) {
if (this.mPlayer == null) {
this.mPlayer = new MediaPlayer();
} else {
this.mPlayer.reset();
mPlayer.start();
}
try {
this.mMediaPlayer.setDataSource(mStringFilePath);
this.mPlayer.setDisplay(this.mSurfaceHolder);
this.mPlayer.prepare();
this.mPlayer.start();
this.mPlayer.pause();
Play();
} catch (Exception e) {
LogUtil.e(e, "Error in PlayVideoAct.surfaceCreate(SurfaceHolder)");
}
}
private void Play() {
mMediaPlayer.start();
if (this.mMediaPlayer.isPlaying()) {
this.mMediaPlayer.pause();
return;
}
if (this.isStop) {
this.mMediaPlayer.seekTo(this.leftPosition);
}
this.mImageViewButtonControls.setImageResource(R.drawable.pause);
}
Check video path, if it's correct then check if you have all necessary permissions like:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
If yes, then depending on your Android version you may need to go to Settings -> Apps -> Your application -> Permissions and toggle those permissions manually.

Categories

Resources