Android Service TextToSpeech - java

Hello I working on an app that readout the incoming message using service, it works fine but changing the TextToSpeech speed and pitch on service activity wont work. I used intent to get the speed and pitch value from MainActivity which works, but setting the speed and pitch to TTS wont work it remains on same speed and pitch value. I'm happy to receive any suggestions. Thanks
Speaker.java
public class Speaker extends Service implements TextToSpeech.OnInitListener {
private TextToSpeech tts;
private boolean ready = false;
private boolean allowed = false;
float speed, pitch;
public Speaker() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
speed = (float) intent.getExtras().get("Speed");
pitch = (float) intent.getExtras().get("Pitch");
Log.i("Speed", String.valueOf(speed));
Log.i("Pitch", String.valueOf(pitch));
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
public Speaker(Context context){
tts = new TextToSpeech(context, this);
}
#Override
public void onInit(int status) {
if(status == TextToSpeech.SUCCESS){
tts.setLanguage(Locale.getDefault());
tts.setPitch(pitch);
tts.setSpeechRate(speed);
ready = true;
}else{
ready = false;
}
}
public void speak(String text){
tts.speak(text, TextToSpeech.QUEUE_ADD, null);
}
public void pause(int duration){
tts.playSilence(duration, TextToSpeech.QUEUE_ADD, null);
}
public void destroy(){
tts.shutdown();
}
}

Related

android mediaplayer setlooping() does not work

In our android webview app, we start a foreground service (RingtonePlayingservice.class) from our firebase.class on notification action. The foreground service in turn starts playing the ringtone vide mediaplayer. The ringtone runs to like 10 seconds and stops, so we implemented setloop parameter, but still the mediaplayer just stops without looping at all. We are at loss as where we are going wrong. The codes are as given below
Firebase.Class (summarized)
public class Firebase extends FirebaseMessagingService {
public static Ringtone ringtone;
Intent i = new Intent(this, RingtonePlayingService.class);
this.startForegroundService(i);
}
Ringtoneplayingservice class
public class RingtonePlayingService extends Service {
private static final String TAG = RingtonePlayingService.class.getSimpleName();
private static final String URI_BASE = RingtonePlayingService.class.getName() + ".";
public static final String ACTION_DISMISS = URI_BASE + "ACTION_DISMISS";
public static final String ACTION_START = URI_BASE + "ACTION_START";
private MediaPlayer mp;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand");
if (intent == null) {
Log.d(TAG, "The intent is null.");
return START_REDELIVER_INTENT;
}
String action = intent.getAction();
if (ACTION_DISMISS.equals(action)) {
int notificationId = intent.getIntExtra("notificationId", 0);
dismissRingtone();
NotificationManager notificationManager =
(NotificationManager) getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
notificationManager.cancel(notificationId);
}
else {
mp = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
mp.setlooping (true);
mp.start();
}
return START_STICKY;
}
public void dismissRingtone() {
// stop the alarm rigntone
Intent i = new Intent(this, RingtonePlayingService.class);
this.stopService(i);
}
#Override
public void onDestroy() {
super.onDestroy();
if(mp.isPlaying())
{
mp.reset();
}
else {
}
}}
Any help would be deeply appreciated

WearOS Off Body Event is not always triggered

I'm developing a simple app for WearOS. This app consists of the app itself, which just shows an image and two services. One is a service, does NFC card emulation and the other simply listens for the off body event, and resets some values, whenever the watch is taken off. This works well while I'm debugging and also for a some time when started normally.
However, after a few hours, the watch can be taken off, without my app getting the event. I suspect, that the OS is killing the service and not restarting it, despite the START_STICKY flag. The watch is not coupled with a phone and is not running other apps.
This is the code of my service:
public class MySensorService extends Service
{
private static final String TAG = "MySensorService";
private SensorManager sensorManager;
private Sensor mOffBody;
public MySensorService()
{
Log.i(TAG, "Sensor service was created.");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.i(TAG, "Sensor service starting.");
sensorManager = (SensorManager) getApplicationContext().getSystemService(SENSOR_SERVICE);
mOffBody = sensorManager.getDefaultSensor(TYPE_LOW_LATENCY_OFFBODY_DETECT, true);
if (mOffBody != null) {
sensorManager.registerListener(mOffbodySensorListener, mOffBody,
SensorManager.SENSOR_DELAY_NORMAL);
}
Log.i(TAG, "Sensor service was started.");
return START_STICKY;
}
private void onWatchRemoved()
{
Log.i(TAG, "Watch is not worn anymore");
Intent intent = new Intent(this, MyAPDUService.class);
intent.putExtra("UserID", 0);
Log.d(TAG,"starting service");
startService(intent);
}
private void onWatchAttached()
{
Log.i(TAG, "Watch is now worn");
}
private final SensorEventListener mOffbodySensorListener = new SensorEventListener()
{
#Override
public void onSensorChanged(SensorEvent event)
{
if (event.values.length > 0)
{
if (event.values[0] == 0) // 0 = Watch is not worn; 1 = Watch is worn
{
onWatchRemoved();
}
else
{
onWatchAttached();
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int i)
{
}
};
#Override
public void onDestroy()
{
super.onDestroy();
Log.i(TAG, "Sensor Service destroyed");
}
}

android studio use camera in background

I'm new to the Android studio and I was trying to make the camera work in the background. I just want the camera to get the feed activity of it but when I'm trying to open the app it just automatically stops. The camera is usually working fine if it's in the MainActivity but when I transfer it to my camera service the app automatically stops when I open.
public class CameraService extends Service implements CameraBridgeViewBase.CvCameraViewListener2{
private static final String TAG = "MainActivity";
private JavaCameraView mOpenCvCameraView;
private Mat mRgba;
public CameraService(){
}
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status){
switch (status) {
case LoaderCallbackInterface.SUCCESS:{
Log.i(TAG, "OpenCV loaded successfully");
mOpenCvCameraView.enableView();
}
break;
default:{
super.onManagerConnected(status);
}
break;
}
}
};
#Override
public void onCreate() {
mOpenCvCameraView = (JavaCameraView) mOpenCvCameraView.findViewById(R.id.javacameraview);
mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
mOpenCvCameraView.setCvCameraViewListener(this);
mOpenCvCameraView.setCameraIndex(CameraBridgeViewBase.CAMERA_ID_FRONT);
Toast.makeText(this, "The new Service was Created", Toast.LENGTH_LONG).show();
}
private void setContentView(int activity_main) {
}
#Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this, " Service Started", Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
super.onDestroy();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
#Override
public void onCameraViewStarted(int width, int height) {
mRgba = new Mat(height, width, CvType.CV_8UC4);
}
#Override
public void onCameraViewStopped() {
mRgba.release();
}
#Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
return inputFrame.rgba();
}
}
can someone give me some tips or pinpoint my problem?
Google’s Android Pie update came with a new feature that prevents apps from running in the background from using the camera. This feature ensures that you don’t live in fear of malicious apps (that remain active in the background when your screen is turned off) capturing potentially unwanted scenes of you or your loved ones without authorization.
error in your code: you are using an unassigned object to find the id
if you are doing it for illegal purposes, don't do this -this type of problem is not liked by the StackOverflow community.

How to prevent music to stop after the phone's screen goes off?

I am making an application which play background music. And when my phone's screen goes off(or sleep) then the music stops and I want it to also play after the screen goes's off.
This is My code.
MediaPlayer ring= MediaPlayer.create(MainActivity.this,R.raw.backgroundmusic);
ring.start();
ring.setLooping(true);
MediaPlayer class can be used to control playback of audio/video files and streams. An example on how to use the methods in this class can be found in VideoView.
MediaPlayer
public class SoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.idil);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
Intent svc=new Intent(this, SoundService.class);
startService(svc);
Make sure You've added your service to the menifest.
<service android:enabled="true" android:name=".SoundService" />
You should consider using Service.

Streaming audio with media player

I have been working on an audio stream app but I need clarity on a variety of issues. First of all, I am playing the audio file with a bound service and I have a play-pause button` that toggles player on and off.
These are the issues i have with my code:
Media player gets instantiated each time I press play button but that is not what because I also need to pause playback when needed.
Playback is very slow. It takes a lot of time for the mediaplayer to prepare and stream.
Sometimes media player gets initialized twice if the user vigorously toggles the playpause button.
Here the code:
Music Player Activity
btn_play_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!playPause) {
btn_play_pause.setImageResource(R.drawable.pause_button);
if (initialStage) {
musicService.play();
Toast.makeText(MusicPlayerActivity.this, "Playing started", Toast.LENGTH_SHORT).show();
}
playPause = true;
} else {
btn_play_pause.setImageResource(R.drawable.play_button);
Toast.makeText(MusicPlayerActivity.this, "Playing paused", Toast.LENGTH_SHORT).show();
playPause = false;
musicService.pause();
}
}
});
}
Music Service
public class MusicService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnCompletionListener{
private final IBinder mBinder = new MusicService.AudioBinder();
private MediaPlayer mediaPlayer;
private AudioManager audioManager;
private AudioManager.OnAudioFocusChangeListener audioFocusChangeListener;
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(this, "Network Error", Toast.LENGTH_LONG).show();
mediaPlayer.reset();
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
try {
mp.setDataSource(stream_source);
mp.prepareAsync();
mp.start();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
mediaPlayer = mp;
}
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer = mp;
}
public class AudioBinder extends Binder {
public MusicService getService() {
//Return this instance of RadioBinder so clients can call public methods
return MusicService.this;
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null && intent.getAction() != null) {
switch (intent.getAction()) {
case Constants.ACTION_STOP_AUDIO_SERVICE:
hideNotification();
Intent i = new Intent(this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags (Intent.FLAG_ACTIVITY_SINGLE_TOP);
i.putExtra("close_activity",true);
this.startActivity(i);
break;
case Constants.ACTION_STREAM_PLAY_PAUSE:
if (isPlaying()) {
pause();
showNotification();
stopForeground(false); // stop making it a foreground service but leave the notification there
} else {
play();
showNotification();
}
break;
default:
break;
}
}
return START_STICKY;
}
#Override
public void onCreate() {
setUpAudioManager();
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
}
public void play() {
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnErrorListener(this);
showNotification();
}
public void pause() {
if(mediaPlayer.isPlaying()) {
mediaPlayer.pause();
audioManager.abandonAudioFocus(audioFocusChangeListener);
}
showNotification();
}
public boolean isPlaying() {
return mediaPlayer != null && (mediaPlayer.isPlaying());
}
#Override
public boolean stopService(Intent name) {
if (mediaPlayer != null){
mediaPlayer.release();
mediaPlayer = null;
}
return super.stopService(name);
}
public void hideNotification() {
stopForeground(true);
}
#Override
public void onDestroy() {
if(mediaPlayer!= null){
mediaPlayer.release();
}
super.onDestroy();
}
public void releaseTrack(){
if(mediaPlayer!= null){
mediaPlayer.release();
}
}
}

Categories