this is my code, i am almost certain the problem is with the while loop.
public void start(View view) {
int currentPosition = 0;
player = MediaPlayer.create(this, R.raw.sound);
player.start();
int total = player.getDuration();
progressBar.setProgress(0);
progressBar.setMax(player.getDuration());
while (player != null && currentPosition < total) {
// try {
// Thread.sleep(500);
currentPosition = player.getCurrentPosition();
// } catch (InterruptedException e) {
// return;
// } catch (Exception e) {
// return;
// }
progressBar.setProgress(currentPosition);
}
}
public void stop(View view) {
player.stop();
}
whether or not i have the sleep intervals my result is the same; the sound starts playing but i cant stop it, and the progress bar doesn't move.
i would appreciate some help
I used this code in my app for using seekBar with MediaPlayer. It implements Runnable to keep the seekBar updating as the music plays. Take a look at the code:
public class MainActivity extends Activity implements Runnable,
OnClickListener, OnSeekBarChangeListener {
private SeekBar seekBar;
private Button startMedia;
private Button stopMedia;
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seekBar = (SeekBar) findViewById(R.id.seekBar1);
startMedia = (Button) findViewById(R.id.button1);
stopMedia = (Button) findViewById(R.id.button2);
startMedia.setOnClickListener(this);
stopMedia.setOnClickListener(this);
seekBar.setOnSeekBarChangeListener(this);
seekBar.setEnabled(false);
}
public void run() {
int currentPosition = mp.getCurrentPosition();
int total = mp.getDuration();
while (mp != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekBar.setProgress(currentPosition);
}
}
public void onClick(View v) {
if (v.equals(startMedia)) {
if (mp == null) {
mp = MediaPlayer.create(getApplicationContext(), R.raw.song2);
seekBar.setEnabled(true);
}
if (mp.isPlaying()) {
mp.pause();
startMedia.setText("play");
} else {
mp.start();
startMedia.setText("pause");
seekBar.setMax(mp.getDuration());
new Thread(this).start();
}
}
if (v.equals(stopMedia) && mp != null) {
if (mp.isPlaying() || mp.getDuration() > 0) {
mp.stop();
mp = null;
startMedia.setText("play");
seekBar.setProgress(0);
}
}
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
try {
if (mp.isPlaying() || mp != null) {
if (fromUser)
mp.seekTo(progress);
} else if (mp == null) {
Toast.makeText(getApplicationContext(), "Media is not running",
Toast.LENGTH_SHORT).show();
seekBar.setProgress(0);
}
} catch (Exception e) {
Log.e("seek bar", "" + e);
seekBar.setEnabled(false);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
Thanks to: Sridhar Kulkarni
Related
Please I want to know how to set my MediaPlayer to playback continuously without stopping when activity screen rotates? The challenge I'm having now is that when playing is in progress and I happen to tilt the screen the music stops and will require another action to have it play again.
this is the part of which plays the music in my Activity
// setting up media players
public void play(View v) {
if (player == null) {
//then here, I sent the position of the chosen song in the intent extras.
//the get back the extra
int position = 0;
try{
position=getIntent().getIntExtra("soundfile",0);
}catch (Exception e)
{
e.printStackTrace();
}
String fileToPlay="song_"+position;
player = MediaPlayer.create(this, position);
Toast.makeText(this, "Hymn Tune Playing", Toast.LENGTH_SHORT ).show();
soundSeekBar = (SeekBar) findViewById(R.id.seekBar1);
soundSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser){
player.seekTo(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
soundSeekBar.setProgress(player.getCurrentPosition());
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
player.getCurrentPosition();
}
});
player.setLooping(true);
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
}
});
}
player.start();
Toast.makeText(this, "Playing Continues...", Toast.LENGTH_SHORT ).show();
soundThread = new Thread(this);
soundThread.start();
}
public void pause(View v) {
if (player != null) {
player.pause();
Toast.makeText(this, "Hymn Tune Paused", Toast.LENGTH_SHORT ).show();
}
}
public void stop(View v) {
stopPlayer();
}
private void stopPlayer() {
if (player != null) {
player.release();
player = null;
Toast.makeText(this, "Hymn Tune Stoped", Toast.LENGTH_SHORT ).show();
}
}
#Override
protected void onStop() {
super.onStop();
stopPlayer();
}
#Override
public void run() {
int currentPosition = 0;
int soundTotal = player.getDuration();
soundSeekBar.setMax(soundTotal);
while (player != null && currentPosition < soundTotal){
try {
Thread.sleep(300);
currentPosition = player.getCurrentPosition();
}
catch (InterruptedException soundException){
return;
}
catch (Exception otherException){
return;
}
soundSeekBar.setProgress(currentPosition);
}
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
You must move your playback code to background service, as those will run constantly while activity is stopped and restarted during tilting. Check out extensive guide to services here
https://developer.android.com/guide/components/services
I'm new to Android programming. I followed a mediaplayer tutorial but I'm now trying to make it more advance, the only problem is thats not working as expected.
When the song is finished it should start playing the next song, but doesn't update my seekbar (only updates Max) and it makes my buttons crash my app. I tried many things but can't fix it myself. If i press the next button however (before music track ends) the buttons and seekbar work.
What I'm want is my seekbar to reset for the new song and go again, and i want my buttons to work after the onCompletion next song.
Here my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
btPlay = (ImageButton) findViewById(R.id.btPlay);
btNxt = (ImageButton) findViewById(R.id.btNxt);
btPv = (ImageButton) findViewById(R.id.btPv);
btPlay.setOnClickListener(this);
btNxt.setOnClickListener(this);
btPv.setOnClickListener(this);
sb = (SeekBar) findViewById(R.id.seekBar);
updateSeekBar = new Thread() {
#Override
public void run() {
int TotalDuration = mp.getDuration();
int currentPosition = 0;
while (currentPosition < TotalDuration) try {
sleep(500);
currentPosition = mp.getCurrentPosition();
sb.setProgress(currentPosition);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
if (mp != null) {
mp.stop();
mp.release();
}
Intent i = getIntent();
Bundle b = i.getExtras();
mySongs = (ArrayList) b.getParcelableArrayList("songlist");
position = b.getInt("pos", 0);
u = Uri.parse(mySongs.get(position).toString());
mp = MediaPlayer.create(getApplicationContext(), u);
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
try {
mp.stop();
mp.reset();
position = (position + 1) % mySongs.size();
u = Uri.parse(mySongs.get(position).toString());
mp = MediaPlayer.create(getApplicationContext(), u);
sb.setMax(mp.getDuration());
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
mp.start();
sb.setMax(mp.getDuration());
updateSeekBar.start();
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mp.seekTo(seekBar.getProgress());
}
});
}
#Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.btPlay:
if (mp.isPlaying()) {
mp.pause();
btPlay.setImageResource(R.drawable.play);
} else {
mp.start();
btPlay.setImageResource(R.drawable.pause);
}
break;
case R.id.btNxt:
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
position = (position + 1) % mySongs.size();
u = Uri.parse(mySongs.get(position).toString());
mp = MediaPlayer.create(getApplicationContext(), u);
mp.start();
sb.setMax(mp.getDuration());
}
} catch (Exception e) {
e.printStackTrace();
}
break;
case R.id.btPv:
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
position = (position - 1 < 0) ? mySongs.size() - 1 : position - 1;
u = Uri.parse(mySongs.get(position).toString());
mp = MediaPlayer.create(getApplicationContext(), u);
mp.start();
sb.setMax(mp.getDuration());
}
} catch (Exception e) {
e.printStackTrace();
}
break;
default:
break;
}
}
}
Errors (in android Monitor):
java.lang.IllegalStateException
i want to reset the seekbar to start position once the music is played and button showing "play"...The problem with the code is that the seek bar stays at the end position after its done playing the music and button still shows "pause"...
Here's my code
ekdanta.java
public class ekdanta extends AppCompatActivity implements Runnable, View.OnClickListener,SeekBar.OnSeekBarChangeListener {
TextView tv4;
Button b9, b10,but19;
int count = 0;
MediaPlayer play;
SeekBar seek_bar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ekdanta);
tv4 = (TextView) findViewById(R.id.textView9);
tv4.setTextSize((float)21.5);
tv4.setText(Html.fromHtml(getString(R.string.thirteen)));
b9 = (Button) findViewById(R.id.b9);
b10 = (Button) findViewById(R.id.b10);
seek_bar = (SeekBar) findViewById(R.id.seekBar);
seek_bar.setOnSeekBarChangeListener(this);
seek_bar.setEnabled(false);
but19 = (Button) findViewById(R.id.button19);
but19.setOnClickListener(this);
}
public void run() {
int currentPosition= play.getCurrentPosition();
int total = play.getDuration();
while (play!=null && currentPosition<total) {
try {
Thread.sleep(1000);
currentPosition= play.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seek_bar.setProgress(currentPosition);
}
}
public void onClick(View v) {
if (v.equals(but19)) {
if (play == null) {
play = MediaPlayer.create(getApplicationContext(), R.raw.ekadanta);
seek_bar.setEnabled(true);
}
if (play.isPlaying()) {
play.pause();
but19.setText("Play");
} else {
play.start();
but19.setText("Pause");
seek_bar.setMax(play.getDuration());
new Thread(this).start();
}
}
}
#Override
protected void onPause() {
if(play!=null){
play.stop();
}
super.onPause();
}
public void increase(View inc) {
count++;
if (count == 1) {
tv4.setTextSize(25);
} else if (count == 2) {
tv4.setTextSize(30);
} else if (count >= 3) {
count = 3;
tv4.setTextSize(40);
}
}
public void decrease(View dec) {
count--;
if (count <= 0) {
tv4.setTextSize((float)21.5);
count = 0;
}
if (count == 1) {
tv4.setTextSize(25);
} else if (count == 2) {
tv4.setTextSize(30);
} else if (count == 3) {
tv4.setTextSize(40);
}
}
#Override
public void onProgressChanged(SeekBar seek_bar, int progress, boolean fromUser) {
try{
if(play.isPlaying()||play!=null){
if (fromUser)
play.seekTo(progress);
}
else if(play==null){
Toast.makeText(getApplicationContext(),"First Play", Toast.LENGTH_SHORT).show();
seek_bar.setProgress(0);
}
}
catch(Exception e){
Log.e("seek bar",""+e);
seek_bar.setEnabled(false);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
MediaPlayer has got onCompletionListener(), you can use that. Your code with handlers is not too reliable, it would be better to refactor it.
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// do whatever you want
}
});
I have a thread named runner. I want to stop this thread onBackPressed but this is not happening. Here is the code:
public class StrobeLightConfig extends Activity {
Camera cam;
StrobeRunner runner;
Thread bw;
CheckBox strobe;
private boolean isFlashOn;
private boolean hasFlash;
private Parameters params;
private MediaPlayer mp;
VerticalSeekBar skbar, skbaroff;
ToggleButton togglebutton;
public final Handler mHandler = new Handler();
public final Runnable mShowToastRunnable = new Runnable() {
public void run() {
showMessage();
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
skbar = (VerticalSeekBar) findViewById(R.id.SeekBar01);
strobe = (CheckBox) findViewById(R.id.checkBox1);
togglebutton = (ToggleButton) findViewById(R.id.ToggleButton01);
skbaroff = (VerticalSeekBar) findViewById(R.id.SeekBar02);
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
turnOnFlash();
strobe.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (buttonView.isChecked()) {
cam.release();
Toast.makeText(getApplicationContext(), "Released 1", 0)
.show();
} else {
cam.release();
Toast.makeText(getApplicationContext(), "Released 2", 0)
.show();
}
}
});
runner = StrobeRunner.getInstance();
runner.controller = this;
if (runner.isRunning) {
} else {
try {
if (cam == null) {
cam = Camera.open();
}
} catch (RuntimeException ex) {
togglebutton.setEnabled(false);
TextView t = (TextView) findViewById(R.id.TextViewHW2);
t.setText(R.string.nocamera);
Toast.makeText(getApplicationContext(),
"Error connecting to camera flash.", Toast.LENGTH_LONG)
.show();
return;
}
}
togglebutton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
if (strobe.isChecked()) {
if (togglebutton.isChecked()) {
turnOnStrobe();
} else {
turnOffStrobe();
}
} else {
if (isFlashOn) {
// turn off flash
turnOffFlash();
} else {
----------------- runner.requeststop working here---------------------
turnOnFlash();
}
}
}
});
skbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
runner.delay = progress;
}
});
skbaroff.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
runner.delayoff = progress;
}
});
}
private void getCamera() {
if (cam == null) {
try {
cam = Camera.open();
params = cam.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
}
}
/*
* Turning On flash
*/
private void turnOnFlash() {
if (!isFlashOn) {
togglebutton.setChecked(true);
cam = Camera.open();
params = cam.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(params);
cam.startPreview();
isFlashOn = true;
strobe.setEnabled(false);
}
}
private void turnOffFlash() {
if (isFlashOn) {
togglebutton.setChecked(false);
params = cam.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
cam.setParameters(params);
cam.stopPreview();
cam.release();
isFlashOn = false;
strobe.setEnabled(true);
}
}
private void turnOnStrobe() {
if (!isFlashOn) {
strobe.setEnabled(false);
bw = new Thread(runner);
bw.start();
}
}
private void turnOffStrobe() {
if (isFlashOn) {
runner.requestStop = true;
strobe.setEnabled(true);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onRestart() {
super.onRestart();
}
public void showMessage() {
String err = runner.errorMessage;
runner.errorMessage = "";
if (!err.equals("")) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, err, duration);
toast.show();
}
ToggleButton togglebutton = (ToggleButton) findViewById(R.id.ToggleButton01);
togglebutton.setChecked(false);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
if (strobe.isChecked()) {
turnOffStrobe();
} else {
if (isFlashOn) {
----------------- runner.requeststop needs to work here---------------------
turnOffFlash();
finish();
moveTaskToBack(true);
}
}
}
}
However if I write
runner.requestStop = true;
strobe.setEnabled(true);
at the place of TurnoffStrobe in the oncreate (not onBackPressed), its working. What can I do to have runner.requeststop working outside onCreate.?
Try
your_thread.isInterrupted(); inside onBackpress()
I have created demo for media player in Android.I'm facing the problem while start to run my application.When my app is run song is playing but not playing the full song it just start and immediately finish means it just start activity and immediately goes to resume() state.And when song is get over the i again restart my activity song is not playing from beginning it start from middle.I'm facing this problem last 1 week and i don't understand how to solve it .Please can any one help me.Here is my code.Thanks in advanced.
public class Audio_Activity extends Activity
{
private MediaPlayer mp = null;
PhoneStateListener phListener;
int length;
SharedPreferences prefs;
ImageView imgVw;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.audio);
init();
imgVw.setImageResource(R.raw.teddy_two);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences. Editor prefsEdit = prefs.edit();
mp=MediaPlayer.create(Audio_Activity.this,R.raw.issaq_tera_by_vishu);
Log.e("Song is playing","in Mediya Player ");
mp.start();
mp.setLooping(false);
System.out.println("Media Plyer Is Start !!!");
prefsEdit.putBoolean("mediaplaying", true);
prefsEdit.commit();
btnChapter.setEnabled(false);
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
// TODO Auto-generated method stub
mp.stop();
System.out.println("Media Plyer Is Complete !!!");
//mp.release();
prefsEdit.putBoolean("mediaplaying", false);
prefsEdit.commit();
btnChapter.setEnabled(true);
System.out.println("Music is over and Button is enable !!!!!!");
}
});
PhoneStateListener phoneStateListener = new PhoneStateListener()
{
#Override
public void onCallStateChanged(int state, String incomingNumber)
{
if (state == TelephonyManager.CALL_STATE_RINGING)
{
if(mp!=null)
{
setPlayerButton(true, false, true);
if(mp.isPlaying())
{
mp.pause();
}
}
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
} else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
}
super.onCallStateChanged(state, incomingNumber);
}
};
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(mgr != null)
{
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
private void setPlayerButton(Boolean play, Boolean pause, Boolean stop){
btnStartStop.setEnabled(play);
if(play==true)
btnStartStop.setEnabled(true);
else
btnStartStop.setEnabled(false);
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
#Override
public void onPause()
{
super.onPause();
SharedPreferences. Editor prefsEdit = prefs.edit();
boolean isPlaying=prefs.getBoolean("mediaplaying",false);
if(isPlaying)
{
int position = mp.getCurrentPosition();
Log.e("Current ","Position -> " + position);
prefsEdit.putInt("mediaPosition", position);
prefsEdit.commit();
}
}
#Override
protected void onResume()
{
super.onResume();
System.out.println("Activity is Resume !!!");
boolean isPlaying=prefs.getBoolean("mediaplaying",false);
if(isPlaying)
{
int position = prefs.getInt("mediaPosition", 0);
mp.seekTo(position);
mp.start();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
super.onStop();
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
if(mp!= null)
{
if(mp.isPlaying())
{
mp.pause();
System.out.println("Media Player is Pause/Stop click on Back button on Emulator!!!");
}
}
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
the starting from middle of the song problem is because you store the current progress of song in SharedPreferences and then at onResume() you start the player from the progressed position that stored at SharedPreferences
It's better to register for OnPreapredListener via MediaPlayer.setOnPreaparedListener and after preparation you start your media playback.
Official guide:
http://developer.android.com/guide/topics/media/mediaplayer.html
Please try to use bellow code.
void play() {
mediaPlayer = MediaPlayer.create(
getApplicationContext(), R.raw.keytone);
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
}
private void pause()
{
mediaPlayer.release();
}