i have a problem. my media player doesn't stop even activity has stopped. so i confuse why media player doesn't stop. media player immediately playing until a mp3 finish. here my code
public class Isi_TakbiratulIhram extends Activity{
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.isitakbiratulihram);
ImageButton iftitah1=(ImageButton) findViewById (R.id.takbiratulihram1);
iftitah1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
go();
}
public void go(){
if(mp != null ){
mp.stop();
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.seekTo(0);
mp = null;
}
else {
mp=MediaPlayer.create(Isi_TakbiratulIhram.this, R.raw.iftitah1);
mp.start();
}
}});
thanks for help
Override Activity onPause() method for stoping Media Player :
#Override
public void onPause(){
super.onPause();
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
You can override onPause() or onStop() and stop it there:
#Override protected void onPause()
{
if(mp != null ){
mp.stop();
// mp.release(); ??
}
super.onPause();
}
When user stops an Activity the state of activity can go to onStop() state,SO it is required to stop any ongoing tasks like music playing here.So in android programming it's required go handle all states like onRestart(), onResume(), onStop(), onPause(), onDestroy() for proper functioning of the program.
For handling stopping and restarting of activity visit :
http://developer.android.com/training/basics/activity-lifecycle/stopping.html
Related
When i launch app and lock the screen without clicking(playing audio) button and after when i unlock the screen and press the play button i am getting Exception.
public class DemoActivity extends Activity {
MediaPlayer mp;
Button btn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
mp = MediaPlayer.create(DemoActivity.this,R.raw.mus);
btn = (Button) findViewById(R.id.btnOk);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (btn.getText().toString().equalsIgnoreCase("play")) {
mp.start();
btn.setText("Pause");
} else if (btn.getText().toString().equalsIgnoreCase("pause")) {
mp.pause();
btn.setText("Play");
}
}
});
#Override
public void onPause() {
super.onPause();
if (mp.isPlaying()) {
mp.start();
} else {
mp.release();
}
}
#Override
protected void onRestart() {
try {
if (mp.isPlaying() && mp!=null) {
mp.start();
} else {
mp.release();
}
} catch (IllegalStateException e) {
e.printStackTrace();
}
super.onRestart();
}
#Override
protected void onDestroy() {
super.onDestroy();
mp.release();
}
}
Here is my code please try to give me a solution.
Thanks in advance
please try call mp.prepare() before every mp.start(). You are getting the error because the mp is not yet ready for your use, and calling start() on that will cause IllegalStateException.
I'm trying to create an app that play a certain audio file, that was previously recorded, when I press a button or shake my phone. Here is my code.
public class Reproduzir extends Activity implements SensorEventListener{
MediaPlayer player = new MediaPlayer();
SensorManager sensor;
#Override
protected void onCreate(Bundle savedInstanceState ){
super.onCreate(savedInstanceState);
sensor= (SensorManager) getSystemService(SENSOR_SERVICE);
setContentView(R.layout.reproduzir);
Button reproduzir = (Button) findViewById(R.id.reproduzir);
reproduzir.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
play();
}
});
Button fechar= (Button) findViewById(R.id.fechar);
fechar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (player.isPlaying()) {
player.stop();
player.release();
}
finish();
}
});
}
public void play(){
try {
player.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/2cp.3gp");
player.prepare();
player.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onStart(){
super.onStart();
sensor.registerListener(this,sensor.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_FASTEST);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if(event.values[0]>10.2
||event.values[1]>10.2
||event.values[2]>10.2){
play();
}
}
}
My problem is that when I run it, I can only play it once. If I press the button a second time or shake it again, it does nothing. Can anyone help?
The easy fix is to simply add player.reset() in your play() method BEFORE calling player.setDataSource(...).
You can only call setDataSource(...) once without resetting the player. It is legal to call reset() in any state however (even if the player isn't yet initialized).
In other words, even if it's the first time you've called play() it is OK to use the following code in your play() method...
try {
player.reset();
player.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/2cp.3gp");
player.prepare();
player.start();
}
// Your catch blocks here
Try to use:
mediaPlayer.reset()
after:
mediaPlayer.stop()
instead of release.
You can only set data source once.
in you code everytime the user presses the button you do this:
player.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/2cp.3gp");
whice is wrong.
you need to setdata and prepare once and play how many times you want.
like so:
put this in you onCreate:
try {
player.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/2cp.3gp");
player.prepare();
player.start();
in the onClick(View v), just have :
player.play();
Long story short - you have to use:
setLooping(true)
For more information about the Media Player check the post below. Take in mind the state diagram
http://developer.android.com/reference/android/media/MediaPlayer.html
MediaPlayer State diagram
I use media player to play sounds on my application. It works just fine.
I am playing sound on a separated thread. Even thought, part of the sound plays before activity appear.
I tried to play sound onCreate method. it didn't work. onStart and
onResume. it has some problems. it plays every time activity resumed.
sometimes while I am not even touching the device!
What is the best way to play sound after activity appears?
public boolean played = false;
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (!played)
Settings.playSound(dvd.titleImageName.replace("png", "mp3"), this);
played = true;
}
public static MediaPlayer mp = null;
public static void playSound(String fileName, Context c)
{
//MediaPlayer mp = MediaPlayer.create(c, resId);
if (mp!=null)
{
mp.stop(); //error
mp.reset();
mp.release();
}
mp = new MediaPlayer();
AssetFileDescriptor descriptor;
try {
descriptor = c.getResources().getAssets().openFd("sounds/" + fileName);
mp.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
mp.prepare();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (mp == null) return;
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
}
});
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
}
});
mp.setOnVideoSizeChangedListener(new OnVideoSizeChangedListener() {
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
// TODO Auto-generated method stub
}
});
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
mp.start();
}
}).start();
}
Your played variable only works while activity is alive. If it gets killed, played doesn't retain. For example, rotate your device an you'll hear sound playing again.
save state (played) in onSavedInstanceState bundle and restore it in onCreate
Play in in OnCreate or onResume
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.
i'm newbie, i'm tried to make play audio play and stop for 1 button only, but i'm in trouble now.
if i touch a button when audio is playing, it doesn't stop, even playing audio again and make a double sound.
here's my code
public class ProjectisengActivity extends Activity{
ImageButton mainkan;
MediaPlayer mp;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test2);
mainkan=(ImageButton)findViewById(R.id.imageButton1);
mainkan.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
go();
}
});
public void go(){
mp=MediaPlayer.create(ProjectisengActivity.this, R.raw.test);
if(mp.isPlaying()){
mp.stop();
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.seekTo(0);
}
else {
mp.start();
}
i'm create for android 3.0 (HoneyComb)
try below code in go function....
public void go() {
if(mp == null) {
mp=MediaPlayer.create(ProjectisengActivity.this, R.raw.test);
}
if(mp.isPlaying()){
mp.stop();
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.seekTo(0);
}
else {
mp.start();
}
}
It is simple, you should follow these steps to achieve this.
In your test2.xml create two buttons name start and stop.
Set the android:visibility attribute gone of stop button in xml file.
Now in your activity get the id of these two buttons and write the code for
starting and stopping of media player.
Set the visibility attribute gone on start click and visible of stop button,
follow its opposite on stop click.
I think you have wrong this line :
mp=MediaPlayer.create(ProjectisengActivity.this, R.raw.test);
You create new instance every time user clicks the button, so it's never playing and starts again. Put this line into onCreate rather than go()
Try also this,
public class MainActivity extends Activity {
MediaPlayer mPlayer;
int flag = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button mButton = (Button) findViewById(R.id.button1);
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (flag == 0) {
Log.v("Inside if", "Success" + "");
mPlayer = MediaPlayer.create(getApplicationContext(),
R.raw.sample);
mPlayer.start();
flag++;
} else {
Log.v("Inside else", "Success" + "");
mPlayer.stop();
mPlayer.release();
flag = 0;
}
}
});
}
}