Control the volume on TextToSpeech function call - java

Hi guys
I've been looking around but cannot seem to find a suitable answer to integrate into my function. I am basically using the following code currently:
private void sayHello(String timeString) {
textToSpeech.speak(timeString,
TextToSpeech.QUEUE_FLUSH,
null);
}
This code works fine but it's too loud and it can only be controlled by the volume of the device itself. I want to be able to adjust/hardcode/be able to use spinner to control the volume of the TTS but cannot seem to do so accordingly.
Is this functionality available for this library? Is it achievable?
I've also tried to implement the following into my code:
KEY_PARAM_VOLUME
However, I cannot see any examples of this being used and it's showing up with the error to create a function. Any advice?

public class MainActivity extends AppCompatActivity {
int androidAPILevel = android.os.Build.VERSION.SDK_INT;
TextToSpeech tts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int i) {
start();
}
});
}
private void start() {
if (androidAPILevel < 21) {
HashMap<String,String> params = new HashMap<>();
params.put(TextToSpeech.Engine.KEY_PARAM_VOLUME, "0.5"); // change the 0.5 to any value from 0-1 (1 is default)
tts.speak("This is a volume test.", TextToSpeech.QUEUE_FLUSH, params);
} else { // android API level is 21 or higher...
Bundle params = new Bundle();
params.putFloat(TextToSpeech.Engine.KEY_PARAM_VOLUME, 0.5f); // change the 0.5f to any value from 0f-1f (1f is default)
tts.speak("This is a volume test.", TextToSpeech.QUEUE_FLUSH, params, null);
}
}
}

Related

Perform an Action when phone is shaked

I'm using shake-detector-librart to detect whether my phone is being shared or not. It is working fine, gives the exact results as needed in the background as well as while the application is opened. I need to perform any action when the phone is being shaken, but it isn't working for that.
Here's my code:
ShakeOptions options = new ShakeOptions()
.background(true)
.interval(1000)
.shakeCount(2)
.sensibility(3.0f);
this.shakeDetector = new ShakeDetector(options);
shakeDetector.start(this, new ShakeCallback() {
#Override
public void onShake() {
Toast.makeText(getApplicationContext(), "locationDetails", Toast.LENGTH_SHORT).show();
String msg_txt = "THis is a sammple sms";
String phoneNo = "03036018110";
System.out.println("jamoodgreat");
//sendSMS(phoneNo,msg_txt);
Log.d("event", "onShake");//this is not being printed
Toast.makeText(getApplicationContext(), "Jamshaid", Toast.LENGTH_LONG).show();//this toast is not being displayed as well.
}
});
}
I tested the following and it works fine (The Toast gets called/displayed).
public class MainActivity extends AppCompatActivity {
private ShakeDetector shakeDetector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ShakeOptions options = new ShakeOptions()
.background(true)
.interval(1000)
.shakeCount(2)
.sensibility(2.0f);
shakeDetector = new ShakeDetector(options).start(this, new ShakeCallback() {
#Override
public void onShake() {
Toast.makeText(MainActivity.this, "onShake", Toast.LENGTH_SHORT).show();
}
});
}
}
Even though it worked, I had to shake the device vigorously before it was picked up.

How to send event from MainActivity onCreate to React Native?

I'm working on an alarm clock and I can't figure out how to sendEvent to React Native from MainActivity. This is what I managed to do so far:
#Override
protected void onCreate(Bundle savedInstanceState) {
mInitialProps = new Bundle();
final Bundle bundle = mActivity.getIntent().getExtras();
ReactInstanceManager mReactInstanceManager = getReactNativeHost().getReactInstanceManager();
ReactApplicationContext context = (ReactApplicationContext) mReactInstanceManager.getCurrentReactContext();
if (context == null) {
mReactInstanceManager.addReactInstanceEventListener(new ReactInstanceManager.ReactInstanceEventListener() {
public void onReactContextInitialized(ReactContext context) {
if (bundle != null && bundle.containsKey("sendAlarm")) {
if (bundle.getString("sendAlarm").equals("sendAlarmOn")) {
LauncherModule.startAlarm(mActivity); // works
LauncherModule.sendAlarmEvent(); // doesn't work. Should run after alarm manager starts app which previously had been killed
}
}
}
});
} else {
if (bundle != null && bundle.containsKey("sendAlarm")) {
if (bundle.getString("sendAlarm").equals("sendAlarmOn")) {
LauncherModule.startAlarm(mActivity); // works
LauncherModule.sendAlarmEvent(); // works and sends event only when app was left open
}
}
}
super.onCreate(savedInstanceState);
}
The code works only If app is left open and alarm manager restarts app itself. If I close the app and alarm manager starts it then it seems that only startAlarm function (it has sound effect) is beeing triggered..
No matter what I do whether I put sendEvent function inside Mainactivity or elsewhere (e.g. external module) it simply won't send event if I close the app. I also tried getReactInstanceManager().getCurrentReactContext() combined with while from this question Send data from Android activity to React Native to no avail.
Also tried to create bolean beeing set to true onCreate and then send event onStart or onRestart. Also to no avail.
Any suggestions?
EDIT: Here is how sendEvent function looks like:
public final void sendEvent(String eventName, boolean isAlarmOn) {
getReactInstanceManager().getCurrentReactContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, isAlarmOn);
}
SOLUTION
Well I think that the answer is not to use sendEvent method onCreate because (I might be wrong) listener seems to be initialized after the event had been sent. So nothing is going to listen to this event.
It seems to work pretty well inside onStart, onRestart, onPause though.
What can we do? React Native provides ReactActivityDelegate with initial props. And it does the job!
ReactActivityDelegate in MainActivity should look as below:
public class ActivityDelegate extends ReactActivityDelegate {
private Bundle mInitialProps = null;
private final #Nullable Activity mActivity;
public ActivityDelegate(Activity activity, String mainComponentName) {
super(activity, mainComponentName);
this.mActivity = activity;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
mInitialProps = new Bundle();
final Bundle bundle = mActivity.getIntent().getExtras();
if (bundle != null && bundle.containsKey("sendAlarm")) {
if (bundle.getString("sendAlarm").equals("sendAlarmOn")) {
mInitialProps.putBoolean("alarmOn", true);
}
}
super.onCreate(savedInstanceState);
}
#Override
protected Bundle getLaunchOptions() {
return mInitialProps;
}
};
#Override
protected ReactActivityDelegate createReactActivityDelegate() {
return new ActivityDelegate(this, getMainComponentName());
}
Then in your main app component (usually index.android.js) call your propTypes and use them to run your code:
static propTypes = {
alarmOn: PropTypes.boolean
}
componentDidMount() {
if (this.props.alarmOn === true) {
// your code
}
}
Voila!
You can find full example here: https://github.com/vasyl91/react-native-android-alarms

How initialize correctly static variable in PreferenceActivity

I have Preference class extent PreferenceActivity.
I create public static String quality; in Preference.class i add in onCreate
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref);
quality = "QUALITY_HIGH";//initialize
}
and add in Preference.class this method
public void getQuality() {
if (keyquality.equals("480p")) {
quality = "QUALITY_LOW";
//
}
if (keyquality.equals("720p")) {
//
quality = "QUALITY_720P";
}
if (keyquality.equals("1080p")) {
//
quality = "QUALITY_HIGH";
}
}
in another class i create method to get my variable and set settings
private void getqualityvideo() {
/*if (Prefernce.quality == null) {
preferencecamrecoder = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
} else {*/
if (Prefernce.quality.equals("QUALITY_LOW")) {
preferencecamrecoder = CamcorderProfile.get(CamcorderProfile.QUALITY_LOW);
}
if (Prefernce.quality.equals("QUALITY_720P")) {
preferencecamrecoder = CamcorderProfile.get(CamcorderProfile.QUALITY_720P);
}
if (Prefernce.quality.equals("QUALITY_HIGH")) {
preferencecamrecoder = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
}
// }
}
Problem:
when start application
private void startServes() {
btnStart = (ImageView) findViewById(R.id.StartService);
btnStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
v.startAnimation(mAnimationImage);
Intent intent = new Intent(MainActivity.this, RecorderService.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startService(intent);
changeCamera
.setEnabled(false);
btnStart.setEnabled(false);
setings.setEnabled(false);
moveTaskToBack(false);
}
});
}
in another class in method
getqualityvideo() error NullPointerException
error in this first line
if (Prefernce.quality.equals("QUALITY_LOW"))
why the quality variable is empty?
The reason is that you're setting Preference.quality in the onCreate method in your Preference class. So what's probably happening is that when you start your application in your other class, Preference.quality is going to be null because it was never initialized to anything. The reason is that the other class has no way to access the onCreate method in your Preference class as of now. onCreate is executed when an activity starts, but that doesn't seem to happen anywhere in your code. A solution could be to initialize public static String quality outside of your onCreate method but still within the Preference class,
public static String quality = "QUALITY_HIGH";
#Override
public void onCreate(Bundle savedInstanceState) {
//insert code here
}
The problem was merely a scope issue.

Libgdx Android: method onStart() not called after onCreate()

onStart()
I know that onStart() method is called after onCreate() ( via Activity Lifecycle documentation ), but in my LibGDX project this doesn't happen. I' ve this code:
#Override
protected void onStart()
{
super.onStart();
Gdx.app.debug(TAG, "onStart");
}
but the string in debug terminal appears only if I resume the app from background. I need to do stuff after the initialise of the activity, when it becomes visible.
EDIT: MORE CODE
public class AndroidLauncher extends AndroidApplication {
private final static String TAG = AndroidLauncher.class.getSimpleName();
GoogleResolver googleResolver;
GoogleSignInAccount acct;
private Preferences googlePrefs;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
googleResolver = new GoogleResolverAndroid();
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
config.useImmersiveMode = true;
config.useGyroscope = false;
config.useCompass = false;
config.useAccelerometer = false;
GoogleLoginHandler.getInstance().setContext(this.getContext());
GoogleLoginHandler.getInstance().startApiClient();
GameManager.getInstance().listener = googleResolver;
initialize(new MainCrucy(), config);
googlePrefs = Gdx.app.getPreferences(GOOGLE_PREF);
GoogleLoginHandler.getInstance().mGooglePrefs = Gdx.app.getPreferences(GOOGLE_PREF);
}
#Override
protected void onStart()
{
super.onStart();
Gdx.app.debug(TAG, "onStart");
OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(GoogleLoginHandler.getInstance().getGoogleApiClient());
if (opr.isDone())
{
Gdx.app.debug(TAG, "Loggato");
GoogleSignInResult result = opr.get();
handleSignInResult(result);
} else {
opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
#Override
public void onResult(GoogleSignInResult googleSignInResult) {
handleSignInResult(googleSignInResult);
}
});
}
}
This is what I do. But onStart() does anything
How long do you wait after launching you application?
You have to remember that your app can take time to Start. If what you say is true than you wouldn't see Gdx debug - it's still fires at onStart().
So I assume:
you launch an app
you don't want to wait so you minimize that
you open it and onStart() ends and you see debug logs
By the way, could you show more code?
In the meantime look at the life cycle of Android app.
Android lifecycle
You can't use Gdx.app.debug() before the Libgdx application has had a chance to start up. I'm not positive if this happens before onStart() because libgdx doesn't run on the UI thread. Also, you must also use Gdx.app.setLogLevel(Application.LOG_DEBUG) first or calls to Gdx.app.debug() will do nothing.
But you can just use Android's Log.d() instead.

how to sync time to android

i have a url given to me to used for syncing the server time to my application,
Question is how to do that? anyone can explain to me what to do here thank i really appreciate it.
here's the URL = http://server10.instaforex.com:2012/TimeService/TimeService.svc/CurrentTime
here is my mainactivity code.
public class MainActivity extends Activity {
Timer timeoutTimer;
final Random myRandom = new Random();
GenerateTask genTask = new GenerateTask();
static String RAN_TEXT = "text";
class GenerateTask extends TimerTask {
boolean started = false;
public void run() {
if (started) {
System.out.println("generating");
final TextView textGenerateNumber = (TextView)findViewById(R.id.generatenumber);
RAN_TEXT = "";
for(int k=0;k<7;k++){
RAN_TEXT += myRandom.nextInt(10) + " ";
}
runOnUiThread(new Runnable() {
#Override
public void run() {
textGenerateNumber.setText(RAN_TEXT);
}
});
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonGenerate = (Button)findViewById(R.id.generateme);
buttonGenerate.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
System.out.println("click");
if (!genTask.started) {
genTask.started=true;
timeoutTimer = new Timer();
timeoutTimer.scheduleAtFixedRate(genTask, 0, 30000);
} else {
genTask.started=false;
timeoutTimer.cancel();
}
}
});
}
}
Try this..
First try to get the source of that html link using either one of solutions from the links of SO
solution 1 or solution 2
Second you can parse its content using parsers.
Third Display the parsed content as required time format.
Let me know if you face any difficulty..
It is unclear what your main activity is up to from the code you posted. It just concatenates some random numbers and sets them in a text area.
If you're looking to parse XML output returned by a HTTP client, there are many examples out there that show you how to do this. Take a look at this question - Android: parse XML from string problems
If NTP time is what you are really interested in, there are NTP clients for android that can help you sycn time correctly.
Use one of those solutions and you're good to go.

Categories

Resources