I am trying to write a small android app for my son. The idea is to make ringtone start to play on button click and it should be stoped by clicking on the other button. Something like you click a button to start a calling and another button to answer to it.
What I manage to do is to make the first button to ring to work by the following code:
CallLukas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), notification);
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
}
});
However, the second button to stop the ringtone does not work as it suppose to. I use the following code:
Incoming.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mp.isPlaying()) {
mp.stop();
mp.release();
}
}
});
It stops the ringtone but in the same time makes the app to crash.
What would be the right way to stop the previously activated ringtone?
Thnak you...
This answer should help you.
I believe the problem is you're creating multiple MediaPlayer objects. Also try to use .reset() instead of .stop().
The solution for my issue was making the MediaPlayer as a service.
I have created a new Java class to extend the service class. Here is the code for it:
public class RingtoneService extends Service {
private MediaPlayer mp;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mp = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
mp.setLooping(true);
mp.start();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
mp.stop();
}
}
Then I have updated my MainActivity class with the fallowing code:
CallLukas.setOnClickListener(this);
Incoming.setOnClickListener(this);
#Override
public void onClick(View v) {
if (v == CallLukas){
startService(new Intent(this, RingtoneService.class));
}else if (v == Incoming) {
stopService(new Intent(this, RingtoneService.class));
}
}
The code basically sets the OnClickListener on my buttons and starts the service if one is clicked and stops the service if the other is clicked.
The final steps are to add the newly created service to the AndroidManifest file. It needs to be added inside the <application> tag.
<application
<service android:name=".RingtoneService"></service>
</application>
The completed instruction on how to implement this can be found here:
https://www.youtube.com/watch?v=p2ffzsCqrs8&t=315s
Related
I would like to turn the sound on and off by clicking on the button.
public void onClick(View v) {
buttonSound.setBackgroundResource(R.drawable.soundan);
CommonMethod.soundplayer.stop();
//buttonSound.setBackgroundResource(R.drawable.soundaus);
//CommonMethod.soundplayer.setVolume(0,0);
}
This is the CommonMethod
public class CommonMethod {
public static MediaPlayer soundplayer;
public static void Soundplayer(Context ctx,int raw_id)
{
soundplayer = MediaPlayer.create(ctx,raw_id);
soundplayer.setLooping(true);
soundplayer.setVolume(100, 100);
}
}
It stops the sound by clicking but it doesn't turn it on again
I got this Code too, but its the same problem
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
if (counter % 2 == 0) {
buttonSound.setBackgroundResource(R.drawable.soundan);
CommonMethod.soundplayer.setVolume(100,100);
}
else
{
buttonSound.setBackgroundResource(R.drawable.soundaus);
CommonMethod.soundplayer.setVolume(0,0);
}
}
Please see this piece of documentation
There are some useful ballots like:
A MediaPlayer object must first enter the Prepared state before
playback can be started.
or
Once in the Stopped state, playback cannot be started until prepare()
or prepareAsync() are called to set the MediaPlayer object to the
Prepared state again.
You can pause it instead of stooping if you stop then you have prepaid it again then it will play rather then you can pause and play`` again from same position.
if(mPlayer.isPlaying()){
mPlayer.pause();
} else {
mPlayer.start();
}
understand the below diagram.
i'am trying to develop an app in android with 2 buttons. the first button must pause and restart the music if you state is on or off. but this code doesn't works, why?
public class MainActivity extends Activity {
MediaPlayer sound;
Boolean pulsado=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
sound=MediaPlayer.create(getBaseContext(),R.raw.gaitas);
sound.setLooping(true);
sound.start();
}
public void boton1(View v){
if(pulsado==false){
sound.stop();
pulsado=true;
}else{
sound.reset();
}
}
public void boton2(View v){
Intent i=new Intent(this,ActivityB.class);
startActivity(i);
}
Android documentation says about MediaPlayer.reset() -- 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().
For your purpose, you could use MediaPlayer.create(...) again to setDataSource to the MP and prepare it for playing.
if (pulsado == false) {
sound.stop();
sound.reset();
pulsado = true;
} else {
sound = MediaPlayer.create(getBaseContext(), R.raw.song);
sound.setLooping(true);
sound.start();
pulsado = false;
}
If you are looking for pausing the song, you could rather call sound.pause() and in else block simple sound.start() should be enough to resume the song.
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);
}
}
Hi!
I have a service that should be playing an audio file when it is started from an activity (by a click on the button). The problem is though, the service won't start when i click the required button in my activity.
Service class (with imports and some other methods omitted):
public class ClockService extends Service {
MediaPlayer myMediaPlayer;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
myMediaPlayer = MediaPlayer.create(this, R.raw.audio);
myMediaPlayer.setLooping(true);
}
#Override
public void onStart(Intent intent, int startid) {
myMediaPlayer.start();
}
}
The activity it is called from:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startService(new Intent(getBaseContext(), ClockService.class));
}
});
}
}
I've struggled with it for an hour already, and i can't see what's wrong.
u got problem on below code line.u cant use this for context inside service.u need to pass context of mainactivity to service to get mediaplayer instance inside service.
myMediaPlayer = MediaPlayer.create(this, R.raw.audio);//wrong one
The problem is how you started the service
Change this line to startservice(new intent(mainactivity.this, clockservice));
here is a link you can refer to.
In our app we have a MusicService. Currently, it works perfectly fine in terms of playing music and stopping it, but that is from starting and stopping the service. We are calling it in other methods, but mp.pause() is crashing unless it is surrounded by a null checker. But when it checks for nulls it doesn't work at all. We had all this working earlier, but we started reformatting the way were doing it, because on Android 4.0 (ICS) the Music kept playing randomly even when we stopped it, but thats not the point anyway.
public class MusicService extends Service {
public static MediaPlayer mp;
#Override
public IBinder onBind(final Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mp = MediaPlayer.create(this, R.raw.title_music);
mp.setLooping(true);
mp.setVolume(200, 200);
}
#Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
mp.start();
return 1;
}
#Override
public void onStart(final Intent intent, final int startId) {
}
public IBinder onUnBind(final Intent arg0) {
return null;
}
public static void onStop() {
mp.stop();
mp.release();
}
public static void onPause() {
if (mp!=null) {
mp.pause();
}
}
public static void onResume() {
if (mp!=null) {
mp.start();
}
}
#Override
public void onDestroy() {
mp.stop();
mp.release();
super.onDestroy();
}
#Override
public void onLowMemory() {
mp.stop();
mp.release();
}
}
We are using this to start the service in another activity:
intent = new Intent(this, MusicService.class);
startService(intent);
Without a log I can't really say with 100% certainty this is the issue, but it would appear that the pause method is being called while mp is in an invalid state. I suggest you change your onPause method so that it reads like so.
public static void onPause() {
if (mp!=null) {
if (mp.isPlaying())
mp.pause();
}
}
This will check to see if it is actually playing and will work for any state it is in, except an error state. At least according to the documentation.