hei, can you help me?, i have 2 activity and i want to stop mediaPlayer in another activity, how to use the button in first activity to stop media player in the second activity,
my code in first activity
public class homenor extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homenor);
Button btmateri = (Button) findViewById(R.id.btmateri);
btmateri.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(homenor.this, home.class);
home.mediaPlayer.stop();
home.mediaPlayer2.stop();
startActivity(intent);
}
});
}
and this code in second activity
public class home extends AppCompatActivity {
int [] sound, soalkuis;
int soundke = 0;
int getNosoal = 0;
public static MediaPlayer mediaPlayer, mediaPlayer2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
sound = new int[] {R.raw.definisiprisma1, R.raw.definisiprisma2, R.raw.definisiprisma3,R.raw.jaringprisma1,R.raw.luasprisma1, R.raw.luasprisma2
,R.raw.luasprisma3,R.raw.luasprisma4,R.raw.luasprisma5,R.raw.luasprisma6,R.raw.contohluasprisma1,R.raw.penyelesaianluasprisma1,R.raw.contohluasprisma2
,R.raw.penyelesaianluasprisma2,R.raw.contohluasprisma3, R.raw.penyelesaianluasprisma3, R.raw.volumeprisma1, R.raw.contohvolume1
, R.raw.penyelesaianvolumeprisma1, R.raw.contohvolume2, R.raw.penyelesaianvolumeprisma2, R.raw.contohvolume3, R.raw.penyelesaianvolumeprisma3
, R.raw.rangkumanprisma1, R.raw.rangkumanprisma2};
soalkuis = new int[] {R.raw.soalprisma1, R.raw.soalprisma2, R.raw.soalprisma3, R.raw.soalprisma4, R.raw.soalprisma5, R.raw.soalprisma6
, R.raw.soalprisma7, R.raw.soalprisma8, R.raw.soalprisma9, R.raw.soalprisma10};
mediaPlayer = new MediaPlayer();
mediaPlayer2 = new MediaPlayer();
mediaPlayer = MediaPlayer.create(home.this, sound[soundke]);
mediaPlayer2 = MediaPlayer.create(home.this, soalkuis[getNosoal]);
mediaPlayer2.setLooping(false);
mediaPlayer.setLooping(false);
mediaPlayer.start();
when i try that, i got error like thisjava.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.stop()' on a null object reference
how can i fix that? thank you
create class MyMediaPlayer,
public class MyMediaPlayer {
private static MyMediaPlayer Instance;
MediaPlayer mediaPlayer;
static MyMediaPlayer getMediaPlayerInstance() {
if (Instance == null) {
return Instance = new MyMediaPlayer();
}
return Instance;
}
public void playAudioFile(Context context, int sampleAudio) {
mediaPlayer = MediaPlayer.create(context, sampleAudio);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
}
public void stopAudioFile() {
if (mediaPlayer != null) {
mediaPlayer.stop();
}
}}
Now, Call this method to play audio
MyMediaPlayer.getMediaPlayerInstance().playAudioFile(this, R.raw.sampleaudio)
To Stop Audio, Call this method
MyMediaPlayer.getMediaPlayerInstance().stopAudioFile()
Take the media player as public which you are already taking, then from the second activity, stop the media player like this
try {
mp.reset();
mp.prepareAsync();
mp.stop();
mp.release();
mp = null;
} catch (Exception e) {
e.printStackTrace();
}
my suggestion is to create a class like MediaPlayerManager or ...
create MediaPlayer instance inner this class and implement your interface with your method like pause, play, stop, ...
so, when need action MediaPlayer get instance this class and call suitable method
Related
public class momtahina5 extends AppCompatActivity {
private static final String TAG = "momtahina5";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_momtahina5);
Log.d(TAG,"onCreate: Starting.");
Button gotobakara201 = (Button) findViewById(R.id.gotobakara201);
Button backtobakara286 = (Button) findViewById(R.id.backtobakara286);
gotobakara201.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: clicked btngotobakara201");
Intent intent1 = new Intent(momtahina5.this,bakara201.class);
startActivity(intent1);
MediaPlayer mp = MediaPlayer.create(momtahina5.this,R.raw.mumfive);
mp.start();
}
});
}
}
What you can do is Release media player when activity is finished or destroyed.
below code will demonstrate you.
#Override
protected void onDestroy() {
super.onDestroy();
if (mp != null) {
mp.stop();
mp.reset();
mp.release();
}
}
override the 'onPause()' method of the current Activity and in that do this:
#Override
public void onPause() {
super.onPause();
if(mp != null) {
mp.release();
mp = null;
}
}
And also you want to make the MediaPlayer object as a class variable.
*Edit: It would be better to use the onPause() method instead of the onDestroy() method. When you move to another activity, the previous activity is not immediately destroyed. Refer to Android activity lifecycle for more info.
I am trying to develop a simple test project that plays sound when I tap the button and stop automatically after a few minutes after playing the sound.
Here is a code snippet:
Code for playing:
if (mPlayer != null) mPlayer = null;
mPlayer = MediaPlayer.create(this, R.raw.shush_v2);
mPlayer.setLooping(true);
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
Code for stopping:
if(mPlayer != null && mPlayer.isPlaying()) {
mPlayer.stop();
mPlayer.reset();
mPlayer.release();
mPlayer = null;
}
But sometimes I can still hear two sounds playing after I've stopped the sound.
Have so ever seen this behaviour before?
You should clear your media player.
//example usage of clearing media player when its over.
ourSong.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
clearMediaPlayer(mp);
}
});
//You can use this to stop media player.
private void clearMediaPlayer(MediaPlayer mp){
if(mp!=null){
mp.stop();
mp.release();// this will clear memory
mp = null;
}
}
public class PlayerApp extends Activity {
Button btnStart;
MediaPlayer mediaPlayer = null;
// Use the handler to stop the Player, after specific time
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player_app);
btnStart = (Button)findViewById(R.id.btnStart);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
// Initialize Player and start it.
// Call the Handler same time.
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.test);
mediaPlayer.start();
startHandler();
}
});
}
private void startHandler()
{
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// if Player is not null, then Stop it and Reset Null.
if(mediaPlayer!=null)
{
mediaPlayer.stop();
mediaPlayer = null;
}
}
}, 2500);
}
}
I'm having a bit of a trouble,, here's the gen. idea,, I have created an app a simple game-like application.. however the problem is when I try to click the button in the title screen it doesn't play the click sound.. can anyone please help me.. here's the code for my sound
public class Effects extends Activity implements MediaPlayer.OnCompletionListener {
Button mPlay;
MediaPlayer mPlayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPlay = (Button)findViewById(R.id.btnStart);
mPlay.setOnClickListener(playListener);
setContentView(R.layout.activity_main);
}
#Override
public void onDestroy() {
super.onDestroy();
if(mPlayer != null) {
mPlayer.release();
}
}
private View.OnClickListener playListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mPlayer == null) {
try {
mPlayer = MediaPlayer.create(Effects.this, R.raw.button11);
mPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
} else {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
}
};
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
}
}
and here's my code for the main java that I want the sound to be played when I clicked this button
public class Main extends Activity implements OnClickListener
{
Button about;
Button Quit;
Button start;
protected void onCreate(Bundle onSavedInstanceState) {
super.onCreate(onSavedInstanceState);
setContentView(R.layout.activity_main);
about = (Button)findViewById(R.id.btnAbout);
about.setOnClickListener(this);
Quit = (Button)findViewById(R.id.btnQuit);
Quit.setOnClickListener(this);
start = (Button)findViewById(R.id.btnStart);
start.setOnClickListener(this);
}
public void onClick(View argo)
{
if(argo.getId()==R.id.btnAbout)
{
Intent i = new Intent(this,About.class);
this.startActivity(i);
}
if(argo.getId()==R.id.btnQuit)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
if(argo.getId()==R.id.btnStart)
{
Intent start = new Intent(this,Howto.class);
this.startActivity(start);
Intent svc=new Intent(this,Effects.class);
startService(svc);
}
}
}
Use SoundPool to play your sounds: http://developer.android.com/reference/android/media/SoundPool.html you should init sounds in your onCreate() and then play them back in onClick()
And instead of doing thousands of pointless if(argo.getId()==R.id.btnQuit) (you should at least use else) get familiar with switch/case syntax)
I have implemented a class that extends MediaPlayer.
public class AudioPlayer extends MediaPlayer {
private String fileName = null;
FileInputStream fileInputStream = null;
private MediaPlayer mediaPlayer = null;
// Constructor
public AudioPlayer(Context context)
{
// Initialization
}
public void onPlay(boolean start)
{
if(start) {
startPlaying(this.fileName);
}else {
stopPlaying(this.fileName);
}
}
private void startPlaying(String fileName) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(fileInputStream.getFD());
mediaPlayer.prepare();
mediaPlayer.start();
// mediaPlayer.setOnCompletionListener(new CompletionListener());
}
class CompletionListener implements MediaPlayer.OnCompletionListener {
#Override
public void onCompletion(MediaPlayer mp) {
// Do stuff
}
}
When I setOnCompletionListener on MediaPlayer object inside my custom AudioPlayer class it works just fine. However I would like to set this listener on the object created from this class since it's used in multiple activities. Different actions should be taken in onCompletion() method therefore implementing onCompletionListener inside my custom class is pointless.
When I create an instance of my custom class in each activity where I want to use it
AudioPlayer audioPlayer = new AudioPlayer(context);
and set on it onCompletionListener:
audioPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
}
});
it’s never being called. Is there a way to call onCompletionListener on my custom object?
The solution is to write a method that returns MediaPlayer object and then call setOnCompletionListener() on this object:
public MediaPlayer getActiveMediaPlayer()
{
if ( mediaPlayer != null )
return this.mediaPlayer;
else
return null;
}
and then in the activity:
audioRecorder.getActiveMediaPlayer().setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
Log.d("MediaPlayer", "test");
}
});
Here is my problem, when I start the Activity the Music start like I want it to, but when I leave the Activity (by pressing the back button) the Application crashes and "stopped unexpectedly" :( All I want to do is have the audio STOP and go to another activity without the unexpected stop. How can I do this?
public class Run extends Activity {
/** The OpenGL View */
private GLSurfaceView glSurface;
private MediaPlayer mPlayer;
/**
* Initiate the OpenGL View and set our own
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Create an Instance with this Activity
glSurface = new GLSurfaceView(this);
//Set our own Renderer and hand the renderer this Activity Context
glSurface.setRenderer(new Lesson06(this));
//Set the GLSurface as View to this Activity
setContentView(glSurface);
new Thread(new Runnable() {
public void run() {
try{
MediaPlayer mPlayer = MediaPlayer.create(Run.this, R.drawable.theygonelovemeformyambition);
mPlayer.setLooping(true);
mPlayer.start();
while(mPlayer.isPlaying()){
android.os.SystemClock.sleep(100);
}
}catch(Exception e){
String TAG = null;
Log.d(TAG,"ERROR PLAYING");
e.printStackTrace();
}
}}).start();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mPlayer.release();
}
}
hi before you have to release media player resources. You should stop media player like below.
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
if(mPlayer.isPlaying())
mPlayer.stop();
mPlayer.release();
super.onDestroy();
}
You dont have innitialized the mPlayer
In the public void run() you are just creating a new MediaPlayer
and so when you are trying mPlayer.release(); you are reffering to the null mPlayer and so you get a nullPointerExceptionerror (i guess)