I want to add a fast forward button on my code but I did not find how.
this is my code I hope someone will help me.
MusicPlayer.java:
imagePlaypause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mediaPlayer.isPlaying()){
handler.removeCallbacks(updater);
mediaPlayer.pause();
imagePlaypause.setImageResource(R.drawable.playbutton);
}else {
mediaPlayer.start();
imagePlaypause.setImageResource(R.drawable.pausebutton);
updateSeekBar();
}
}
});
new Content().execute(getIntent().getStringExtra("downloadlink"));
textTotalDuration.setText(milliSecondsToTimer(mediaPlayer.getDuration()));
playerSeekBar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
SeekBar seekBar = (SeekBar) view;
int playPosition = (mediaPlayer.getDuration() / 100) * seekBar.getProgress();
mediaPlayer.seekTo(playPosition);
textCurrentTime.setText(milliSecondsToTimer(mediaPlayer.getCurrentPosition()));
return false;
}
});
mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int i) {
playerSeekBar.setSecondaryProgress(i);
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
playerSeekBar.setProgress(0);
imagePlaypause.setImageResource(R.drawable.playbutton);
textCurrentTime.setText(R.string.zero);
textTotalDuration.setText((R.string.zero));
mediaPlayer.reset();
new Content().execute(getIntent().getStringExtra("downloadlink"));
textTotalDuration.setText(milliSecondsToTimer(mediaPlayer.getDuration()));
}
});
}
I want to add a fast forward button on my code but I did not find how.
this is my code I hope someone will help me.
I found how
if (mediaPlayer != null) {
int currentPosition = mediaPlayer.getCurrentPosition();
if (currentPosition + seekForwardTime <= mediaPlayer.getDuration()) {
mediaPlayer.seekTo(currentPosition + seekForwardTime);
} else {
mediaPlayer.seekTo(mediaPlayer.getDuration());
}
}
Related
My SeekBar can work but then it can't auto-run the SeekBar progress
when I clicked on the SeekBar I will auto move to the position with an overlay player. and the runnable thread does not on the SeekBar
the line below is the code of my SeekBar
positionBar.setOnSeekBarChangeListener(
new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(fromUser && progress != 100) {
player.getDuration();
player.seekTo(progress);
positionBar.setProgress(progress);
Toast.makeText(getApplicationContext(), "seekbar progress: " + progress, Toast.LENGTH_SHORT).show();
}else {
progress = 0;
positionBar.setProgress(progress);
Song nextSong = songCollection.getNextSong(songId);
if(nextSong != null){
songId = nextSong.getId();
title = nextSong.getTitle();
artist = nextSong.getArtist();
fileLink = nextSong.getFileLink();
coverArt = nextSong.getCoverArt();
url = BASE_URL + fileLink;
displaySong(title,artist,coverArt);
stopActivities();
}
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
//
Toast.makeText(getApplicationContext(),"seekbar touch started!", Toast.LENGTH_SHORT).show();
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// player.seekTo(musicPostion);
Toast.makeText(getApplicationContext(),"seekbar touch stop!", Toast.LENGTH_SHORT).show();
}
}
);
new Thread(new Runnable() {
#Override
public void run() {
while(player != null){
try{
Message msg = new Message();
msg.what = player.getCurrentPosition();
handler.sendMessage(msg);
positionBar.setProgress(player.getCurrentPosition());
Thread.sleep(1000);
}catch (InterruptedException e){
}
}
}
}).start();
}
private Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
int currentPosition = msg.what;
positionBar.setProgress(currentPosition);
}
};`
Just like a view holder has the method getAdapterPosition(), I want to write my own setAdapterPosition() for the view holder(which doesn't exist).
What am I working on?
Currently, I am working on a project wherein I have to list 10 songs in the form of a recycler view and then play them, if any particular song is clicked. Each list item contains the song name, a seek bar and a play button
I have implemented this part, by adding all the media player contros inside the adapter class.
What do I want?
Currently, this model used mediaPlayer.setLooping(true) so that as soon as a song finished, it kept looping till some other song is clicked for playing.
Now I want to extend this model to an "autoplay" version so that as soon as a song is finished, the next song is played
What is the problem?
The seekBar progress and playButton image transition to a pauseButton image were happening with the call
viewHolder.seekBar.setProgress(...)
viewHolder.playButton.setImageDrawable(...)
Since this was happening on the
viewHolder.itemView.setOnClickListener(...)
as soon as a new song was clicked, the seekBar and playButton image were being updated.
Now, when the song is completed, I don't want the user to click on the next song to play it. I want it to be autoplayed, but I am unable to understand, how do I change myViewHolder position accordingly.
Suppose Song 0 has finished playing and Song 1 has started playing, viewHolder.getAdapterPosition() still returns 0 instead of 1. Hence the seekBar & playButton of song 0 is being updated and not of song 1.
I want to be able to do something like this
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
int nextSongPosition, currentSongPosition;
currentSongPosition = viewHolder.getAdapterPosition();
if(currentSongPosition==(songs.size()-1)){
nextSongPosition = 0;
//do some miracle so that viewHolder.getAdapterPosition() now shows 0 instead of currentSongPosition
}else{
nextSongPosition = currentSongPosition + 1;
//do some miracle so that viewHolder.getAdapterPosition() now shows nextSongPosition instead of the currentSongPosition;
}
}
});
As clear from the question statement, I want to implement something similar to a setAdapterPosition() which doesn't exist.
EDIT 1
onBindViewHolder Code:
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, int i) {
Song song = songs.get(i);
viewHolder.itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
audioManager = (AudioManager) Objects.requireNonNull(context).getSystemService(Context.AUDIO_SERVICE);
if(mediaPlayer.isPlaying()){
pauseMediaPlayer(viewHolder);
}else{
StorageReference storageRef = FirebaseStorage.getInstance().getReference("Songs");
StorageReference dateRef = storageRef.child(song.getStoredAs());
dateRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
try {
mediaPlayer.setDataSource(uri.toString());
mediaPlayer.prepare();
viewHolder.seekBar.setMax(mediaPlayer.getDuration() / 1000);
mSeekbarUpdateHandler = new Handler();
mUpdateSeekbar = new Runnable() {
#Override
public void run() {
if (viewHolder.seekBar != null && mediaPlayer != null) {
try{
viewHolder.seekBar.setProgress(mediaPlayer.getCurrentPosition() / 1000);
mSeekbarUpdateHandler.postDelayed(this, 50);
} catch(IllegalStateException e){
Log.i("Exception",e.toString());
}
}
}
};
viewHolder.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser && mediaPlayer != null)
mediaPlayer.seekTo( progress * 1000);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
startMediaPlayer(viewHolder);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
Log.i("Song Loading Error", exception.toString());
}
});
}
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
int nextSongPosition, currentSongPosition;
currentSongPosition = viewHolder.getAdapterPosition();
if(currentSongPosition==(songs.size()-1)){
nextSongPosition = 0;
//do some miracle so that viewHolder.getAdapterPosition() now shows 0 instead of currentSongPosition
}else{
nextSongPosition = currentSongPosition + 1;
//do some miracle so that viewHolder.getAdapterPosition() now shows nextSongPosition instead of the currentSongPosition;
}
}
});
}
pauseMediaPlayer(..) & startMediaPlayer(..) Code:
private void pauseMediaPlayer(ViewHolder viewHolder) {
int result = audioManager.requestAudioFocus(this, AudioManager.USE_DEFAULT_STREAM_TYPE, AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
isSongPlaying = false;
viewHolder.playButton.setImageResource(R.drawable.play_button);
if (mediaPlayer != null) {
mediaPlayer.pause();
}
}
}
private void startMediaPlayer(ViewHolder viewHolder) {
int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
isSongPlaying = true;
viewHolder.playButton.setImageResource(R.drawable.pause_button);
if (mediaPlayer != null) {
//mediaPlayer.setLooping(true);
mediaPlayer.start();
}
mSeekbarUpdateHandler.postDelayed(mUpdateSeekbar, 0);
}
}
I have some trouble getting the Seekbar to work, The first song that loads will not let me use the SeekBar, but when I load a secondary or third song the SeekBar will work for them. I tried initializing the SeekBar after the song Uri dataSource was loaded, however it still exhibited the same behavior.
Any ideas on how to get the SeekBar to work on the first song?
Thanks
...
public class MainActivity extends AppCompatActivity {
final int REQUEST_OPEN_FILE = 1;
MediaPlayer mediaPlayer = new MediaPlayer();
Uri audioFileUri;
/*SeekBar seekBar;*/
/*TextView SongProgress = findViewById(R.id.SongProgress);*/
#Override
protected void onCreate(Bundle savedInstanceState) {
...
}
...
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_OPEN_FILE) {
if (resultCode == RESULT_OK) {
audioFileUri = data.getData();
SeekBar seekBar;
seekBar = findViewById(R.id.seekbar);
seekBar.setMax(mediaPlayer.getDuration());
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
seekBar.setProgress(progress);
mediaPlayer.seekTo(progress);
/*int Minutes=((progress/1000)/60);
int Seconds=((progress/1000)%60);
int time = Minutes + Seconds;
SongProgress.setText(time);*/
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
try {
if (mediaPlayer.isPlaying()) {
mediaPlayer.reset();
mediaPlayer.setDataSource(this, audioFileUri);
mediaPlayer.prepare();
mediaPlayer.start();
Toast.makeText(this, "Was Playing", Toast.LENGTH_SHORT);
}
else{
mediaPlayer.setDataSource(this, audioFileUri);
mediaPlayer.prepare();
mediaPlayer.start();
Toast.makeText(this, "Was not playing", Toast.LENGTH_SHORT);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
...
...
}
Ok, I got the seekbar progress to update with the song so that the seekbar tracks along the audio file while it is playing. It was a simple runnable with a handler which I've posted in the code here. You have to have a runnable loop to track through the song as it is playing to update the seekbar. Then you have to write a handler to call that runnable loop. One important thing to note if you don't add the Boolean if(fromUser) in the seekbar onchanged listener the thread will cause it to play back choppy because it is also updating the progress in relation to the seekBar update progress function.
SeekBar seekBar;
Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
...
seekBar = (SeekBar) findViewById(R.id.seekbar);
...
}
...
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_OPEN_FILE) {
if (resultCode == RESULT_OK) {
audioFileUri = data.getData();
try {
if (mediaPlayer.isPlaying()) {
seekBar.setProgress(0);
mediaPlayer.reset();
mediaPlayer.setDataSource(this, audioFileUri);
mediaPlayer.prepare();
mediaPlayer.start();
seekBar.setMax(mediaPlayer.getDuration()); // Set the Maximum range of the
Toast.makeText(this, "Was Playing", Toast.LENGTH_SHORT);
} else {
seekBar.setProgress(0);
mediaPlayer.setDataSource(this, audioFileUri);
mediaPlayer.prepare();
mediaPlayer.start();
seekBar.setMax(mediaPlayer.getDuration()); // Set the Maximum range of the
/*seekBar.getVisibility();
seekBar.setVisibility(View.INVISIBLE);*/
Toast.makeText(this, "Was not playing", Toast.LENGTH_SHORT);
}
} catch (Exception e) {
e.printStackTrace();
}
int mediaPos = mediaPlayer.getCurrentPosition();
int mediaMax = mediaPlayer.getDuration();
seekBar.setMax(mediaMax); // Set the Maximum range of the
seekBar.setProgress(mediaPos);// set current progress to song's
handler.removeCallbacks(moveSeekBarThread);
handler.postDelayed(moveSeekBarThread, 1000);
}
}
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(fromUser) {
seekBar.setProgress(progress);
mediaPlayer.seekTo(progress);
}
else{}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
private Runnable moveSeekBarThread = new Runnable() {
public void run() {
if(mediaPlayer.isPlaying()){
int mediaPos_new = mediaPlayer.getCurrentPosition();
int mediaMax_new = mediaPlayer.getDuration();
seekBar.setMax(mediaMax_new);
seekBar.setProgress(mediaPos_new);
handler.postDelayed(this, 100); //Looping the thread after 0.1 second
// seconds
}else if(mediaPlayer.getCurrentPosition() == mediaPlayer.getDuration()){}
}
};
while playing music using this mediaplayer, whenever a call comes, home button is pressed and lockscreen appears and on return to the app after the above problems...the play button in the app doesnt respond....I want to pause the music untill I return to the app and should continue playing from where it had stopped......plz help...
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) {
}
}
#Override
protected void onPause()
{
super.onPause();
if (play3!= null)
{
play3.pause();
}
}
#Override
protected void onResume()
{
super.onResume();
if ((play3 != null) && (!play3.isPlaying())) {
but32.setText("Play");
but32.setOnClickListener(this);
}
}
This helped me to overcome my problems.....I'm able to play the music which gets paused when home button/lockscreen/calls appears...from where it had stopped
My application contains one mediaplayer with one (play/pause) button in audio.xml , but the problem is that I am not able to find right code to stop MediaPlayer before the page gets destroyed and because of that the app crashes when i log in audio page (xml) and quit without running mediaplayer , here is the code i used:
public class audio extends Langue 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.audio);
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.espoir);
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
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
// stop song
#Override
protected void onPause(){
super.onPause();
mp.stop();
finish();
}
}
Do something like this into the onPause() method for preventing crash
try{
mp.stop();
} catch(Exception e) {
}
finish();