Android Google Cloud Text to speech doesn't stop - android

Google cloud TTS audio does not stop after activity destroy.
googleCloudTTS = GoogleCloudTTSFactory.create(BuildConfig.API_KEY)
override fun onDestroy() {
destroyStory()
super.onDestroy()
}
// destroy story
private fun destroyStory() {
IS_PLAY_AUDIO = false
// googleCloudTTS?.stop()
googleCloudTTS?.close()
}
I tried with both googleCloudTTS?.close() and googleCloudTTS?.stop() but doesn't stop playing audio.

Related

Android app crash, when stopping a service

In an Android app made to play some audio file in the background, I have the following situation. The app plays the audio as I expect, also keeping playing in the background. The issue I am facing is when I want to stop the service.
I have two buttons on the main activity, one for starting the service and the other one to stop it.
This is the function fired by the START button:
fun startHandler(view: View) {
val audioName = "myAudio"
val serviceIntent = Intent(this, TheService::class.java)
serviceIntent.putExtra("name", audioName);
startForegroundService(serviceIntent)
}
This is the function fired by the STOP button:
fun stopHandler(view: View) {
val serviceIntent = Intent(this, TheService::class.java)
stopService(serviceIntent)
}
When I tap the STOP button, the audio stops (as expected), but the app crashes right after (this is not expected).
Here is the onDestroy() function on the service side:
override fun onDestroy() {
super.onDestroy()
audioPlayer.stop()
}
And the onStartCommand() function on the service side:
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val runnable = Runnable {
val audioName = intent?.getStringExtra("name")
val audioID = resources.getIdentifier(audioName,"raw", packageName)
audioPlayer = MediaPlayer.create(this, audioID)
audioPlayer?.setLooping(true)
audioPlayer.start()
}
val thread = Thread(runnable)
thread.start()
return START_NOT_STICKY
}
Is there any mistake that can be seen in the code above or some place I should look at in order to solve the problem ?

Android Kotlin - ExoPlayer keeps playing when app goes to background

So far I only found questions about how to make ExoPlayer keep playing when app goes to background. Why the hell is that the case by me without coding this bs??
This is what I have so far and it's inside RecyclerView OnBingViewHolder:
val player = ExoPlayer.Builder(context).build()
val mediaItem: MediaItem = MediaItem.fromUri(fileUrl)
player.setMediaItem(mediaItem)
player.repeatMode = Player.REPEAT_MODE_ONE
holder.vidPlayer.player = player
player.prepare()
player.seekTo(100)
// player.play()
holder.vidPlayer.setTag(mpTag, player)
holder.vidPlayer.setTag(manuelPlayTag, false)
holder.vidPlayer.setTag(manuelPauseTag, false)
player.addListener(object : Player.Listener { // player listener
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
if (playWhenReady && playbackState == Player.STATE_READY) {
Log.d(tagg, "state: plays")
holder.vidPlayer.hideController()
} else if (playWhenReady) {
// might be idle (plays after prepare()),
// buffering (plays when data available)
// or ended (plays when seek away from end)
} else {
Log.d(tagg, "state: pause")
holder.vidPlayer.showController()
}
}
})
how I prevent the play when app goes to background?
When your app goes to the background the active Fragment/Activity's Lifecycle method onPause (and onStop) is called. In the onPause method you can cycle through your bound ViewHolders and stop the video player(s).
You can simply stop the ExoPlayer when the app goes to the background.
override fun onStop() {
super.onStop()
simpleExoPlayer.stop()
}
And in onStart just prepare() the ExoPlayer again:
override fun onStart() {
super.onStart()
simpleExoPlayer.prepare()
}
In order to automatically play the media, you need to set playWhenReady = true.
simpleExoPlayer.playWhenReady = true
By setting playWhenReady = true it will automcatically play the content and we don't need to explicitly call simpleExoPlayer.play().

Exoplayer notification not clearing

I have exoplayer integrated within my application based on this link.
I have added a pending intent inside createCurrentContentIntent().
return PendingIntent.getActivity(
context, 0,
Intent(context, MyActivity::class.java), 0
)
I face an issue over here. I started playing the audio and the player notification also comes up in the status bar. My requirement is to play audio even if the app is in the background. So, I haven't released the player in onStop(). I have added the below code in onDestroy().
override fun onDestroy() {
playerNotificationManager?.setPlayer(null)
player?.stop()
player?.release()
player = null
super.onDestroy()
}
If I manually kill the application from the background when the player is playing, the notification doesn't go off. So, if I click on the notification it will crash with NullPointerException because MyActivtity is no more.
Could someone suggest a solution for the same?
I've implemented ExoPlayer along with MediaSessionCompat and MediaSessionConnector, which allows Exo to manage the media notification (and stuff like audio focus) implicitly.
class MyServiceClass {
private lateinit var player: SimpleExoPlayer
private lateinit var playerNotificationManager: PlayerNotificationManager
private lateinit var mediaSession: MediaSessionCompat
private lateinit var mediaSessionConnector: MediaSessionConnector
override fun onCreate() {
super.onCreate()
player = ...
playerNotificationManager = ...
mediaSession = MediaSessionCompat(this, CONSTANT).apply{ ..setup callback... }
mediaSessionConnector = MediaSessionConnector(mediaSession)
mediaSessionConnector.setPlayer(player)
playerNotificationManager.setMediaSessionToken(mediaSession.token)
playerNotificationManager.setPlayer(player)
}
override fun onDestroy() {
mediaSession.isActive = false
mediaSession.release()
mediaSessionConnector.setPlayer(null)
playerNotificationManager.setPlayer(null)
player.release()
super.onDestroy()
}
}
This should handle removing the notification, when you kill the app.
I also use a PlayerNotificationReceiver to react to notification changes by the system which is omitted in the code above. Also the whole part of triggering and reacting to notifications in the app is omitted.
I changed the complete implementation and used services. This solved the issue.

How to put an audio before a stream connection in Android Studio (Kotlin)

I am new to programming and I am making a basic app for radio in which an introduction audio sounds when you press a button, then a second audio should appear until the network connection of the online radio is established.
I have managed to make the intro audio sound complete when I click, then silence is generated until the online radio plays, but I don't know how to put a second audio that detects the charging status before the radio plays. This is my code:
fun MediaPlayerRadio(){
mediaPlayer = MediaPlayer.create(
this#MainActivity,
Uri.parse("https://radiolink.com")
)
mediaPlayer?.start()
}
........................................................................
fun MediaPlayerIntroSound(){
mediaPlayer = MediaPlayer.create(this, R.raw.SoundIntro)
mediaPlayer?.start()
}
........................................................................
fun click_Button_Radio(){
btn.setOnClickListener(){
if (btn.isSelected){
btn.isSelected = false
mediaPlayer?.stop()
}else{
btn.isSelected = !btn.isSelected
MediaPlayerIntroSound()
mediaPlayer!!.setOnCompletionListener(object : MediaPlayer.OnCompletionListener {
override fun onCompletion(mp: MediaPlayer?) {
MediaPlayerRadio()
}
})
}
}
}
I hope you can support me with this.
For this, you will have to use 2 media players, one for intro sound and another for actual sound.
While the time actual sound media player gets ready, you can play different audios on the intro sound media player.
To stop the intro audio player once the other player is ready, you can make use of a view model.
//Play Media player
mediaPlayer = MediaPlayer.create(this#MainActivity, R.raw.first_audio)
mediaPlayer.start()
// Add completion listener, so that we can change the audio
// once the first one is finished
mediaPlayer.setOnCompletionListener {
mediaPlayer.release()
mediaPlayer = MediaPlayer.create(this#MainActivity, R.raw.second_audio)
mediaPlayer.start()
}
// We are observing a MutableLiveData of Boolean type,
// once it is true we will stop the intro media player
// and start the radio player
viewModel.isPlayerReady.observe(this) { isReady ->
if(isReady) {
mediaPlayer.stop()
// Start radio media player
}
}
// This is how I am changing the value of MutableLiveData
demoBtn.setOnClickListener {
viewModel.isPlayerReady.value = true
}
I have tested the above approach and it works fine as expected.
Steps to link a view model to the activity:
Add the dependency: implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0"
Make a view model class and a mutable live variable of type boolean in it.
class MainViewModel: ViewModel() {
val isPlayerReady = MutableLiveData<Boolean>()
}
Link view model with the activity.
class MainActivity : AppCompatActivity() {
private lateinit var viewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
....
}

When will onCompletion be launched in MediaPlayer?

I try to use the following code to play music.
I know I need to release mediaPlayer as soon as possible if I don't use it again, so I place the release code in onCompletion.
1: Will onCompletion be launched after a music have finished play?
2: Will onCompletion be launched after I invoke mediaPlayer?.stop()?
3: Will onCompletion be launched if the Activity which invoke PlayHelper is destroied?
Code
class PlayHelper private constructor(): MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener {
private var mediaPlayer: MediaPlayer? = null
fun play(path: String){
mediaPlayer= MediaPlayer()
mediaPlayer?.setAudioAttributes(
AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build()
)
mediaPlayer?.setDataSource(path)
mediaPlayer?.setOnPreparedListener(this#PlayHelper)
mediaPlayer?.prepareAsync()
}
fun pause(){
mediaPlayer?.pause()
}
fun stop(){
mediaPlayer?.stop()
}
/** Called when MediaPlayer is ready */
override fun onPrepared(mediaPlayer: MediaPlayer) {
mediaPlayer.start()
}
override fun onCompletion(mediaPlayer: MediaPlayer) {
if (mediaPlayer.isPlaying) {
mediaPlayer.stop();
mediaPlayer.release()
}
}
companion object {
// For Singleton instantiation
#Volatile private var instance: PlayHelper? = null
fun getInstance() = instance?: synchronized(this) {
instance?: PlayHelper().also { instance = it }
}
}
}
Regarding the official documents, onCompletion is called only when the end of a media source is reached during playback. So, in other cases, like calling mediaPlayer.stop(), it won't be called.
1: Will onCompletion be launched after a music have finished play?
It will.
2: Will onCompletion be launched after I invoke mediaPlayer?.stop()?
It will not.
3: Will onCompletion be launched if the Activity which invoke PlayHelper is destroied?
It will not. The PlayHelper will be removed from memory when the Activity is destroyed.
This link: onCompletionListener from the docs contains the following line:
Called when the end of a media source is reached during playback.

Categories

Resources