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);
Related
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 try to play a song when I receive an SMS,
when I receive 2 SMS then song play simultaneously.
Thanks for your help
Runnable stopPlayerTask = new Runnable(){
#Override
public void run() {
mPlayer.stop();
}
};
if(mPlayer.isPlaying()){
mPlayer.stop();
}else{
mPlayer.seekTo(startime);
mPlayer.start();
mPlayer.setLooping(true);
}
Handler handler = new Handler();
handler.postDelayed(stopPlayerTask, endtime);
If I understand your intended use of the mediaPlayer correctly, you should be requesting Audio Focus from the Android system. Therefore, you can have the mediaplyer wrapped in a service that implements "AudioManager.OnAudioFocusChangeListener". If you implement the callbacks correctly for your application, then the song should never play simultaneously.
Note that Android requires an API level of at least 8 to use AudioManager
Here is the reference in the documentation for this:
http://developer.android.com/guide/topics/media/mediaplayer.html
Use mPlayer.reset(); after mPlayer.stop();
This will reset all initialization ex: track URI etc so will have to set again track URI before mPlayer.start();
This will let only new and one track play at a time and will stop & reset previous track completely.
I start the mediaplayer to play a piece of music in a thread and I'm wondering why mediaplayer can continue working even the thread is already dead. Here is the example:
public class MusicThread extends Thread {
MediaPlayer mp;
public MusicThread(Context context) {
mp = MediaPlayer.create(context, R.raw.music);
}
#Override
public void run() {
mp.start();
Log.d("MusicThread", "mp started");
}
}
Then inside the activity:
MusicThread musicThread = new MusicThread(this);
musicThread.start();
Here is my confusion:
After musicThread.start(), the music begins. Also, the thread completes becasue we can see the log generated by Log.d(...) in LogCat and we can see the false returned by musicThread.isAlive().
I have the reference to musicThread such that it won't be GC immediately when it finishes.
But what about the mediaplayer? It continues working but the thread which it resides has died already. It seems that it's in a weird state in this case. Is it still working in musicThread? If yes, why and how? If not, where it is?
mp.start() is not a blocking call. So your thread won't wait until playing is finished. mp.start() call returns immediately. You don't even need a separate thread to call it.
PS : If you want to get a callback when the playing is finished just use setOnCompletionListener. Once the playing is completed, public void onCompletion(MediaPlayer mp) will be called
Need to play some .wav file but only some part of it (from start).
For example I have test.wav file and it is 10 seconds I want to play only 0-5 seconds.
I try to use seekTo method but it doesn't help my app was crashed.
AssetFileDescriptor afd = context.getResources().openRawResourceFd(R.raw.test);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_SYSTEM);
mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mMediaPlayer.setOnPreparedListener(mOnPreparedListener);
mMediaPlayer.setOnCompletionListener(mMediaPlayerCompletionListener);
mMediaPlayer.seekTo(5000);
mMediaPlayer.prepare();
You could just stop playing after set amount of time (5 sec in your case). There are many ways to do that, one could be:
final Handler handler = new Handler();
//create a runnable that will be called to stop playback
final Runnable runnable = new Runnable() {
#Override
public void run() {
//stop playback, make sure mMediaPlayer is declared as a field
//in the class where it's used
mMediaPlayer.stop();
}
};
//post a job for handler do be done in 5 seconds
handler.postDelayed(runnable, 5 * 1000);
you can't seek before you call prepare, i am not sure whether you can do that before actually calling MediaPlayer.play() to be honest you need to check that up but for sure prepare goes first.
I'm using a MediaController and MediaPlayer together, to create a simple audio player in Android, taken from an example I found here on this site.
However, after much search I could not find the solution to my problem: the progress/seek bar doesn't refresh while the music is playing. It just updates itself when something on the MediaController is pressed (Play/Pause, forward, etc).
Any easy fix for this that I'm not getting ?
NOTE: My MediaController is declared in XML, and my MediaController.MediaPlayerControl methods just make use of the MediaPlayer class.
Mediaplayer provides a method getCurrentPosition() you can put this in a thread to continously update the progressbar.
public int getCurrentPositionInt(){
if (player != null)
return player.getCurrentPosition();
else
return 0;
}
Create a Thread or CountDownTimer to continuously update the seekbar :
seekBar.setMax((getCurrentPositionInt() / 1000));
OR
MediaController.MediaPlayerControl mp;
mp.seekTo((getCurrentPositionInt() / 1000))
Im Sorry for my English!
you are showing the controller before the music player is ready.
You need to notify your activity from the controller when it is ready.
public void onPrepared(MediaPlayer mp) {
mp.start();
Intent onPreparedIntent = new Intent("MP_READY");
LocalBroadcastManager.getInstance(activity).sendBroadcast(onPreparedIntent);
}
Then you need to create a BroadcastReceiver in your activity and override his onReceive method to show the controller.
private BroadcastReceiver mpReadyReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context c, Intent i) {
controller.show(0);
}
};
You also need to register the receiver in your activity`s onResume().
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mpReadyReceiver,
new IntentFilter("MP_READY"));
}
Now try to call controller.show only when it is necesary.
Be careful not creating more than one controller instance