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)
Related
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
I want a play button in my app that when clicked plays the audio and changes to pause, and when the pause button is clicked the audio stops and the button changes to play again and so on. But the button is not working as expected. Please help. I'm adding my java code below.
public class surah extends AppCompatActivity {
MediaPlayer mp = new MediaPlayer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_surah);
mp=MediaPlayer.create(surah.this, R.raw.surahkahf);
final ImageView audio = (ImageView)findViewById(R.id.btn);
audio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mp.isPlaying()){
mp.stop();
audio.setBackgroundResource(R.drawable.play);
try {
mp.prepare();
}catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
mp.start();
audio.setImageResource(R.drawable.pause);
}
}
});
}
}
Use audio.setImageResource(R.drawable.play) instead of audio.setBackgroundResource(R.drawable.play). Use mp.pause() instead of mp.stop();
First, as aborocz mentions in comments, you probably intend to pause playback instead of stop it, so the method you want to use is pause(). In that case you would not need to prepare the MediaPlayer again, and it will start from the same place it was paused when playback is resumed.
Second, the isPlaying() method is not particularly appropriate for this purpose. There are race conditions that prevent the desired behavior. From the Android MediaPlayer documentation:
Note that the transition from the Started state to the Paused state
and vice versa happens asynchronously in the player engine. It may
take some time before the state is updated in calls to isPlaying(),
and it can be a number of seconds in the case of streamed content.
Instead, store your own boolean value.
public class surah extends AppCompatActivity {
private MediaPlayer mp;
private boolean isMediaPlaying = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_surah);
mp = MediaPlayer.create(surah.this, R.raw.surahkahf);
final ImageView audio = (ImageView)findViewById(R.id.btn);
audio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isMediaPlaying) {
mp.pause();
audio.setBackgroundResource(R.drawable.play);
isMediaPlaying = false;
} else {
mp.start();
audio.setImageResource(R.drawable.pause);
isMediaPlaying = true;
}
}
});
}
}
I am creating a game, I want to play a background music for one activity only(For main menu of game), my code shown below, The problem is that the music plays more than one time, I want to play the same music also when activity Resumes.
public class Menu extends Activity {
MediaPlayer mp
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
mp = MediaPlayer.create(Menu.this, R.raw.adalante);
if(!mp.isPlaying()) {
mp.start();
}
public void play(View ButtonClicked) {
mp.stop();
mp.release();
//mp = MediaPlayer.create(Menu.this, R.raw.l);
//mp.start();
goToActivity(Game.class);
}
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
//coins
coin.setText(data.getString("coin"));
mp = MediaPlayer.create(Menu.this, R.raw.adalante);
if(!mp.isPlaying()) {
mp.start();
}
//mps.release();
}
In your onResume don't initialise MediaPlayer again and again. It creates new instance every time when you come to onResume. So add a check in onResume like this :
#Override
protected void onResume() {
super.onResume();
if (mp==null)
mp=MediaPlayer.create(MainActivity.this,R.raw.adalante);
if (!mp.isPlaying())
mp.start();
}
and additionally add this for prevention to play when activity goes to onPause
#Override
protected void onPause() {
super.onPause();
mp.pause();
}
Momentarily I have in LogCat "Mediaplayer error (-19,0)" after repeated plays. So the first time(s) I play my app everything is ok, but after a time the Sound doesn't work anymore.
public TextView tw;
MediaPlayer mpButtonKlick;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.app);
tw = (TextView)findViewById(R.id.Text);
tw.setOnClickListener(this);
mpButtonKlick = MediaPlayer.create(this, R.raw.sound);
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mpButtonKlick.start();
you release like this:
mpButtonKlick.release();
mpButtonKlick = null;
It's good practice to also release the MediaPlayer object when you start playing new media to ensure that there is just one instance running.
private void stopMedia(){
mpButtonKlick.release();
mpButtonKlick = null;
}
and when you call start() make sure to first call stopMedia();
stopMedia();
mpButtonKlick.start();
Try this one.
protected void onStop()
{
mediaPlayer.release();
mediaPlayer = null;
}
i am facing some issue in media player when i use as service.
1. If i initialize Media Player Object in Activity as static and further use in service class then its show me this error (-38, 0) , Attempt to perform seekTo in wrong state: mPlayer=0x0, mCurrentState=0 , start called in state 0.
2. If i initialize Media Player Object in Service class and user in activity for more
action its show's me Null Pointer.
public static MediaPlayer mPlayer = null;
play Click Event
Audio_Player_Play.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
if (mPlayer == null)
{
Intent Play_Intent = new Intent(RDS_Singel_Audio.this,
Audio_Player.class);
startService(Play_Intent);
Audio_Player_Play.setVisibility(View.GONE);
Audio_Player_Pause.setVisibility(View.VISIBLE);
} else
{
// Play_Streaming();
mPlayer.seekTo(mPlayer.getCurrentPosition());
mPlayer.start();
Audio_Player_Play.setVisibility(View.GONE);
Audio_Player_Pause.setVisibility(View.VISIBLE);
}
}
});
Pause Click Event
Audio_Player_Pause.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
// Play_Streaming();
// checking is medai player running
Audio_Player_Play.setVisibility(View.VISIBLE);
Audio_Player_Pause.setVisibility(View.GONE);
// checking is audio playing in background
if (mPlayer != null && mPlayer.isPlaying())
{
mPlayer.pause();
/*
* Intent Pause_Intent = new Intent(RDS_Singel_Audio.this,
* Audio_Player.class); stopService(Pause_Intent);
*/
Audio_Player_Play.setVisibility(View.VISIBLE);
Audio_Player_Pause.setVisibility(View.GONE);
}
}
});
OnResume() - OnPause() -OnDistroy()
#Override
protected void onResume()
{
super.onResume();
}
#Override
protected void onPause()
{
// cleanUp();
if (mPlayer != null && mPlayer.isPlaying())
{
mPlayer.release();
mPlayer = null;
}
super.onPause();
}
#Override
protected void onDestroy()
{
cleanUp();
super.onDestroy();
}
private void cleanUp()
{
if (mPlayer != null)
{
mVisualizerView.release();
mPlayer.release();
mPlayer = null;
}
}
Service.Java
public class Audio_Player extends Service
{
private static final String TAG = "MyService";
// public static MediaPlayer mPlayer;
Function f;
RDS_Singel_Audio sa;
MediaPlayer mPlayer;
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onCreate()
{
try
{
sa = new RDS_Singel_Audio();
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG)
.show();
sa.mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
sa.mPlayer.setDataSource(sa.Audio_URL);
sa.mPlayer.prepare();// might take long! (for buffering, etc)
sa.mVisualizerView.link(sa.mPlayer);
sa.mPlayer.start();
sa.addLineRenderer();
sa.mPlayer.setLooping(false); // Set looping
// sa.mPlayer.start();
} catch (Exception e)
{
// TODO: handle exception
Log.d(TAG, "" + e);
}
}
#Override
public void onDestroy()
{
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
super.onDestroy();
if (sa.mPlayer != null)
{
sa.mPlayer.stop();
sa.mPlayer.release();
}
sa.mPlayer = null;
}
#Override
public void onStart(Intent intent, int startid)
{
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
// mPlayer.setDataSource("http://clients.ncrypted.net/riddimapp/images/audio/4/df9919ccb2880933c795f43d735cf9bc.mp3");
}
}
I found some link about same issue but I don't know how solve it.
Well, I see this part of your code, but it is not clear what you are trying to achieve. You are trying to make the player go to its current position, but it is already at that position? You could remove that part then.
// Play_Streaming();
mPlayer.seekTo(mPlayer.getCurrentPosition());
Also, on your onpause you're releasing the player, but not generating it again on your onresume. You can recreate it there with code from that link you provided:
#Override
protected void onResume()
{
super.onResume();
}
#Override
protected void onPause()
{
// cleanUp();
if (mPlayer != null && mPlayer.isPlaying())
{
mPlayer.release();
mPlayer = null;
}
super.onPause();
}
Also, as you seem to be setting the source of the mediaplayer to be an url, you should change the prepare for a prepareAsync in the following part, so that it buffers:
sa.mPlayer.setDataSource(sa.Audio_URL);
sa.mPlayer.prepare();// might take long! (for buffering, etc)
The link you provided already has a lot of suggestions for overcoming these problems above.
Please try the code on that link, especially the ones that suggest prepareAsync and the onprepared listener. Then you can get back here if it does not work.