how to play a sound for 5 seconds - android

i want to play a sound for 5 seconds but the code which i am using is playing the sound infinitely.
My code is
final MediaPlayer player = new MediaPlayer();
AssetFileDescriptor afd = this.getResources().openRawResourceFd(R.raw.hangout_ringtone);
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
player.setAudioStreamType(AudioManager.STREAM_ALARM);
player.setLooping(true);
player.prepare();

Try to remove this line from your code
player.setLooping(true);

Use a Runnable with a delay to stop your audio.
postDelayed(new Runnable() {
public void run() {
//Code to stop your sound
}
}, 5000);

Create a new handler to post a delay for when to stop.
mMediaPlayer.start();
// wait 5 sec... then stop the player.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mMediaPlayer.stop();
}
}, 5000);//millisec.

Related

How to play a tone repeatedly every 2 seconds?

My Question is about how i can play tone named beep_e.mp3 repeatedly with delay of 2 seconds.I am playing tone when i get value below 100 or above 200.So when value is i get 250 every time i want to play tone regularly but with delay of 2seconds.I tried below code but it is not working.plz help me in this.
` Handler handler=new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if(mp.isPlaying())
{
mp.stop();
}
try {
mp.reset();
AssetFileDescriptor afd;
afd = getAssets().openFd("beep_e.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.start();
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}` }
},2000);

When using MediaPlayer, sometimes it does not sound

for recording file output, I use MediaPlayer.
usually, When I button clicked, start media file.
but, sometime not sound play.
/MediaPlayer: mediaplayer went away with unhandled events
W/MediaPlayer-JNI: MediaPlayer finalized without being released
at first I think before the voice file is finished, when clicked button occur this problem.
but even if I press the button repeatedly, sometime not sound play.
source.
player = new MediaPlayer();
player.reset();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
player.reset();
AssetFileDescriptor assetFileDescriptor =
getApplicationContext().getResource().openRawResourceFd(R.raw.sound);
player.setDataSource(assetFileDescriptor.getFileDescriptor(),
assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
player.prepare();
player.start();
} catch (Exception e) {
e.printStackTrace();
}
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
if (player != null) {
player.stop();
player.release();
}
}
});
How to fix sometimes not sound play when i button clicked?
thanks.
There's no reason to call MediaPlayer.release() if it will be used again, as calling reset() will release all the memory & codecs that are in use.
init:
player = new MediaPlayer();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.reset();
}
});
Handling button clicks:
void onButtonClicked() {
player.reset();
AssetFileDescriptor assetFileDescriptor =
getApplicationContext().getResource().openRawResourceFd(R.raw.sound);
player.setDataSource(assetFileDescriptor.getFileDescriptor(),
assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
player.prepare();
player.start();
}

How to play/stop default sound automatically in Android?

I want to play and stop the default sound with following rules:
If the sound is not playing, let play it in 10 seconds.
If the sound is playing, let stop it and play at the first position.
Based on these above rules, I design a function as follows:
public MediaPlayer mp =null;
public void playDefaultSound(){
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
mp = MediaPlayer.create(getApplicationContext(), notification);
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(getApplicationContext(), notification);
}
mp.start();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
mp.stop();
mp.release();
}
}, 10000);
} catch (Exception e) {
e.printStackTrace();
}
}
But sometime I still listen two sound are playing (in case of the first sound play and I call the playDefaultSound() function again). Do you think is it correct to delete the mp = MediaPlayer.create(getApplicationContext(), notification); bellow mp.release()? How could I correct the function to satisfy these rules? Thanks all
final MediaPlayer mp = new MediaPlayer();
public void playDefaultSound(){
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
try {
if (mp != null && mp.isPlaying()) {
mp.seekTo(0);
} else {
mp.reset();
mp.setDataSource(getApplicationNotification(), notification);
mp.start();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
mp.stop();
mp.release();
}
}, 10000);
} catch (Exception e) {
e.printStackTrace();
}
}
P.S. - Always see the state diagram or lifecycle of things whenever stuck.
Ref : [Android Media Player State Diagram][1]
[1]: https://developer.android.com/reference/android/media/MediaPlayer.html#StateDiagram "MediaPlayer State Diagram"

Android how can play song for 30 seconds only in mediaPlayer

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);
}
}

Android mediaplayer causing "dead thread" message

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();
}
}
}

Categories

Resources