Hi all here is my code:
final ImageView imageView = (ImageView) findViewById(R.id.Image7);
imageView.setImageResource(mFullSizeIds[position]);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(Audio.this,mAudio[position]);
mp.start();
}
});
Now this code works fine to play the audio when the user taps the image, however when I want to exit this activity and go to a different activity, the audio track is still playing, even when I press the home key the audio is still playing. How can I prevent this from happening?
Is there a way to stop the track from playing when the user taps the image again or presses the back/home button?
Add
#Override
public void onBackPressed ()
{
if (mp != null)
mp.stop();
super.onBackPressed();
}
and
#Override
public void onPause ()
{
if (mp != null)
{
mp.pause();
mp.stop();
}
super.onPause();
}
Create an onStop in the activity and make mp a class variable although I always create/prefer media player helper class for this sort of stuff. Then call mp.stop()/pause on onStop.
private MediaPlayer mp = null;
#Override
public void onStop() {
super.onStop();
if (mp != null) {
mp.stop();
}
}
then you just create it with removing the MediaPlayer before mp:
mp = MediaPlayer.create(Audio.this,mAudio[position]);
Override the onBackPressed method, and stop your MediaPlayer object, which is mp.
Related
MediaPlayer player = MediaPlayer.create(context, R.raw.background);
player.start();
The Code above is part of the current code.
When I press the home key, MediaPlayer does not stop playing.
#Override
public boolean onKeyDown(int KeyCode, KeyEvent event)
{
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (KeyCode == KeyEvent.KEYCODE_BACK) {
System.exit(0);
return true;
}
}
return super.onKeyDown(KeyCode, event);
}
I've implemented the code shown above, for when you press the Back key.
Do you think that the above code is correct? Appreciate any help.
Just implement below methods for this,
#Override
protected void onPause() {
super.onPause();
if(player != null)
player.stop();
}
#Override
protected void onStop() {
super.onStop();
if(player != null)
player.stop();
}
#Override
protected void onDestroy() {
super.onDestroy();
if(player != null)
player.stop();
}
Please try with this solution:
public class PlayaudioActivity extends Activity {
private MediaPlayer mp;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.button1);
Button b2 = (Button) findViewById(R.id.button2);
final TextView t = (TextView) findViewById(R.id.textView1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.far);
mp.start();
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.beet);
mp.start();
}
});
}
private void stopPlaying() {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
}
For more information, please read this post: Android MediaPlayer Stop and Play
If your media player is running on the activity you created, you can call player.stop() in onStop() method.
Edit:
Your implementation is OK, but it only overrides the back key only. You have to override the home key also to stop the player on pressing the home key. (but, use onStop() instead as it calls when the user interface is hidden.)
Do not use System.exit(), use finish() instead.
If you using finish() method (which destroys the activity), make sure that you have released the MediaPlayer resources by calling player.release() and nullifying the player. (i.e. player = null)
I have a loop-all button and a stop button. Both buttons work fine while I'm still on the page. The problem is when I hit the loop-all button, it plays a series of audio files as it is supposed to, but when I leave the page (i.e. hit the phone's back button) and come back to the page, the audio doesn't stop! I hit the stop button, but it does nothing. The only way to stop it is to go into task manager and end the program. It seems to me that the reference of mp2 gets lost once I leave the page...Does anyone have any suggestions on how to fix this. Any help would be appreciated. Here is the code:
public class OneVoc extends ActionBarActivity {
private ListView lv;
private MediaPlayer mp;
private MediaPlayer mp2;
int[] myAudio = {R.raw.v_1100, R.raw.v_1101, R.raw.v_1102, R.raw.v_1103, R.raw.v_1104, R.raw.v_1105,
R.raw.v_1113, R.raw.v_1106, R.raw.v_1107, R.raw.v_1108, R.raw.v_1109, R.raw.v_1110, R.raw.v_1112,
R.raw.v_1114, R.raw.v_1115, R.raw.v_1116};
int mCompleted = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.one_voc);
Button btnLoop = (Button) findViewById(R.id.button1);
Button btnStop = (Button) findViewById(R.id.button2);
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mp2 != null) {
if (mp2.isPlaying()) {
mp2.setOnCompletionListener(null);
mp2.stop();
}
mp2.reset();
mp2.release();
mp2 = null;
}
}
});
btnLoop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mp2 = MediaPlayer.create(getBaseContext(), myAudio[0]);
mp2.setOnCompletionListener(new OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp2)
{
mCompleted++;
mp2.reset();
if (mCompleted < myAudio.length)
{
try
{
AssetFileDescriptor afd = getResources().openRawResourceFd(myAudio[mCompleted]);
if (afd != null)
{
mp2.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mp2.prepare();
mp2.start();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
else if (mCompleted == myAudio.length)
{
mCompleted =0;
try
{
AssetFileDescriptor afd = getResources().openRawResourceFd(myAudio[mCompleted]);
if (afd != null)
{
mp2.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mp2.prepare();
mp2.start();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
else
{
mCompleted=0;
mp2.release();
mp2 = null;
}
}
});
mp2.start();
}
});
try overriding onbackpressed method
#Override
public void onBackPressed()
{
// code here to stop and finish()
super.onBackPressed();
}
I think it's an It's an Audio buffer issue, memory is loaded in audio buffer and persist later on,finish() might not help u.
When u press back button on an android button it simply calls the finish() for current activity, while when u press home button it calls onPause(),
You need to override onBackPressed() method, and before line super.onbackPressed();
Put your code to stop playing.
When u go to TakMgr it simply get's the PID refer to ur App process and kills the process.
Which is like System.exit(0); or android.os.process.kill(getMyPid());
Which simply ends ur app which u do not want.
Can you pause your mp in onPause() and restart it in onResume()?
Maybe you want also to store in savedInstance at which point you were!
Hope it's helpful
when you back press the activity just stop the mediaplayer and free the resources and finish the activity.that's it..!
#Override
public void onBackPressed()
{
btnStop.performClick();
super.onBackPressed();
}
I am making a new android sound application. I made a clickable button to play sound when I click on it. But I also want it to stop playing sound when I click for the second time. That part works fine now here is the problem, when I click again on button to play sound again, it doesn't play it, Media player is completely stopped. I was looking on forums but I can't seem to find an answer that could help me.
Here is my Activity:
MediaPlayer mpButtonClick1;
MediaPlayer mpButtonClick2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.prvi);
final MediaPlayer mpButtonClick1 = MediaPlayer.create(this, R.raw.spalshm);
final MediaPlayer mpButtonClick2 = MediaPlayer.create(this, R.raw.splashs);
Button dugme = (Button) findViewById(R.id.dugme);
dugme.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mpButtonClick1.isPlaying()) {
mpButtonClick1.stop();
mpButtonClick1.reset();
}
else {
mpButtonClick1.start();
}
}
});
When I try to write mpButtonClick1.prepare(); I get error Unhandled Exception Type IOE exception
Try to use pause instead of stop.
Reason: if you pause the MediaPlayer, then you can resume it later. However, if you use stop, almost any other method won't work and you will have to prepare the MediaPlayer again (or create a new one).
More info: here and here
PS: don't forget to release the memory when you finish using the resources.
Try this:
You should use only one mediaplayer object
public class PlayaudioActivity extends Activity {
private MediaPlayer mp;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.button1);
Button b2 = (Button) findViewById(R.id.button2);
final TextView t = (TextView) findViewById(R.id.textView1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.far);
mp.start();
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.beet);
mp.start();
}
});
}
private void stopPlaying() {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
}
Change your class with below code:
remove reset();.
init well all components:
MediaPlayer mpButtonClick1;
MediaPlayer mpButtonClick2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.prvi);
mpButtonClick1 = MediaPlayer.create(this, R.raw.spalshm);
mpButtonClick2 = MediaPlayer.create(this, R.raw.splashs);
Button dugme = (Button) findViewById(R.id.dugme);
dugme.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mpButtonClick1.isPlaying()) {
mpButtonClick1.stop();
}
else {
mpButtonClick1.start();
}
}
});
You're calling mpButtonClick1.reset() after mpButtonClick1.stop() - don't do that:
if (mpButtonClick1.isPlaying()) {
mpButtonClick1.stop();
mpButtonClick1.reset(); //<--------- calling reset(), remove this line
}
The docs for reset() say:
Resets the MediaPlayer to its uninitialized state. After calling this method, you will have to initialize it again by setting the data source and calling prepare().
Remove mpButtonClick1.reset() and it should work.
Keep in mind that MediaPlayer works as a state machine, which means that if you call methods in the wrong order, you'll get problems. Please read about MediaPlayer here and here.
Hey please use following
for stop -> media player
mp.seekTo(0);
mp.pause();
again for start just call
mp.start();
In my experience when I need to play multiple times and I may need to stop one play to start another play, (like in the case of multiple buttons), I just create another player, making sure that I release the resources for the previous one. To stop just use
mediaPlayer.stop();
But for play use something like this (adapt the logging to your specific needs) to create/recreate your player:
private boolean createMediaPlayer()
{
if (mediaPlayer!=null)
{
if(mediaPlayer.isPlaying())
{
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer=null;
}
}
mediaPlayer = new MediaPlayer();
mediaPlayer.setVolume(1f, 1f);
try
{
mediaPlayer.setAudioStreamType(Interop.PRIMARY_STREAM);
mediaPlayer.setDataSource(m_soundFile);
mediaPlayer.prepare();
return true;
// Interop.logDebug(TAG + "-loadAudio: SUCCESS" + m_soundFile);
} catch (Exception e)
{
Interop.logError(TAG + "-LoadAudio for Clic Sound: audioPlayer prepare failed for current file: " + m_soundFile);
Interop.logError(TAG + "-Exception: " , e);
return false;
}
}
and than use
if (createMediaPlayer())
mediaPlayer.start();
this will ensure proper release of the resources used by the media player.
A simple solution is to Use pause instead of stop and the seek to the beginning of the song.
I know that this question is quite old but recently while learning Android, I also got stuck at this point and found a very simple solution which I'd like to share with everyone.
Instead of trying to stop or reset the media, you can just seek back to the starting position.
mediaPlayer.seekTo(0);
For reference, I am also posting my code below:
public class MainActivity extends AppCompatActivity {
MediaPlayer mp;
public void play(View view) {
mp.start();
}
public void pause(View view) {
mp.pause();
}
public void stop(View view) {
// this seeks to the beginning of the file
mp.seekTo(0);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = MediaPlayer.create(this, R.raw.sample_audio);
}
}
I have a mediaplayer in my activity and with the mediaplayer I have a seekbar that I am updating via a thread handler. The way I run the thread handler is like so:
Runnable run = new Runnable() {
#Override
public void run() {
seekUpdation();
}
};
public void seekUpdation() {
if(mp.isPlaying()){
this.seekbar.setProgress(mp.getCurrentPosition());
this.seekHandler.postDelayed(run, 2);
}
}
I call this whenever the user hits the play button and then the seekbar keeps getting updated while the mediaplayer is in playing. SO this works great, but when I hit the Back button when the mediaplayer is playing I then get an illegalstateexception because I am doing the following:
#Override
public void onBackPressed(){
super.onBackPressed();
if (mr != null)
mr.release();
if (mp != null){
mp.pause();
mp.stop();
mp.release();
}
}
See I figured by pausing the mediaplayer this would trigger the thread to stop, but it hasn't worked. Does anyone have any other suggestions?
I am new to android. i know that we can not access control of activity from service. But i want to change the ImageSource of the button whenever i call the method of the service.
here is the method that i created in service :
public void play()
{
if (mp.isPlaying()) {
if (mp != null) {
mp.pause();
// Changing button image to play button
btnPlay.setImageResource(R.drawable.btn_play); // not allowed
}
} else {
// Resume song
if (mp != null) {
mp.start();
// Changing button image to pause button
btnPlay.setImageResource(R.drawable.btn_pause); // not allowed
}
}
}
in activity i am calling this method on play button click. How to implement this functionality in service. how can i change the image source of the button. Please clear my doubt. Thanx.
Create custom event object for those events and register your activity as listener.
Note: Don't forget to unregister it because it might cause a memory leak.
Try this code
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
public static MainActivity mThis;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mThis = this;
}
}
public void play()
{
Button btnPlay=((Button)MainActivity.mThis.findViewById(R.id.btnPlay));
if (mp.isPlaying()) {
if (mp != null) {
mp.pause();
// Changing button image to play button
btnPlay.setImageResource(R.drawable.btn_play);
}
} else {
// Resume song
if (mp != null) {
mp.start();
// Changing button image to pause button
btnPlay.setImageResource(R.drawable.btn_pause);
}
}