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);
}
}
Related
I am developing voice app in android. i used google speech recognizer.I want to change the starting tone of google speech and as well as ending tone. I tried ,to add my mp3file but what happens is it just merged to default stating and ending tone. I want to remove the default starting tone ,ending tone and i want to add my mp3 file.
private void enableMediaPlayer() {
MediaPlayer mediaPlayer = new MediaPlayer();
Resources res = null;
float volume = prefs.getFloat(PreferenceConstants.BELL_VOLUME, PreferenceConstants.DEFAULT_BELL_VOLUME);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
MediaPlayer mp = MediaPlayer.create(this,
R.raw.starttone);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.start();
mediaPlayer.setVolume(volume, 100);}
private void onRecordAudioPermissionGranted() {
final Activity activity =ConsoleActivity.this;
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
linearLayout.setVisibility(View.VISIBLE);
}
}, 100);
}
});
try {
enableMediaPlayer();
Speech.getInstance().startListening(progress,this);
} catch (SpeechRecognitionNotAvailable exc) {
Utils.showSpeechNotSupportedDialog(this);
} catch (GoogleVoiceTypingDisabledException exc) {
Utils.showEnableGoogleVoiceTyping(this);
}
}
I tried like above , but mp3 which i customized is merged to the default tone.Please help me to figure out this.Thanks in Advance!!!
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"
I tried almost everything found on the internet and I can't stop the media player once it starts. I'm using broadcast receiver and I'm controlling the media player using SMS. Here is my code.
public class Receiver extends BroadcastReceiver{
String body;
String address;
public static final String SMS_EXTRA_NAME="pdus";
MediaPlayer mp = new MediaPlayer();
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
SharedPreferences obj1=context.getSharedPreferences("mypref", Context.MODE_PRIVATE);
String newstring=obj1.getString("key1", null);
String name=newstring;
Bundle bund=intent.getExtras();
String space="";
if(bund!=null)
{
Object[] smsExtra=(Object[])bund.get(SMS_EXTRA_NAME);
for(int i=0;i<smsExtra.length;i++)
{
SmsMessage sms=SmsMessage.createFromPdu((byte[])smsExtra[i]);
body=sms.getMessageBody().toString();
address=sms.getOriginatingAddress();
if(body.equals("ON"))
{
if(mp.isPlaying())
{
mp.stop();
}
try {
mp.reset();
AssetFileDescriptor afd;
afd = context.getAssets().openFd("file.mp3");
mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
mp.prepare();
mp.start();
mp.setLooping(true);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(body.equals("OFF"))
{
if (mp.isPlaying()==true||mp!=null)
{
try{
mp.stop();
mp.release();
} catch(Exception e){
System.out.println("Exception"+e);
}
}
}
}
}
}
}
The media player is turning on when I send "ON", but it won't turn off. And yes I have given the required permissions in the Manifest file.
The BroadcastReciever it stays alive for around 9 seconds, you should not create big operation in it. However, you can let it start an operation like start acitivty or service and there you play a track or start download a file ...etc
If you want to only start a player and no need for user interaction, I suggest that you start a service and there you play your what you want.
I spent a lot of time studying this problem, and found out that:
The problem here is that I create a MediaPlayer inside a thread that is managed by the IntentService. And at the time of starting playback the thread is no longer valid.
So the way out is:
final Handler handler = new Handler(getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
mediaPlayer.start();
}
});
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
}
, 30 * 1000);
It helped me stop the mediaplayer.
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 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