Change button background from service - java

i'm following a step to play audio file from here link
and it works all right, the service in the link above is to play and stop audio.
The problem is i want to change a button background when the audio stop, so far i only got this in the activity that call the service:
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isPlaying == false) {
isPlaying = true;
btnPlay.setBackgroundResource(R.drawable.stop_play_button);
playAudio();
} else {
isPlaying = false;
btnPlay.setBackgroundResource(R.drawable.play_button);
stopAudio();
}
}
});

You can declare on completetion listener on your player:
player.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
isPlaying = false;
btnPlay.setBackgroundResource(R.drawable.play_button);
stopAudio();
}
});

Related

Stop MediaPlayer when minimizing

button4 = findViewById(R.id.button4);
musicSound = MediaPlayer.create(this, R.raw.music);
buttonClick(); }
private Button button4;
private MediaPlayer musicSound;
public void buttonClick() {
button4.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
soundPlay(musicSound);
}
} ); }
public void soundPlay(MediaPlayer sound) {
{ sound.start();
sound.setLooping(true); }
buttonMusicStop = findViewById(R.id.buttonMusStop);
buttonClick2();}
private ImageButton buttonMusicStop;
public void buttonClick2() {
buttonMusicStop.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
soundPlay2(musicSound);
}});}
public void soundPlay2(MediaPlayer sound) {
if (sound.isPlaying()) {
sound.pause();
} else {
sound.start();
sound.setLooping(true);
} }
Hello! I start music in my application, but when I minimize the application, the music does not stop. What do I need to write so that when the application is minimized and also when the screen is turned off, the music stops. Any help would be greatly appreciated!
Seem your app is playing in background. So create onResume and onStop to stop play and release resource, somethings look like this
onStop{
sound.stop();
sound.reset();
sound.release();
mediaplayer = null;
supper.onStop();
}

How to play android radio with screen off background playable option

How to play android radio with screen off background playable option. My App working fine without backgournd playing option. But I want to give background playing option in my app that is when user closes the app, the radio should keep on playing, untill user stops it.
I am also disable screen off option in xml file with android:keepScreenOn="true" option but I want to remove this option and keep mobile screen off and play my app in background.
This is my code
Button BPlay;
String stream = "http://stream.zeno.fm/hmzuvfwn9k0uv";
MediaPlayer mediaPlayer;
boolean prepared = false;
boolean started = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio);
BPlay = (Button) findViewById(R.id.b_play);
BPlay.setEnabled(false);
BPlay.setText("Loading.....");
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
new PlayerTask().execute(stream);
BPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (started){
started = false;
mediaPlayer.pause();
BPlay.setText("PLAY");
} else {
started = true;
mediaPlayer.start();
BPlay.setText("PAUSE");
}
}
});
}
class PlayerTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... strings) {
try {
mediaPlayer.setDataSource(strings [0]);
mediaPlayer.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
BPlay.setEnabled(true);
BPlay.setText("PLAY");
}
}
#Override
protected void onPause() {
super.onPause();
if (started){
mediaPlayer.pause();
}
}
#Override
protected void onResume() {
super.onResume();
if (started){
mediaPlayer.start();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (prepared){
mediaPlayer.release();
}
}
}
In order to have you media playing while the app is in the background, you'll need a MediaSession background Service running in parallel.
TLTR, here's a basic tutorial from Google on how to do that.

record video from rtsp on TextureView

Hi I have the following code that simply displays an RTSP on a TextureView to then make a screenShot of the stream and save it as an image,
playButton.setOnClickListener(this);
playButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(String.valueOf(Uri.parse("rtsp://........./")));
} catch (IOException e) {
e.printStackTrace();
}
mMediaPlayer.setSurface(surface);
mMediaPlayer.setLooping(true);
mMediaPlayer.prepareAsync();
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
playButton.setVisibility(View.INVISIBLE);
btnCapture.setVisibility(View.VISIBLE);
recordVideo.setVisibility(View.VISIBLE);
}
});
}
});
recordVideo.setOnClickListener(this);
recordVideo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
how can I record a portion of this video and save it as mp4? I made the start and stop buttons for recording the video Can I save the video between the start and stop?

Media Player error in RecyclerView

i have a RecyclerView that displays a list of songs and i have successfully implemented on click listener with it and verified it with logs. Now i want to play the song upon click event. When i first click on a item the songs starts to play but if i then tap on any other item the app simply crashes
Here is my RecyclerViewClickListener
SongAdapter songAdapter = new SongAdapter(getContext(), songsList, new RecyclerViewClickListener() {
#Override
public void onClick(View view, int position) {
Toast.makeText(getContext(), "You clicked on Ssong "+songsList.get(position).getSongName(), Toast.LENGTH_SHORT)
.show();
songPath = songsList.get(position).getUrl();
Log.v("Song Path", songPath);
if(mp.isPlaying())
releaseMediaResources();
playSong();
}
});
recyclerView.setAdapter(songAdapter);
Here is my playSong method
private void playSong () {
if(!songPath.equals("")) {
try {
mp.setDataSource(songPath);
} catch (Exception e) {
Log.e("Home Fragment", "Error setting song Url", e);
}
mp.prepareAsync();
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.stop();
mp.reset();
mp.release();
}
});
}
}
And here is my releaseMediaResources
private void releaseMediaResources() {
mp.stop();
mp.reset();
mp.release();
}
These are the errors
java.lang.IllegalStateException
at android.media.MediaPlayer.isPlaying(Native Method)
at com.ashutosh.prototype4.HomeFragment.playSong(HomeFragment.java:159)
at com.ashutosh.prototype4.HomeFragment.releaseMediaResources(HomeFragment.java:192)
at com.ashutosh.prototype4.HomeFragment.access$100(HomeFragment.java:31)
at com.ashutosh.prototype4.HomeFragment$2.onClick(HomeFragment.java:94)
at com.ashutosh.prototype4.SongAdapter$1.onClick(SongAdapter.java:50)
According to me the main problem lies in setting up the media player because when i display only toast messages there's no issues at all but as soon as i implement media player to on click method the crash occurs
I will create every time the new MediaPlayer, but of course try to check, if there is not already existing instance for instance:
private MediaPlayer mediaPlayer;
private void playSong(String filePath) {
if (mediaPlayer != null && mediaPlayer.isPlaying()){
mediaPlayer.stop();
}
mediaPlayer = MediaPlayer.create(getActivity(), Uri.parse(filePath));
mediaPlayer.setVolume(DEFAULT_VOLUME_MUSIC, DEFAULT_VOLUME_MUSIC);
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
}
});
}

Mediaplayer : pause called in state 1 - Android Eclipse

I'm creating a MediaPlayer button in the ActionBar, wherein it is playing automatically when the app started and when I clicked it should be off. The problem now is that the sound is not playing and when I click the button there is an error in logcat saying...
UPDATED LOGCAT.
12-18 19:04:57.812: E/MediaPlayer(5673): attachNewPlayer called in state 32
Here is the code..
public class MainActivity extends Activity{
private MediaPlayer mp;
Item btnplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = new MediaPlayer();
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
isPlaying=false;//when the media file playing is completed isPlaying=false; is must
}
});
play(null);//you are calling play by launching
}
//inflate items in actionbar
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
boolean isPlaying = false;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.btnplay) //whatever you named in xml
{
play(item);
}
return super.onOptionsItemSelected(item);
}
public void play(MenuItem menuItem) {
if (!isPlaying) {
try
{
AssetFileDescriptor afd = getAssets().openFd("caketown.mp3");
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp.prepare();
mp.start();//play sound
}
catch(Exception e) {
e.printStackTrace();
}
isPlaying = true;
}
else if (isPlaying) {
mp.pause();
isPlaying = false;
}
}
Here is the menu
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.xxx.MainActivity" >
<item
android:id="#+id/btnplay"
android:title=""
android:icon="#drawable/ic_action_volume_on"
android:onClick="play"
android:showAsAction="always"/>
<menu>
Please help me. I'm just new here. :(
1.Please initialize mp = new MediaPlayer(); in your onCreate() method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play(null);//you are calling play by launching
}
2.change it to boolean isPlaying = false; because when app start it set as boolean isPlaying = false so it will play the audio and again you click on it for pause it will work as per your code
3.change this else if
else if (isPlaying) {
mp.pause();
isPlaying=false;
}
4.change this function too
public void play(MenuItem menuItem) {
if (!isPlaying && !isPaused) {
try {
if (mp == null) {
// mp.release();
// mp.reset();
mp = new MediaPlayer();
AssetFileDescriptor afd = getAssets()
.openFd("caketown.mp3");
mp.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
mp.prepare();
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
isPlaying = false;// when the media file playing is completed
isPaused = false;
// Toast.makeText(getApplicationContext(), "play completed",
// Toast.LENGTH_SHORT).show(); // isPlaying=false; is must
}
});
}
mp.start();// play sound
} catch (Exception e) {
e.printStackTrace();
}
isPlaying = true;
} else if (isPlaying) {
Toast.makeText(getApplicationContext(), "play paused",
Toast.LENGTH_SHORT).show();
mp.pause();
isPlaying = false;
isPaused = true;
length = mp.getCurrentPosition();
// and for resuming the player from the position where it stopped
// lately is done by:
} else if (isPaused) {
mp.seekTo(length);
mp.start();
isPlaying = true;
isPaused = false;
}
}
Initialize isPlaying to false to get your conditional working.
Initialize MediaPlayer only once to to get the stop/pause working instead of overlapping sounds. That is, move the mp = new MediaPlayer(); to onCreate() for example.

Categories