public class MainActivity extends AppCompatActivity
implements View.OnClickListener {
private MediaPlayer mediaPlayer;
private ImageButton playBtn,previousBtn,forwardBtn,rewindBtn,nextBtn;
private SeekBar seekBar;
private int[] songsName = {R.raw.song1,R.raw.song2,R.raw.song3,R.raw.song4};
private int songPosition=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seekBar = (SeekBar) findViewById(R.id.songProgressBar);
seekBar.setClickable(false);
seekBar.setEnabled(false);
playBtn = (ImageButton) findViewById(R.id.play);
playBtn.setOnClickListener((View.OnClickListener)this);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if(mediaPlayer != null && b){
mediaPlayer.seekTo(i);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
forwardBtn = (ImageButton) findViewById(R.id.forward);
forwardBtn.setOnClickListener((View.OnClickListener)this);
rewindBtn = (ImageButton) findViewById(R.id.rewind);
rewindBtn.setOnClickListener((View.OnClickListener)this);
nextBtn = (ImageButton) findViewById(R.id.next);
nextBtn.setOnClickListener((View.OnClickListener)this);
previousBtn = (ImageButton) findViewById(R.id.previous);
previousBtn.setOnClickListener((View.OnClickListener)this);
subView = (SubtitleView) findViewById(R.id.subs_box);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaplayer) {
Toast.makeText(getApplicationContext(),"Media Player End",Toast.LENGTH_LONG).show();
nextSong();
}
});
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.play:
playSong();
break;
case R.id.forward:
forwardSong(5000);
break;
case R.id.rewind:
rewindSong(5000);
break;
case R.id.next:
if(mediaPlayer !=null)
nextSong();
break;
case R.id.previous:
previousSong();
break;
}
}
public void playSong(){
imageName = (String) playBtn.getTag();
if(imageName.equals("play")) {
playBtn.setTag("stop");
//mediaPlayer = MediaPlayer.create(this, R.raw.chalisa);
Log.d(TAG,""+songPosition);
prepareMediaPlayer(songPosition);
seekBar.setMax(mediaPlayer.getDuration());
seekUpdation();
seekBar.setEnabled(true);
playBtn.setImageResource(R.drawable.stop);
}else{
playBtn.setImageResource(R.drawable.play);
playBtn.setTag("play");
mediaPlayer.pause();
mediaPlayer = null;
seekBar.setProgress(0);
seekBar.setEnabled(false);
subView.setText("");
}
}
public void forwardSong(int time){
if(mediaPlayer != null){
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() + time);
}
}
public void rewindSong(int time){
if(mediaPlayer != null){
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() - time);
}
}
public void nextSong(){
songPosition++;
if(songPosition < songsName.length){
mediaPlayer.pause();
seekBar.setProgress(0);
mediaPlayer.seekTo(0);
mediaPlayer = null;
prepareMediaPlayer(songPosition);
}else{
mediaPlayer.pause();
seekBar.setProgress(0);
mediaPlayer.seekTo(0);
songPosition = 0;
mediaPlayer = null;
prepareMediaPlayer(songPosition);
}
}
public void previousSong(){
songPosition--;
if (songPosition != -1){
mediaPlayer.pause();
seekBar.setProgress(0);
mediaPlayer.seekTo(0);
mediaPlayer = null;
prepareMediaPlayer(songPosition);
}else{
mediaPlayer.pause();
seekBar.setProgress(0);
mediaPlayer.seekTo(0);
songPosition = 0;
mediaPlayer = null;
prepareMediaPlayer(songPosition);
}
}
public void prepareMediaPlayer(int songPosition){
mediaPlayer = MediaPlayer.create(this, songsName[songPosition]);
mediaPlayer.start();
subView.setPlayer(mediaPlayer);
subView.setSubSource(subTitleName[songPosition], MediaPlayer.MEDIA_MIMETYPE_TEXT_SUBRIP);
}
public void seekUpdation() {
if(mediaPlayer != null) {
seekBar.setProgress(mediaPlayer.getCurrentPosition());
myHandler.postDelayed(run, 1000);
}
}
Runnable run = new Runnable() {
#Override public void run()
{
seekUpdation();
}
};
media player on completion not working, not able to print the log also.
My intention is to play the next song once the current song is completed, but i am not able to check the song is completed or not.
In the logcat, it is showing the below warning
W/MediaPlayer-JNI(16888): MediaPlayer finalized without being released.
not showing any error in the logcat......
What may be the issue?
Anything wrong with the MediaPlayer.onCreate?
setOnCompletionListener Always Work after Allocating Media Resources.
remove It From OnCreate Method And
add this listener to you Method PlaySong() after Preparing You Media Player..
It May Work.
public void playSong(){
imageName = (String) playBtn.getTag();
if(imageName.equals("play")) {
playBtn.setTag("stop");
//mediaPlayer = MediaPlayer.create(this, R.raw.chalisa);
Log.d(TAG,""+songPosition);
prepareMediaPlayer(songPosition);
seekBar.setMax(mediaPlayer.getDuration());
seekUpdation();
seekBar.setEnabled(true);
playBtn.setImageResource(R.drawable.stop);
}else{
playBtn.setImageResource(R.drawable.play);
playBtn.setTag("play");
mediaPlayer.pause();
mediaPlayer = null;
seekBar.setProgress(0);
seekBar.setEnabled(false);
subView.setText("");
}
myMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// do what ever you want
}
});
}
And Also This mediaPlayer = MediaPlayer.create(this, songsName[songPosition]); add Only Single time For Selected Song After Play do not create again..
then Again Create When You Are Doing Nextsong.
Related
when i am play audio player and between playing i am play second audio first audio progress bar and timer sink with second audio player and so on . please help on this .**All audio are loaded in recyclerview.**I want audio Player like whatsapp play audio one by one and there progress bar no sink with each other
if (message.getFileType() == MessageFileType.AUDIO)
{
mediaUrl=message.getFile();
Log.d("tag","mediaURL"+mediaUrl);
Uri video = Uri.parse(mediaUrl);
holder.BtnPlayMusic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.BtnPlayMusic.setImageResource(R.drawable.pause_button_red);
if(flag){
mPlayer = MediaPlayer.create(mContext, video);
flag = false;
}
if ( mPlayer.isPlaying())
{
holder.MusicSeekBar.setProgress(0);
mPlayer.stop();
flag=true;
// mPlayer.reset();
holder.BtnPlayMusic.setImageResource(R.drawable.play_button_red);
mPlayer = MediaPlayer.create(mContext, video);
flag = false;
mPlayer.start();
holder.BtnPlayMusic.setImageResource(R.drawable.pause_button_red);
getDurationTimer(holder);
holder.MusicSeekBar.setMax(mPlayer.getDuration()/1000);
getSeekBarStatus(holder);
}
else
{
mPlayer.start();
getDurationTimer(holder);
holder.BtnPlayMusic.setImageResource(R.drawable.pause_button_red);
holder.MusicSeekBar.setMax(mPlayer.getDuration()/1000);
getSeekBarStatus(holder);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
holder.BtnPlayMusic.setImageResource(R.drawable.play_button_red);
flag=true;
holder.MusicSeekBar.setProgress(0);
}}); }}
});
holder.BtnStopMusic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPlayer.stop();
mPlayer.reset();
flag=true;
// mPlayer.reset();
holder.BtnPlayMusic.setImageResource(R.drawable.play_button_red);
}
});
}
//Creating duration time method
public void getDurationTimer(MessageViewHolder holder){
final long minutes=(mPlayer.getDuration()/1000)/60;
final int seconds= (int) ((mPlayer.getDuration()/1000)%60);
holder.MusicTime.setText(minutes+ "0:0"+seconds);
}
//creating a method for seekBar progress
public void getSeekBarStatus(MessageViewHolder holder){
thread=new Thread(new Runnable() {
#Override
public void run() {
int currentPosition = 0;
int total = mPlayer.getDuration();
holder.MusicSeekBar.setMax(total);
while (mPlayer != null && currentPosition < total && flag==false) {
try {
Thread.sleep(1000);
currentPosition = mPlayer.getCurrentPosition();
} catch (InterruptedException e) {
return;
}
holder.MusicSeekBar.setProgress(currentPosition);
}
}
});
thread.start();
holder.MusicSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progress=0;
#Override
public void onProgressChanged(final SeekBar seekBar, int ProgressValue, boolean fromUser) {
if (fromUser) {
mPlayer.seekTo(ProgressValue);//if user drags the seekbar, it gets the position and updates in textView.
progress=ProgressValue;
}
final long mMinutes=(ProgressValue/1000)/60;//converting into minutes
final int mSeconds=((ProgressValue/1000)%60);//converting into seconds
holder.MusicTime.setText(mMinutes+"0:0"+mSeconds);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mPlayer.seekTo(progress);
}
});
}
I would like to add a Repeat Button (onClick) to my Media player. I have the play, pause and stop buttons like in code below. how can i add the Repeat Button for make the music is playing in Media player to be repeated like a loop by a Repeat button clicked from the user.
This is my Media Player Code:
public class Musica extends AppCompatActivity implements Runnable {
private Button pause;
private Button stop;
private SeekBar mseek;
private MediaPlayer mp;
private Thread soundThread;
private Button play;
//list
AdRequest adRequest;
private AdView adView;
ListView listm;
String[] itemname = {
"music 1",
"music 2",
"music 3",
"music 4",
"music 5",
"music 6",
"Lullaby 1",
"Lullaby 2",
"Lullaby 3",
"Lullaby 4",
"Lullaby 5",
};
Integer[] imgid = {
R.drawable.musicon,
R.drawable.musicon,
R.drawable.musicon,
R.drawable.musicon,
R.drawable.musicon,
R.drawable.musicon,
R.drawable.musicon,
R.drawable.musicon,
R.drawable.musicon,
R.drawable.musicon,
R.drawable.musicon,
};
#Override
protected void onDestroy() {
super.onDestroy();
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_musica);
getSupportActionBar().hide();
adView = (AdView)findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.build();
adView.loadAd(adRequest);
adView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
adView.setVisibility(View.VISIBLE);
}
#Override
public void onAdFailedToLoad(int error) {
adView.setVisibility(View.GONE);
}
});
CustomListAdapterMusic adapter = new CustomListAdapterMusic(this, itemname, imgid);
listm = (ListView) findViewById(R.id.listmusic);
listm.setAdapter(adapter);
listm.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String Slecteditem = itemname[+position];
Toast.makeText(getApplicationContext(), Slecteditem, Toast.LENGTH_SHORT).show();
if (position == 0) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.babyone);
mp.start();
}
if (position == 1) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.babytwo);
mp.start();
}
if (position == 2) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.water);
mp.start();
}
if (position == 3) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.ocean);
mp.start();
}
if (position == 4) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.rain);
mp.start();
}
if (position == 5) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.sm);
mp.start();
}
if (position == 6) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.classica);
mp.start();
}
if (position == 7) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.relax6);
mp.start();
}
if (position == 8) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.twinkle7);
mp.start();
}
if (position == 9) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.ninar11);
mp.start();
}
if (position == 10) {
stopPlaying();
mp = MediaPlayer.create(Musica.this.getBaseContext(), R.raw.lullaby9);
mp.start();
}
play = (Button) findViewById(R.id.bplay);
pause = (Button) findViewById(R.id.bpause);
stop = (Button) findViewById(R.id.bstop);
mseek = (SeekBar) findViewById(R.id.seekBar);
setupListeners();
soundThread = new Thread(Musica.this);
soundThread.start();
}
});
}
private void stopPlaying() {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
private void setupListeners()
{
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.start();
}
});
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.pause();
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View currentView) {
mp.stop();
}
});
mseek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
mp.seekTo(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
#Override
public void run() {
int currentPosition = 0;
int soundTotal = mp.getDuration();
mseek.setMax(soundTotal);
while (mp != null && currentPosition < soundTotal) {
try {
Thread.sleep(300);
currentPosition = mp.getCurrentPosition();
} catch (InterruptedException SoundException) {
return;
} catch (Exception otherException) {
return;
}
mseek.setProgress(currentPosition);
}
}
}
below code will help
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
if(is_repeat_enable){
mp.start(); //for repeat only current media file
// or play first media file
}
}
});
i am designing a mediaplayer from scratch so what i am getting stuck in is that when the song finish to play i want to set seekbar to initial value
i know this can be done with
seekBar.setProgress(0)
but this don't work with me and i want the play button to switch back to pause button and if the user play song again than the song will be played normally
here is my code of media player and hope you tell me what is the logic and how to place it
public class MusicPlayerActivity extends AppCompatActivity implements Runnable,
SeekBar.OnSeekBarChangeListener {
ImageView playpause;
SeekBar seekBar;
MediaPlayer mp = null;
int len = 0;
boolean isPlaying = false;
public MusicPlayerActivity() throws IOException {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_player);
String url = getIntent().getExtras().getString("musicurl");
playpause = (ImageView)findViewById(R.id.imageView);
seekBar = (SeekBar)findViewById(R.id.seekBar);
playpause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!isPlaying){
playpause.setImageResource(R.drawable.pause);
mp.pause();
len = mp.getCurrentPosition();
seekBar.setEnabled(false);
}else{
playpause.setImageResource(R.drawable.play);
mp.seekTo(len);
mp.start();
seekBar.setEnabled(true);
}
isPlaying = !isPlaying;
}
});
mp = new MediaPlayer();
try {
mp.setDataSource(url);
} catch (IOException e) {
e.printStackTrace();
}
try {
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
//if(mp.isPlaying()) mp.stop(); mp.release();
mp.start();
seekBar.setMax(mp.getDuration());
new Thread(this).start();
// Toast.makeText(this, mp.getDuration(), Toast.LENGTH_SHORT).show();
}
//if(mp.isPlaying()){}
#Override
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) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
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);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mp.stop();
startActivity(new Intent(this,MainActivity.class));
break;
}
return true;
}
#Override
public void onBackPressed() {
Intent mainActivity = new Intent(Intent.ACTION_MAIN);
mainActivity.addCategory(Intent.CATEGORY_HOME);
mainActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(mainActivity);
}
}
You are not setting the listener : seekbar.setOnSeekBarChangeListener(this)
Add seekbar.setOnSeekBarChangeListener(this); in your onCreate otherwise the onProgressChanged() does not get called.
To reset progress bar look into the following approach:
Set OnCompletionListener on your media player instance. When the media file completes playing, your can carry out the required actions in OnCompletion(MediaPlayer mp) callback function.
Adding following code snippet before mp.start() should work for you.
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
seekBar.setProgress(0); // sets seekbar to initial position.
toggleViews();//implement this function to toggle your play/pause button
}
});
I am trying to play a song by using seek bar listener. But when I try to drag the progress bar then it is playing from beginning of the song. It need to play from that dragged position.
Here is my code:
public class MainActivity extends Activity {
private TextView prairText;
private AssetFileDescriptor descriptor;
private SeekBar seekBar;
private MediaPlayer mp = new MediaPlayer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Keep screen active
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
findViewById(R.id.play_button).setVisibility(View.INVISIBLE);
findViewById(R.id.pauseButton).setVisibility(View.VISIBLE);
init();
// Play prayer
/*if (mp != null) {
mp.start();
}*/
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (mp != null && fromUser) {
mp.seekTo(progress * 1000);
}
}
});
findViewById(R.id.play_button).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mp != null) {
mp.start();
final Handler mHandler = new Handler();
//Make sure you update Seekbar on UI thread
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if(mp != null){
int mCurrentPosition = mp.getCurrentPosition() / 1000;
seekBar.setProgress(mCurrentPosition);
}
mHandler.postDelayed(this, 1000);
}
});
findViewById(R.id.play_button).setVisibility(View.INVISIBLE);
findViewById(R.id.pauseButton).setVisibility(View.VISIBLE);
}
}
});
findViewById(R.id.pauseButton).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mp != null) {
mp.pause();
findViewById(R.id.pauseButton).setVisibility(View.INVISIBLE);
findViewById(R.id.play_button).setVisibility(View.VISIBLE);
}
mp.pause();
}
});
findViewById(R.id.restart_button).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mp != null) {
mp.seekTo(0);
mp.start();
findViewById(R.id.play_button).setVisibility(View.INVISIBLE);
findViewById(R.id.pauseButton).setVisibility(View.VISIBLE);
}
}
});
private void init() {
prairText = (TextView) findViewById(R.id.prairText);
seekBar = (SeekBar) findViewById(R.id.seekBar1);
try {
descriptor = getAssets().openFd("mysong.mp3");
mp.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
mp.prepare();
} catch (Exception e) {
e.printStackTrace();
}
seekBar.setMax(mp.getDuration());
}
How to resolve this issue. Thanks in advance..
Here I did tricks:
Moved MediaPlayer instance to init() method
Changed this line
int mCurrentPosition = mMediaPlayer.getCurrentPosition() / 1000;
to:
int mCurrentPosition = mp.getCurrentPosition();
Changed this line
mp.seekTo(progress * 1000);
to:
mp.seekTo(progress);
Finally working Code will be:
public class MainActivity extends Activity {
private TextView prairText;
private AssetFileDescriptor descriptor;
private SeekBar seekBar;
private MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Keep screen active
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
findViewById(R.id.play_button).setVisibility(View.INVISIBLE);
findViewById(R.id.pauseButton).setVisibility(View.VISIBLE);
init();
// Play song
if (mp != null) {
mp.start();
}
final Handler mHandler = new Handler();
//Make sure you update Seek bar on UI thread
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if(mp != null){
int mCurrentPosition = mp.getCurrentPosition();
seekBar.setProgress(mCurrentPosition);
}
mHandler.postDelayed(this, 1000);
}
});
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (mp != null && fromUser) {
mp.seekTo(progress);
mp.start();
findViewById(R.id.play_button).setVisibility(View.INVISIBLE);
findViewById(R.id.pauseButton).setVisibility(View.VISIBLE);
}
}
});
findViewById(R.id.play_button).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mp != null) {
mp.start();
findViewById(R.id.play_button).setVisibility(View.INVISIBLE);
findViewById(R.id.pauseButton).setVisibility(View.VISIBLE);
}
}
});
findViewById(R.id.pauseButton).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mp != null) {
mp.pause();
findViewById(R.id.pauseButton).setVisibility(View.INVISIBLE);
findViewById(R.id.play_button).setVisibility(View.VISIBLE);
}
mp.pause();
}
});
findViewById(R.id.restart_button).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mp != null) {
mp.seekTo(0);
mp.start();
findViewById(R.id.play_button).setVisibility(View.INVISIBLE);
findViewById(R.id.pauseButton).setVisibility(View.VISIBLE);
}
}
});
private void init() {
mp = new MediaPlayer();
mp.reset();
prairText = (TextView) findViewById(R.id.prairText);
seekBar = (SeekBar) findViewById(R.id.seekBar1);
try {
descriptor = getAssets().openFd("mysong.mp3");
mp.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
mp.prepare();
} catch (Exception e) {
e.printStackTrace();
}
int duration = mp.getDuration();
seekBar.setMax(duration);
}
}
Note: Don't forget to put mysong.mp3 in assets folder
I'm newbie in android programming. I have the following code with a mediaplayer. when the user presses the back key or goes to another activity the sound won't stop.
what's the problem? I have the onDestory method but my problem exists!
public class Elementary1Activity extends Activity implements Runnable, OnClickListener, OnSeekBarChangeListener{
private SeekBar seekBar;
private ImageButton startMedia;
private ImageButton pauseMedia;
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.elementary1);
AudioControl();
}
public void AudioControl(){
seekBar = (SeekBar) findViewById(R.id.seekBarnew2);
startMedia = (ImageButton) findViewById(R.id.playbuttonnew2);
pauseMedia = (ImageButton) findViewById(R.id.pausebuttonnew2);
seekBar.setOnSeekBarChangeListener(this);
startMedia.setOnClickListener(this);
pauseMedia.setOnClickListener(this);
}
public void run() {
int currentPosition= 0;
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) {
pauseMedia.setVisibility(View.VISIBLE);
seekBar.setVisibility(View.VISIBLE);
startMedia.setVisibility(View.INVISIBLE);
if (v.equals(startMedia)) {
if (mp != null && mp.isPlaying()) return;
if(seekBar.getProgress() > 0) {
mp.start();
return;
}
mp = MediaPlayer.create(Elementary1Activity.this, R.raw.e1);
mp.start();
seekBar.setProgress(0);
seekBar.setMax(mp.getDuration());
new Thread(this).start();
}
if (v.equals(pauseMedia) && mp!=null) {
mp.pause();
pauseMedia.setVisibility(View.INVISIBLE);
startMedia.setVisibility(View.VISIBLE);
}
}
#Override
public void onDestroy() {
super.onStop();
mp= MediaPlayer.create(Elementary1Activity.this,R.raw.e1);
if(mp.isPlaying())
{
mp.stop();
mp.release();
finish();
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if(fromUser) mp.seekTo(progress);
}
}
I'd use onPause() event in your Elementary1Activity to manage the music pausing.
Something like:
#Override
public void onPause() {
super.onPause();
if (mp!=null) {
mp.pause();
}
}
You can do two things. If you want that MediaPlayer stop when you push back button and you want to close the app the best option is:
#Override
public void onDestroy(){
if(mp != null){
if(mp.isPlaying()){
mp.stop
}
mp.release();
}
super.onDestroy();
}
And if you want to make that MediaPlayer stop when you change of activity:
#Override
public void onPause(){
if (mp != null && mp.isPlaying()){
mp.pause();
}
}
Apart of that, don't create a new MediaPlayer when you want to close your app.