I am attempting to play a notification sound once every two seconds. My code is as follows:
final Handler myHandler = new Handler();
mMediaPlayer = new MediaPlayer();
final Runnable mMyRunnable = new Runnable()
{
#Override
public void run()
{
try
{
mMediaPlayer.setDataSource(getBaseContext(), getAlarmUri(alarm_number));
final AudioManager audioManager = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0)
{
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
}
catch (IOException e)
{
}
}
};
mMediaPlayer.setOnCompletionListener(new OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
myHandler.postDelayed(mMyRunnable, 2000);
}
});
myHandler.post(mMyRunnable);
When the code executes, the notification sound plays once and then I get an IllegalStateException at the line mMediaPlayer.setDataSource(...
I have no idea why.
NO! You should use a Timer which will execute a TimerTask for a repeat rate that you choose:
Timer timer = new Timer();
TimerTask task = new TimerTask()
{
#Override
public void run()
{
// Do your work here
}
};
timer.schedule(task, 'DELAY_FOR_EXECUTION', 'TIME_TO_WAIT');
example:
`//timer.schedule(task, 0, 5000);`
This will run immediatly, every 5 secs
Related
I am developing a phone finder application, and i would like to implement the remote ringing function... I already write a code for MediaPlayer, but when I tested it, the alarm is ringing non-stop (maybe the time for the alarm song is too long but i wanna make it rings for a particular period only)... I hope to set a timer for the alarm ringing like let say ringing for 10 seconds, but no idea on how to achieve it... Need help from you guys... thanks...
MediaPlayer mp = new MediaPlayer();
mp = MediaPlayer.create(RingerActivity.this, R.raw.alarm);
try {
mp.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (Exception e) {
Toast.makeText(this, e.getMessage() , Toast.LENGTH_SHORT).show(); }
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
You could use a Runnable and a Handler to stop the MediaPlayer after 10 seconds.
Handler h = new Handler();
Runnable stopPlaybackRun = new Runnable() {
public void run(){
mp.stop();
mp.release();
}
};
h.postDelayed(stopPlaybackRun, 10 * 1000);
Android
media player in timer
MediaPlayer buzzer; //Outside the method
public void BuzzerSound(){
buzzer=MediaPlayer.create(MainActivity.this, R.raw.buzzer_sound);
Thread timer= new Thread(){
public void run(){
try{
buzzer.start();
buzzer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}catch(Exception e){
e.printStackTrace();
}
}
};
timer.start(); }
I am writing a code for playing a song which is near about 3 min long in background and at the same time I want to show a slideshow of images in the front. There are two problems I am facing:
1. The song stops after 15 seconds.
2. the slideshow of images starts only after song stops.
Please help..thanks in advance...
My code is like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mygame);
final Handler mHandler = new Handler();
try {
AssetFileDescriptor afd = getAssets().openFd("AudioFile.mp3");
MediaPlayer player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor());
player.prepare();
player.start();
} catch (Exception e) {
e.printStackTrace();
}
final Runnable mUpdateResults = new Runnable() {
public void run() {
animateandSlideShow();
}
};
int delay = 15000;
int period = 20000;
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
mHandler.post(mUpdateResults);
}
}, delay, period);
}
I am working on Android , I am creating a player for audio songs. I want to play a song only for just 30 seconds. After that, player must be closed. It should be start again, if I press START button again.
This is the code for creating a media player:
MediaPlayer mediaPlayer = new MediaPlayer();
public void songPreview(String songURL){
try{
mediaPlayer=new MediaPlayer();
mediaPlayer.setDataSource(songURL);
mediaPlayer.prepare();
mediaPlayer.start();
} catch(Exception ex){
ex.printStackTrace();
}
}
Please suggest me what code should I use to play my song only for 30 seconds after that it will stop, and if I want to play again then I have to press start button.
Note: Please provide me logic to stop media player after 30 second.
Thank you in advance.
use countdownTimer to complete your goal in which you can set countdown timer till 30 second manually. when countdown finish process it will go to finish method and execute finish method code
::
CountDownTimer cntr_aCounter = new CountDownTimer(3000, 1000) {
public void onTick(long millisUntilFinished) {
mp_xmPlayer2.start();
}
public void onFinish() {
//code fire after finish
mp_xmPlayer2.stop();
}
};cntr_aCounter.start();
private void playSoundForXSeconds(final Uri soundUri, int seconds) {
if(soundUri!=null) {
final MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(Settings.this, soundUri);
mp.prepare();
mp.start();
}catch(Exception e) {
e.printStackTrace();
}
Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
public void run() {
try {
mp.stop();
}catch(Exception e) {
e.printStackTrace();
}
}
}, seconds * 1000);
}
}
This method jumps to the end of the track after a given time and allows the native onCompleted callback do its work. You'd obviously need to expand the code to handle any pause events fired before the playback completes.
private static void startMedia(final MediaPlayer mediaPlayer, #Nullable Integer previewDuration) {
mediaPlayer.start();
if( previewDuration != null) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mediaPlayer.seekTo(mediaPlayer.getDuration());
}
}, previewDuration);
}
}
I am starting a sound from a background service (IntentService), which is triggered by a system alarm (the thread of the service will most often be dead when the sound ends).
The relevant code is this:
Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (alert == null)
alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
MediaPlayer mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(this, alert);
final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) != 0) {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
mMediaPlayer.setLooping(false);
mMediaPlayer.prepareAsync();
mMediaPlayer.start();
}
This stuff works fine, but every time the sound is played, I get this in log cat:
WARN/MessageQueue(7508): Handler{482f97e0} sending message to a Handler on a dead thread
I think this could be due to a callback to the background thread when the sound is finished, or my repeated use of a media player before having finalized the previous one. Any ideas?
Very old question, but #Alex' xkcd link convinced to me answer it anyway.
I have a very similar situation, and was able to achieve the desired result by instantiating the MediaPlayer through a Runnable. In my case an IntentService calls an ongoing Service, which is responsible for the media playback. My solution looks as follows (relevant code only):
public class HelperService extends Service {
public void play() {
Thread thread = new Thread(new Runnable() {
public void run() {
soundStart();
}
});
thread.start();
}
private void soundStart() {
try {
AssetFileDescriptor afd = mContext.getResources().openRawResourceFd(R.raw.sound);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
mp.reset();
return false;
}
});
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// do stuff
}
});
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Scenario
I have a problem that starts to drive me nuts. In one activity I have the following scenario. On create:
- create a GPS Listner
- create a Location Listener
- Start GPS listner and location listener
- Start a asyncTask that downloads a map from the web / or load it from cache
- play a wav file which is a raw resource, very small (around 63 Kilo) which is short, basically it says: "Let's head to the start point" and it makes visible a textview for 10 seconds.
Problem
Rarely the sound gets play fully. Sometimes I hear only "Let's head", sometimes "Let's head to the star", sometimes no play at all. It's like something else is blocking the sound. I moved the sound in its own thread but still no success:
Code
private void ShowTextPlayVoice(String message, int soundResId)
{
txtProceed.setText(message);
txtProceed.setVisibility(View.VISIBLE);
final int soundId = soundResId;
Handler splashHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
txtProceed.setVisibility(View.INVISIBLE);
break;
}
super.handleMessage(msg);
}
};
Message msg = new Message();
msg.what = 0;
splashHandler.sendMessageDelayed(msg, 10000);
Thread thread = new Thread() {
public void run() {
MediaPlayer mp = MediaPlayer.create(ctx, soundId);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}
};
thread.start();
}
Thank you all for help.
After some tries, here is a working solution
private MediaPlayer mediaPlayer = new MediaPlayer();
private void ShowTextPlayVoice(String message, int soundResId)
{
txtProceed.setText(message);
txtProceed.setVisibility(View.VISIBLE);
Handler splashHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
txtProceed.setVisibility(View.INVISIBLE);
break;
}
super.handleMessage(msg);
}
};
Message msg = new Message();
msg.what = 0;
splashHandler.sendMessageDelayed(msg, 10000);
new SoundTask().execute(soundResId);
}
protected class SoundTask extends AsyncTask<Integer, Void, Void>
{
#Override
protected Void doInBackground(Integer... params)
{
AssetFileDescriptor afd = ctx.getResources().openRawResourceFd(params[0]);
try
{
//final MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.reset();
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
mediaPlayer.prepare();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer arg0) {
mediaPlayer.seekTo(0);
mediaPlayer.start();
});
}
});
afd.close();
}
catch (Exception e) {
}
return null;
}
}