I am developing a Battery Alarm App. and I want to play music using media-player in every one minute using the Timer and also want to repeat music 2 times within one minute.
This works fine for the first time when Timer calls the *8playAlarm() method** but after one minute when Timer again call the playAlarm() method it plays music only once.
#Override
public void onCreate() {
super.onCreate();
mStartTime=preferencesAlert.getInt("alert",0); // 0 == immediately
mInterval=preferencesInterval.getInt("interval",1); // 1==1 minute
mSongUri=preferencesSongUri.getString("uri","android.resource://"+getPackageName()+"/raw/celesta");
timer = new Timer();
TimerTask hourlyTask = new TimerTask() {
#Override
public void run () {
playAlarm();
}
};
// schedule the task to run starting now and then every time interval...
timer.schedule (hourlyTask,60000*mStartTime, 60000*mInterval);
}
playAlarm() method
private void playAlarm(){
playerAlarm=MediaPlayer.create(getApplicationContext(),Uri.parse(mSongUri));
playerAlarm.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
repeatMax=preferencesRepeat.getInt("repeat",2);
if(repeatMin<=repeatMax){
repeatMin++;
if(playerAlarm!=null && !playerAlarm.isPlaying()) {
mp.seekTo(0);
mp.start();
}
}else {
mp.reset();
mp.release();
}
}
});
playerAlarm.start();
}
I want to play music two times in every minute but it plays only once
the first time works because your repeatMin is still at its first value but after you did not set it at 0 again in your code
repeatMin = first int value; // you have to reinitialize your repeatMin somewhere when the sound
has been played for the second time
I guess because you are executing method in onCreate which calls only once. Might be you can make it in some background service and call it every minute
Related
I've a strange problem with my app.
Every time a button is clicked, I call a method to execute sound.
The code:
public static void executeSound(Context context) {
if (isSoundEnabled(context)) {
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(context, R.raw.button_click);
}
mediaPlayer.start();
}
}
Where isSoundEnabled function verified if user has sound enabled inside app.
Sound is not executed each time I tap button, but after I tap other buttons, and sounds are executed all together.
So happen that I press three different buttons, and three sounds are executed only when I push a button for third time. How can I execute immediately the sound?
I have this problem on lollipop devices (the same code run perfectly on the same device but with kitkat)
Change your execute method to this
public static void executeSound(Context context) {
if (isSoundEnabled(context)) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(mContext, audioUriPath);
mediaPlayer.prepare();
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
}
}
I am able to play an mp3 file using android's MediaPlayer object. But I would like to play between a range of milliseconds for example between 30000 ms to 40000 ms ( 10 seconds only ). How can I achieve this?
Currently the following code is what I have,
private MediaPlayer mPlayer;
public void play() {
try {
mPlayer = MediaPlayer.create(getApplicationContext(), R.raw.mp3_file);
if (mPlayer != null) {
int currentPosition = mPlayer.getCurrentPosition();
if (currentPosition + 30000 <= mPlayer.getDuration()) {
mPlayer.seekTo(currentPosition + 30000);
} else {
mPlayer.seekTo(mPlayer.getDuration());
}
mPlayer.start();
}
}
catch(Exception e) {
}
}
Any help is greatly appreciated. Thank you!
You can use the method:
public int getCurrentPosition ()
to obtain the current time in milSeconds maybe inside a Handler that runs every 1000 milSeconds and tests to see:
if(mPlayer.getCurrentPosition() >= (mPlayer.getDuration + 40000));
Dont forget to release the media file when you're done using it:
public void release();
mPlayer.release();
Releases resources associated with this MediaPlayer object. It is
considered good practice to call this method when you're done using
the MediaPlayer. In particular, whenever an Activity of an application
is paused (its onPause() method is called), or stopped (its onStop()
method is called), this method should be invoked to release the
MediaPlayer object, unless the application has a special need to keep
the object around. In addition to unnecessary resources (such as
memory and instances of codecs) being held, failure to call this
method immediately if a MediaPlayer object is no longer needed may
also lead to continuous battery consumption for mobile devices, and
playback failure for other applications if no multiple instances of
the same codec are supported on a device. Even if multiple instances
of the same codec are supported, some performance degradation may be
expected when unnecessary multiple instances are used at the same
time.
The best approach is to use a Handler to time the stopping of the playback. Start the player and then use the Handler's postDelayed to schedule the execution of a Runnable that will stop the player. You should also start the player only after the initial seek completes. Something like this:
public class PlayWord extends Activity implements MediaPlayer.OnSeekCompleteListener {
Handler mHandler;
MediaPlayer mPlayer;
int mStartTime = 6889;
int mEndTime = 7254;
final Runnable mStopAction = new Runnable() {
#Override
public void run() {
mPlayer.stop();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final TextView tv = new TextView(this);
tv.setText("Playing...");
setContentView(tv);
mHandler = new Handler();
mPlayer = MediaPlayer.create(this, R.raw.nicholas);
mPlayer.setOnSeekCompleteListener(this);
mPlayer.seekTo(mStartTime);
}
#Override
public void onDestroy() {
mPlayer.release();
}
#Override
public void onSeekComplete (MediaPlayer mp) {
mPlayer.start();
mHandler.postDelayed(mStopAction, mEndTime - mStartTime);
}
}
Note also that the MediaPlayer.create method you are using returns a MediaPlayer that has already been prepared and prepare should not be called again like you are doing in your code.on the screen. I also added a call to release() when the activity exits.
Also, if you want to update the UI when the seek completes, be aware that this method is usually called from a non-UI thread. You will have to use the handler to post any UI-related actions.
I'm copied this from: Android: How to stop media (mp3) in playing when specific milliseconds come?
I am working in an app with chronometer that when an user press the button a sound playing, and when the time at 10:00 other sound playing, but i can't play the last one, Here the code:
btIniciar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (click){
chronometer.setBase(SystemClock.elapsedRealtime() + tempoQuandoParado);
chronometer.start();
Toast.makeText(GerenciaPartida.this, "The match begin!", Toast.LENGTH_LONG).show();
MediaPlayer musica = MediaPlayer.create(GerenciaPartida.this, R.raw.apito);
musica.start();
}
***Here i want play another sound at 10:00, when the time's over***
}
});
You can try to use timer.
Timer myTimer = new Timer();
When you start chronometer start the timer like in example below. 600000 - is 10 minutes in milliseconds.
myTimer.schedule(new TimerTask() {
#Override
public void run() {
//play sound
}
}, 600000);
I want to increase the sound by one level up in each and every 5 seconds meanwhile the sound clip plays.Below is my code:-
MediaPlayer player;
player=MediaPlayer.create(this, R.raw.alarm);
player.setLooping(true);
Is there any method in which i can track each and every 5 minutes when over.How can i achieve this?
I think you can achieve this with java TimerTask, this is an example code, not tested but should work with no big modifications :
Basically you start a task every 5 seconds, in the run() function of the TimerTask you level up your sound level, and when you reach the maxSoundLevel you call cancel() to stop the task.
//Put this in global
int REFRESH_INTERVAL = 5 * 1000; //5 seconds
int maxSoundLevel = 10; // Number of loop to get to max level
int curSoundLevel = 0; //Start at 0 volume level
//Put this after you started the sound
Timer timer = new Timer();
timer.scheduleAtFixedRate(new MyTimerTask(), 0, REFRESH_INTERVAL);
//Put this after your method
private class MyTimerTask extends TimerTask{
public void run() {
if(curSoundLevel < maxSoundLevel)
{
float logLevel = (float)(Math.log(maxSoundLevel-curSoundLevel)/Math.log(maxSoundLevel));
yourMediaPlayer.setVolume(1-logLevel);
curSoundLevel ++;
}
else {
this.cancel();
}
}
}
If you have more questions feel free to ask me.
I am using a media player instance to play a music file.I want to play the song for certain time then stop playing.I'm using a thread with counter decrementing but some how tis not workin properly.
you have to use handler for that
try this
in your onCreate use this
//start media player
mp.start();
mTimer.sendMessageDelayed(new Message(),5*10000);
create a class in you activity class as
private MusicTimer mTimer = new MusicTimer();
private class MusicTimer extends Handler
{
#Override
handleMessage(Message msg)
{
onTimerExpire();
}
public void onTimerExpire()
{
//stop player here
}
}
make media player object member variable this will play that for five seconde then stop nthat
this is something you can do.. Play with media player normally and at the same Time initialise a handler and call its postDelayed method with interval you want.. and inside it stop the MEdia player.. Something like this..
new Handler().postDelayed(new Runnable(){
//stop playing
}, 400);