Android studio check if Mediaplayer is playing in a screen widget activity - java

There'd be a button on the home screen which would play a certain song and change the background image of the button. If the user clicks on the button again (when the music is playing) then the music should stop and the background image of the button should set itself back to the general position. But it looks like the program can't detect if my Mediaplayer is playing. What am I missing here?
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
AppWidgetManager appWidgetManager= AppWidgetManager.getInstance(context);
RemoteViews rv= new RemoteViews(context.getPackageName(),
R.layout.playbtn_widget);
if (intent.getAction().equals("btnPlay")) {
if (!mediaPlayer.isPlaying()) {
mediaPlayer= MediaPlayer.create(context,R.raw.itsmylife);
mediaPlayer.start();
rv.setImageViewResource(R.id.imbtnwidget,
R.drawable.btnk32);
} else {
mediaPlayer.stop();
}
mediaPlayer.setOnCompletionListener(mediaPlayer -> {
rv.setImageViewResource(R.id.imbtnwidget,
R.drawable.btnk3);
appWidgetManager.updateAppWidget(new ComponentName(context,
BtnAppWidgetProvider.class), rv);
});
appWidgetManager.updateAppWidget(new ComponentName(context,
BtnAppWidgetProvider.class), rv);
}
}
It should set the background image back and stop the music when I tap on the button, but it just starts the mediaplayer again and the background image remains the same. I have no idea how I could fix this. It seems like it creates a new mediaplayer every single time

Issue
It creates a new Media Player because the class is recreated or re-executed. This clears all the variables and re-defines them. This makes the issue in your case.
Solution
Just create a class name anything like MediaPlayerHelper.java
Create a variable of MediaPlayer which is public and static. Like this:
public static MediaPlayer mp;
Now, when the button is pressed, you can check if it is playing or not. Something like this:
if(MediaPlayerHelper.mp != null && MediaPlayerHelper.mp.isPlaying()){
// the media player is currently playing. Stop it.
}else{
// the media is not playing. Start it
}

Related

Playing a sound on android

I have come across another error along my first app journey :) I want to play a sound when the app loads. Which is a .wav file. It lasts 2 seconds long yet it does not play when I run the app on my old Samsung S4. There is no errors within the IDE or anything I can see, I have checked if 'mp' has a value and it does. Looking around on posts most people have the problem that 'mp' is = null. Whereas mine has a value just no sound comes out of the phone... Again, any help is appreciated!
public class OpeningScreen extends Activity {
#Override
// create the screen state
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// connect the xml layout file
setContentView(R.layout.activity_opening_screen);
final MediaPlayer mp = new MediaPlayer();
mp.create(this, R.raw.welcome_message);
mp.start();
// create the on touch listener
ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.opening_layout);
layout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// change the screen to a new state
Intent intent = new Intent(OpeningScreen.this, GameScreen.class);
// start the new activity
startActivity(intent);
// stop welcome sound (if still playing)
mp.stop();
return true;
}
});
}
}
public static MediaPlayer create(Context context, int resid) is a static method to create a MediaPlayer for a given resource id.
It means that by calling create you are creating a new instance of media player with no reference usage.
Try to change
final MediaPlayer mp = new MediaPlayer();
mp.create(this, R.raw.welcome_message);
to
final MediaPlayer mp = MediaPlayer.create(this, R.raw. welcome_message);
And the player should work.
It's better to register for OnPreapredListener via MediaPlayer.setOnPreaparedListener and after preparation you start your media playback.
http://developer.android.com/guide/topics/media/mediaplayer.html
Why do you use final?
You can play a mp3 with
MediaPlayer mp = MediaPlayer.create(OpeningScreen.this, R.raw.welcome_message);
mp.start();
Also stopping mediaplayer is better if you stop in onDestroy.
public void onDestroy() {
mp.stop();
super.onDestroy();
}

cant pause mediaplayer after reopen activity

Here in my MainActivity.java I have an object MediaPlayer, which plays a sound when you click playB button and pause by pressing pauseB. Everything is working fine. But if you re-open the app and click pauseB, the sound continues to play. How to fix it? How to catch the current playing MediaPlayer?
public class MainActivity extends ActionBarActivity {
Button playB;
Button pauseB;
Context c;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button playB = (Button) findViewById(R.id.playB);
Button pauseB = (Button) findViewById(R.id.pauseB);
mp = mp.create(this, R.raw.fawaid_1);
playB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mp.start();
}
});
pauseB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mp.pause();
}
});
}
}
when you re-open the app, onCreate is called again, hence you have a new MediaPlayer object, and from that moment, play and pause buttons will control that new player object instead of a previous one. That's why your pause button will have no effect on the sound that started BEFORE you minimized the app. And if you press play button now, you will have two sounds playing at the same time
one way to overcome this, is to check if media player has already been initialized:
if(mp==null)
mp = MediaPlayer.create(this, R.raw.fawaid_1);
It is advisable to use Service with AIDL in developing music player.
Reasons.
You can retain the control again once you go back in your activity.
It is easy to perform an inter process communication.
Here is a simple music Player that runs on the Background, Music Player
The song I used in this music player is Owned by SnowFlakes

Using MediaPlayer class in Java (Android Studio)

I want the background music to repeat as long as the user stays in a particular screen. Is there a function in the MediaPlayer class that allows you to do the above task?
button1.setOnClickListener(new View.OnClickListener() {
#Overridepublic void onClick(View v) {
Intent intent = new Intent(context,kids_quiz.class);
startActivity(intent);
player=MediaPlayer.create(Games.this,R.raw.macdonald);
player.start();
}
});
Just start it when you are in that Activity, setLooping to true, and when the user leaves the screen destroy the mediaPlayer in Activity.onDestroy(and maybe onPause depending on what you want to accomplish) method.
Remember it is important to destroy a mediaPlayer when you're done with it as it consumes a lot of resources.

Mediaplayer gap before playing another

I have a few media players setup to play one after another on a button click however there is a noticeable gap between the media players playing ie. once mediaplayer one has finished there is a half a second before mediaplayer two plays, for the purpose I'm using the mediaplayers for the gap in audio is very noticeable, so what I'm asking is, is there a way to remove this gap. Now I don't know if I'm going wrong using different mediaplayers each time however this is what I've come up with so far.
Basically I've got onCompleteionListeners for each mediaplayer and within those I have the next mediaplayer play until the last. Any pointers would be appreciated.
public void onClick(View v) {
mpButtonThree = MediaPlayer.create(MainActivity.this, R.raw.audioReplay);
if (mpButtonThree==null){
//display a Toast message here
return;
}
mpButtonThree.start();
mpButtonThree.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mpButtonThree) {
mpButtonThree.release();
mpButtonOne = MediaPlayer.create(MainActivity.this, audioReplayPrimary);
if (mpButtonOne==null){
//display a Toast message here
return;
}
mpButtonOne.start();
mpButtonOne.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mpButtonOne) {
mpButtonOne.release();
mpButtonTwo = MediaPlayer.create(MainActivity.this, audioReplaySecondary);
if (mpButtonTwo==null){
//display a Toast message here
return;
}
mpButtonTwo.start();
mpButtonTwo.setOnCompletionListener(new soundListener1()
{
});
}
If You play files in series you can use single media player object.
create function that plays next media file and put it into OnCompletion.
This should remove gap between playing, because You don't have to release and create media player every time

How can I use Intent on Java, Android?

I have written the following code for playing video:
private void loadPlayer() {
Intent youtube=new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=CES7xNy70hU"));
startActivityForResult(youtube, 100);
}
My problem is that when the player finishes showing the video it won't close itself and the user needs to press the back button. I need the player to close itself automatically after the video has finished playing. How can I accomplish this?
The target platform is Android - 2.2.
Create an activity that just displays a VideoViewer. Play the video from there. Implement a listener for the completion of the video. Then call finish within there to end the activity:
videoViewer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp)
{
finish();
}
});
This will return you to the previous Activity.

Categories

Resources