I'm using media player in recycler view and the problem is when different item's play buttons are clicked they all play at the same time. How can I stop the previous one and start the new one?
public void onBindViewHolder(#NonNull MyAdapter.ViewHolder viewHolder, int position) {
final MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(item.get(position).getAudio());
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
viewHolder.play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
viewHolder.play.setImageResource(R.drawable.play);
} else {
mediaPlayer.start();
viewHolder.play.setImageResource(R.drawable.pause);
}
This is my recyclerView adapter and you must put your arraylist in this adapter
public class MyAdapter2 extends RecyclerView.Adapter<MyAdapter2.AudioItemsViewHolder> {
static MediaPlayer mediaPlayer;
Activity activity;
private final ArrayList<GroupItems> audioItems;//change it() to your items
private int currentPlayingPosition;
private final SeekBarUpdater seekBarUpdater;
private AudioItemsViewHolder playingHolder;
public MyAdapter2(Activity activity, ArrayList<GroupItems> items_pro) {
this.audioItems = items_pro;
this.currentPlayingPosition = -1;
seekBarUpdater = new SeekBarUpdater();
this.activity = activity;
}
#Override
public AudioItemsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//put YourItemsLayout;
return new AudioItemsViewHolder(LayoutInflater.from(parent.getContext()).inflate(YourItemsLayout, parent, false));
}
#Override
public void onBindViewHolder(AudioItemsViewHolder holder, int position) {
if (position == currentPlayingPosition) {
playingHolder = holder;
updatePlayingView();
} else {
updateNonPlayingView(holder);
}
}
private void updateNonPlayingView(AudioItemsViewHolder holder) {
holder.sbProgress.removeCallbacks(seekBarUpdater);
holder.sbProgress.setEnabled(false);
holder.sbProgress.setProgress(0);
holder.ivPlayPause.setImageResource(R.drawable.ic_baseline_play_arrow_24);
}
private void updatePlayingView() {
playingHolder.sbProgress.setMax(mediaPlayer.getDuration());
playingHolder.sbProgress.setProgress(mediaPlayer.getCurrentPosition());
playingHolder.sbProgress.setEnabled(true);
if (mediaPlayer.isPlaying()) {
playingHolder.sbProgress.postDelayed(seekBarUpdater, 100);
playingHolder.ivPlayPause.setImageResource(R.drawable.ic_pause);
} else {
playingHolder.sbProgress.removeCallbacks(seekBarUpdater);
playingHolder.ivPlayPause.setImageResource(R.drawable.ic_baseline_play_arrow_24);
}
}
private class SeekBarUpdater implements Runnable {
#Override
public void run() {
if (null != playingHolder && null != mediaPlayer) {
playingHolder.sbProgress.setProgress(mediaPlayer.getCurrentPosition());
playingHolder.sbProgress.postDelayed(this, 100);
}
}
}
#Override
public int getItemCount() {
return audioItems.size();
}
class AudioItemsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, SeekBar.OnSeekBarChangeListener {
SeekBar sbProgress;
ImageView ivPlayPause;
AudioItemsViewHolder(View itemView) {
super(itemView);
ivPlayPause = itemView.findViewById(R.id.sound_btn);
ivPlayPause.setOnClickListener(this);
sbProgress = itemView.findViewById(R.id.seekBar);
sbProgress.setOnSeekBarChangeListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.seekBar:
break;
case R.id.sound_btn: {
if (getAdapterPosition() == currentPlayingPosition) {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.pause();
} else {
if (mediaPlayer != null)
mediaPlayer.start();
}
} else {
currentPlayingPosition = getAdapterPosition();
if (mediaPlayer != null) {
if (null != playingHolder) {
updateNonPlayingView(playingHolder);
}
mediaPlayer.release();
}
playingHolder = this;
PlaySound(YOUR AUDIO FILE);//put your audio file
}
if (mediaPlayer != null)
updatePlayingView();
}
break;
}
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
mediaPlayer.seekTo(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
private void PlaySound(File filesound) {
mediaPlayer = MediaPlayer.create(activity, Uri.parse(String.valueOf(filesound)));
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
releaseMediaPlayer();
}
});
mediaPlayer.start();
}
private void releaseMediaPlayer() {
if (null != playingHolder) {
updateNonPlayingView(playingHolder);
}
if (outputFile.exists())
outputFile.delete();
mediaPlayer.release();
mediaPlayer = null;
currentPlayingPosition = -1;
}
}
Here is what you can do
Use a single global MediaPlayer rather than a player per view. Then when you click an item, stop the audio, set a new data source, and restart i.e. don't create a new MediaPlayer instance everytime in onBindViewHolder
MediaPlayer mediaPlayer = new MediaPlayer(); // Somewhere at the top of your code
Now you can use the mediaPlayer directly anywhere and don't assign a new instance to this
2.If for some reason you need to do it like so,
You first have to check if there is a sound that is already playing and if there is, you should stop it when the user decides to start a new sound.
viewholder.play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaplayer.isPlaying ()) {
if (mediaplayer != null){
mediaplayer.stop ();
}
} else {
if (mediaplayer != null) {
mediaplayer.start ();
}
}
}
});
In setOnCompletionListner you release the sound if the user listens to the whole sound clip.
mediaplayer.setOnCompletionListner (new MediaPlayer.OnCompletionListner () {
public void OnCompletion (MediaPlayer mediaplayer) {
mediaplayer.release ();
}
});
I will personally recommend the first solution as your application will take much lesser memory in that case
Related
I have come along in leaps and bound with my first android app in the last three days. This is my last hurdle. How do I get my app to run a background Service that will allow the audio to keep playing? I have tried several examples I could find but they are based on playing a local (or streamed) mp3 file as opposed to a live (Icecast) mp3 stream.
Here's my code currently, everything works except background audio.
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
private ImageButton btn;
private ImageView img;
private boolean playPause;
private MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.playPause);
img = findViewById(R.id.radioTower);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
mp.reset();
return false;
}
});
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
//mp.start();
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!playPause) {
if(!mediaPlayer.isPlaying()) {
mediaPlayer.start();
btn.setBackgroundResource(R.drawable.ic_rounded_pause_button);
img.setImageResource(R.drawable.ic_toweron);
img.setAlpha(1.0f);
playPause = true;
}
} else {
if(mediaPlayer.isPlaying()) {
mediaPlayer.pause();
btn.setBackgroundResource(R.drawable.ic_play_button);
img.setImageResource(R.drawable.ic_toweroff);
img.setAlpha(0.3f);
playPause = false;
}
}
}
});
try {
mediaPlayer.setDataSource("http://bbcmedia.ic.llnwd.net/stream/bbcmedia_radio2_mf_p");
mediaPlayer.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void onStop() {
super.onStop();
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
mediaPlayer = null;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
mediaPlayer = null;
}
}
}
Any help would be much appreciated.
use service to play audio file instant of activity.
here is simple code how to use media player in service.
public class MusicService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener {
//region "member variable"
boolean isServiceRunning = false;
ArrayList<Song> PlayerList = new ArrayList<>();
MediaPlayer mediaPlayer;
int position = 0;
MainActivity mainActivity;
private final IBinder mBinder = new LocalBinder();
int playingMood;
private final static int MAX_VOLUME = 15;
Toast toast;
public static MusicService objService;
//endregion
//region "service method"
#Override
public void onCreate() {
objService = this;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
isServiceRunning = true;
if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
// showNotification(false);
} else if (intent.getAction().equals(Constants.ACTION.PREV_ACTION)) {
playPrevious();
} else if (intent.getAction().equals(Constants.ACTION.PLAY_ACTION)) {
play();
} else if (intent.getAction().equals(Constants.ACTION.NEXT_ACTION)) {
playNext();
} else if (intent.getAction().equals(
Constants.ACTION.STOPFOREGROUND_ACTION)) {
stop();
stopForeground(true);
stopSelf();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
isServiceRunning = false;
objService = null;
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
//returns the instance of the service
public class LocalBinder extends Binder {
public MusicService getServiceInstance() {
return MusicService.this;
}
}
public void registerClient(MainActivity activity) {
mainActivity = activity;
}
//endregion
//region "Media player"
public void SongRequest() {
try {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
//Handel UI on main activity
mainActivity.showPlayer();
mediaPlayer = new MediaPlayer();
mainActivity.updatePlayerUI();
prepareMediaPlayer(PlayerList.get(position).getUrl());
} catch (Exception ex) {
ex.printStackTrace();
}
}
void showToast(String text) {
if (toast != null)
toast.cancel();
toast = Toast.makeText(App.getContext(), text, Toast.LENGTH_LONG);
toast.show();
}
#Override
public void onPrepared(MediaPlayer mp) {
// try {
mediaPlayer.start();
mainActivity.checkPlaying(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
public void onCompletion(MediaPlayer mp) {
try {
mainActivity.sentUpdateBroadcast(true);
if (playingMood == 1) {
mediaPlayer.start();
}
if (playingMood == 2) {
playNext();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
if (mainActivity != null)
mainActivity.updateProgressBuffer(percent);
if (percent == 1)
mainActivity.showPlayer();
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
try {
Log.i("MediaPlayer", "error");
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
void startPrepare(String url) {
prepareMediaPlayer(url);
}
void prepareMediaPlayer(String url) {
try {
mediaPlayer.setDataSource(url);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnPreparedListener(MusicService.this);
mediaPlayer.setOnErrorListener(MusicService.this);
mediaPlayer.setOnCompletionListener(MusicService.this);
mediaPlayer.setOnBufferingUpdateListener(MusicService.this);
mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
//endregion
//region "media player method"
public boolean play() {
if (mediaPlayer != null) {
switchButton();
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
return false;
} else {
mediaPlayer.start();
return true;
}
}
return false;
}
void switchButton() {
mainActivity.checkPlaying(!mediaPlayer.isPlaying());
}
public void stop() {
try {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
isServiceRunning = false;
if (mainActivity != null) {
mainActivity.ShowPlayer(0);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void playNext() {
if (position < PlayerList.size() - 1) {
position++;
mediaPlayer.stop();
SongRequest();
}
}
public void playPrevious() {
if (position > 0) {
position--;
mediaPlayer.stop();
SongRequest();
}
}
public void onError() {
}
public void onCompletion() {
}
public void onCleanMemory() {
}
public void initilizePlayerList(ArrayList<Song> list, int position) {
this.PlayerList = list;
this.position = position;
}
public boolean isplaying() {
return mediaPlayer == null ? false : mediaPlayer.isPlaying();
}
public boolean isRunning() {
return isServiceRunning;
}
public Song getCurrentSong() {
if (PlayerList != null && PlayerList.size() != 0 && PlayerList.size() >= position) {
return PlayerList.get(position);
}
return null;
}
public MediaPlayer getMediaPlayer() {
return mediaPlayer;
}
public void seekTo(int duration) {
if (mediaPlayer != null) {
mediaPlayer.seekTo(duration);
}
}
public int getMood() {
return playingMood;
}
public void setMood(int mood) {
playingMood = mood;
}
public void setVolume(int soundVolume) {
if (mediaPlayer != null) {
final float volume = (float) (1 - (Math.log(MAX_VOLUME - soundVolume) / Math.log(MAX_VOLUME)));
mediaPlayer.setVolume(volume, volume);
}
}
//endregion
}
you can start your service from activity like this.
public void startMusicService() {
Intent serviceIntent = new Intent(MainActivity.this, MusicService.class);
serviceIntent.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
startService(serviceIntent);
bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
}
for stop service use this code
public void stopMusicService() {
if (service != null) {
try {
service.stop();
unbindService(mConnection);
stopService(new Intent(MainActivity.this, service.getClass()));
service = null;
} catch (IllegalArgumentException ex) {
stopService(new Intent(MainActivity.this, service.getClass()));
service = null;
ex.printStackTrace();
}
}
}
for bind service with activity use this
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder _service) {
MusicService.LocalBinder binder = (MusicService.LocalBinder) _service;
service = binder.getServiceInstance(); //Get instance of your service!
service.registerClient(MainActivity.this); //Activity register in the service as client for callabcks!
if (listHolder != null) {
initilizeSongsList(listHolder.list, listHolder.position);
}
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
}
};
where service is music service object in activity MusicService service;
So this is the working service for a single live stream URL thanks to asim.
public class StreamService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener {
public static final String ACTION_PLAY = "com.example.action.PLAY";
private static final String STREAM_URL = "...";
private static final String TEST_URL = "https://www.nasa.gov/mp3/586447main_JFKwechoosemoonspeech.mp3";
MainActivity mainActivity;
MediaPlayer mediaPlayer = null;
WifiManager.WifiLock wifiLock;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public class LocalBinder extends Binder {
public StreamService getServiceInstance() {
return StreamService.this;
}
}
#Override
public void onCreate() {
super.onCreate();
}
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(ACTION_PLAY)) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
wifiLock = ((WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE))
.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "mylock");
wifiLock.acquire();
try {
// Set the stream URL location
mediaPlayer.setDataSource(TEST_URL);
// prepareAsync must be called after setAudioStreamType and setOnPreparedListener
mediaPlayer.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
}
return START_STICKY;
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// ... react appropriately ...
// The MediaPlayer has moved to the Error state, must be reset!
return false;
}
void switchButton() {
mainActivity.checkPlaying(!mediaPlayer.isPlaying());
}
public boolean play() {
if (mediaPlayer != null) {
//switchButton();
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
return false;
} else {
mediaPlayer.start();
return true;
}
}
return false;
}
public void stop() {
try {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
/** Called when MediaPlayer is ready */
public void onPrepared(MediaPlayer player) {
//player.start();
}
#Override
public void onDestroy() {
super.onDestroy();
if( wifiLock != null) wifiLock.release();
if (mediaPlayer != null) mediaPlayer.release();
}
public void registerClient(MainActivity activity) {
mainActivity = activity;
}
public boolean isplaying() {
return mediaPlayer == null ? false : mediaPlayer.isPlaying();
}
}
Which is implemented in the main activity:
public class MainActivity extends AppCompatActivity {
private ImageButton btn; // Play | Pause toggle button
private ImageView img; // Radio tower image that alternates between on and off
StreamService service;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Bind the view buttons to local variables
btn = findViewById(R.id.playPause);
img = findViewById(R.id.radioTower);
startStream();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (service.isplaying()) {
Log.d("pause","Pause Playback");
} else {
Log.d("play", "Start Playback");
}
}
});
}
public void startStream() {
Intent serviceIntent = new Intent(MainActivity.this, StreamService.class);
serviceIntent.setAction(StreamService.ACTION_PLAY);
startService(serviceIntent);
bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
}
public void stopStream() {
if (service != null) {
try {
service.stop();
unbindService(mConnection);
stopService(new Intent(MainActivity.this, service.getClass()));
service = null;
} catch (IllegalArgumentException ex) {
stopService(new Intent(MainActivity.this, service.getClass()));
service = null;
ex.printStackTrace();
}
}
}
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder _service) {
StreamService.LocalBinder binder = (StreamService.LocalBinder) _service;
service = binder.getServiceInstance(); //Get instance of your service!
service.registerClient(MainActivity.this); //Activity register in the service as client for callabcks!
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
}
};
}
Service starts just fine, I just need to learn how to access the service object to implement the play pause functionality.
I need some help, I want to make a recycle view containing audio in each item, how to play the audio when press play button and set progress to seekbar and at the same time pause other sound and convert the play button to play mode in all row except the playing one be in pause mode
such as or chats in facebook messenger
This is my code:
MyAdapter.class
private List<String> positions = new ArrayList<>();
public myAdapter(Activity activity, ArrayList<Tweet> list) {
this.activity = activity;
this.list = list;
mPlayer = new MediaPlayer();
}
public void onBindViewHolder(final viewHolder holder, final int position) {
if (!positions.contains(String.valueOf(position)))
positions.add(String.valueOf(position));
}
}
viewHolder.class
public class viewHolder extends RecyclerView.ViewHolder implements
SeekBar.OnSeekBarChangeListener, View.OnClickListener {
LinearLayout parentPanel;
int viewType;
private RelativeLayout pauseLayout, playLayout;
private ImageView pauseIcon, playIcon;
private SeekBar seekBar;
private TextView periodTime;
AudioCallbacks mAudioCallbacks;
private int last_position;
viewHolder(final View itemView, int viewType) {
super(itemView);
this.viewType = viewType;
playLayout = (RelativeLayout) itemView.findViewById(R.id.play_layout);
pauseLayout = (RelativeLayout) itemView.findViewById(R.id.pause_layout);
playIcon = (ImageView) itemView.findViewById(R.id.play_icon);
pauseIcon = (ImageView) itemView.findViewById(R.id.pause_icon);
seekBar = (SeekBar) itemView.findViewById(R.id.seekBar);
periodTime = (TextView) itemView.findViewById(R.id.period_time);
seekBar.setOnSeekBarChangeListener(this);
playLayout.setOnClickListener(this);
pauseLayout.setOnClickListener(this);
mAudioCallbacks = new AudioCallbacks() {
#Override
public void onUpdate(int percentage) {
seekBar.setProgress(percentage);
if (percentage == 100)
mAudioCallbacks.onStop();
}
#Override
public void onPause() {
Log.i("on pause audio", " pause");
}
#Override
public void onStop() {
Log.i("on stop audio", " stop");
stopPlayingAudio();
}
};
}
void stopPlayingAudio() {
if (mPlayer != null) {
if (mPlayer.isPlaying()) {
updateAudioProgressBar();
mPlayer.stop();
mPlayer.reset();
seekBar.setProgress(0);
playLayout.setVisibility(View.VISIBLE);
pauseLayout.setVisibility(View.GONE);
}
}
}
void pausePlayingAudio() {
if (mPlayer != null) {
if (mPlayer.isPlaying()) {
mPlayer.pause();
updateAudioProgressBar();
mAudioCallbacks.onPause();
}
}
}
void playingAudio(Tweet message) {
updateAudioProgressBar();
if (mPlayer != null) {
try {
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setDataSource(message.getAudioUrl());
mPlayer.prepare();
mPlayer.start();
periodTime.setVisibility(View.VISIBLE);
periodTime.setText(String.valueOf(message.getAudioDuration()));
} catch (Exception e) {
e.printStackTrace();
}
}
}
void updateAudioProgressBar() {
durationHandler.postDelayed(mUpdateTimeTask, 100);
}
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
try {
if (mPlayer.isPlaying()) {
long totalDuration = mPlayer.getDuration();
long currentDuration = mPlayer.getCurrentPosition();
int progress = Utils.getProgressPercentage(currentDuration, totalDuration);
mAudioCallbacks.onUpdate(progress);
periodTime.setText(Utils.getFileTime(currentDuration));
durationHandler.postDelayed(this, 100);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
durationHandler.removeCallbacks(mUpdateTimeTask);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
int totalDuration = mPlayer.getDuration();
int currentPosition = Utils.progressToTimer(seekBar.getProgress(), totalDuration);
mPlayer.seekTo(currentPosition);
updateAudioProgressBar();
}
#Override
public void onClick(View view) {
Log.e("getAdapterPosition()L", last_position + " /");
for (String pos : positions) {
if (!pos.equals(String.valueOf(getAdapterPosition())))
notifyItemChanged(Integer.parseInt(pos));
}
last_position = getAdapterPosition();
Log.e("getAdapterPosition()F", last_position + " /");
Tweet message = list.get(getAdapterPosition());
switch (view.getId()) {
case R.id.pause_layout:
playLayout.setVisibility(View.VISIBLE);
pauseLayout.setVisibility(View.GONE);
pausePlayingAudio();
break;
case R.id.play_layout:
playLayout.setVisibility(View.GONE);
pauseLayout.setVisibility(View.VISIBLE);
mAudioCallbacks.onStop();
playingAudio(message);
break;
}
}
}
public interface AudioCallbacks {
void onUpdate(int percentage);
void onPause();
void onStop();
}
the problem of this code is :
some time the image not reversed of other object when play specific item .
when scrolled the pause button appear in multiple row.
when play one then play another, stop the first and run the new one but when return to the previous not playing.
when leave the activity or press back press button the sound not stopped.
Can someone helped me, please?
Controlling and updating progress of MediaPlayer from RecyclerView cells is tricky. Your solution does not correctly update the view states in onBindViewHolder call, which is the root cause of all the issues you are facing. Few other notes one should keep in mind are as follows:
update cell view state correctly, which also include add/remove progress updater
try to avoid anonymous allocations of xxxListeners, Runnables in onBindViewHolder, i.e. ViewHolder can be used to implement xxxListener interfaces etc.
remove the seek bar updater, when media player completes the playback of audio
respect activity life-cycle and release/stop media player if it is not required to play the audio
Below source shows possible implementation of Adapter
private class AudioItemAdapter extends RecyclerView.Adapter<AudioItemAdapter.AudioItemsViewHolder> {
private MediaPlayer mediaPlayer;
private List<AudioItem> audioItems;
private int currentPlayingPosition;
private SeekBarUpdater seekBarUpdater;
private AudioItemsViewHolder playingHolder;
AudioItemAdapter(List<AudioItem> audioItems) {
this.audioItems = audioItems;
this.currentPlayingPosition = -1;
seekBarUpdater = new SeekBarUpdater();
}
#Override
public AudioItemsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new AudioItemsViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false));
}
#Override
public void onBindViewHolder(AudioItemsViewHolder holder, int position) {
if (position == currentPlayingPosition) {
playingHolder = holder;
updatePlayingView();
} else {
updateNonPlayingView(holder);
}
}
#Override
public void onViewRecycled(AudioItemsViewHolder holder) {
super.onViewRecycled(holder);
if (currentPlayingPosition == holder.getAdapterPosition()) {
updateNonPlayingView(playingHolder);
playingHolder = null;
}
}
private void updateNonPlayingView(AudioItemsViewHolder holder) {
holder.sbProgress.removeCallbacks(seekBarUpdater);
holder.sbProgress.setEnabled(false);
holder.sbProgress.setProgress(0);
holder.ivPlayPause.setImageResource(R.drawable.ic_play_arrow);
}
private void updatePlayingView() {
playingHolder.sbProgress.setMax(mediaPlayer.getDuration());
playingHolder.sbProgress.setProgress(mediaPlayer.getCurrentPosition());
playingHolder.sbProgress.setEnabled(true);
if (mediaPlayer.isPlaying()) {
playingHolder.sbProgress.postDelayed(seekBarUpdater, 100);
playingHolder.ivPlayPause.setImageResource(R.drawable.ic_pause);
} else {
playingHolder.sbProgress.removeCallbacks(seekBarUpdater);
playingHolder.ivPlayPause.setImageResource(R.drawable.ic_play_arrow);
}
}
void stopPlayer() {
if (null != mediaPlayer) {
releaseMediaPlayer();
}
}
private class SeekBarUpdater implements Runnable {
#Override
public void run() {
if (null != playingHolder) {
playingHolder.sbProgress.setProgress(mediaPlayer.getCurrentPosition());
playingHolder.sbProgress.postDelayed(this, 100);
}
}
}
#Override
public int getItemCount() {
return audioItems.size();
}
class AudioItemsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, SeekBar.OnSeekBarChangeListener {
SeekBar sbProgress;
ImageView ivPlayPause;
AudioItemsViewHolder(View itemView) {
super(itemView);
ivPlayPause = (ImageView) itemView.findViewById(R.id.ivPlayPause);
ivPlayPause.setOnClickListener(this);
sbProgress = (SeekBar) itemView.findViewById(R.id.sbProgress);
sbProgress.setOnSeekBarChangeListener(this);
}
#Override
public void onClick(View v) {
if (getAdapterPosition() == currentPlayingPosition) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
} else {
mediaPlayer.start();
}
} else {
currentPlayingPosition = getAdapterPosition();
if (mediaPlayer != null) {
if (null != playingHolder) {
updateNonPlayingView(playingHolder);
}
mediaPlayer.release();
}
playingHolder = this;
startMediaPlayer(audioItems.get(currentPlayingPosition).audioResId);
}
updatePlayingView();
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
mediaPlayer.seekTo(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
private void startMediaPlayer(int audioResId) {
mediaPlayer = MediaPlayer.create(getApplicationContext(), audioResId);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
releaseMediaPlayer();
}
});
mediaPlayer.start();
}
private void releaseMediaPlayer() {
if (null != playingHolder) {
updateNonPlayingView(playingHolder);
}
mediaPlayer.release();
mediaPlayer = null;
currentPlayingPosition = -1;
}
}
You can find complete working solution here - GitHub
public class MyAdapter2 extends RecyclerView.Adapter<MyAdapter2.AudioItemsViewHolder> {
static MediaPlayer mediaPlayer;
Activity activity;
private final ArrayList<GroupItems> audioItems;//change it() to your items
private int currentPlayingPosition;
private final SeekBarUpdater seekBarUpdater;
private AudioItemsViewHolder playingHolder;
public MyAdapter2(Activity activity, ArrayList<GroupItems> items_pro) {
this.audioItems = items_pro;
this.currentPlayingPosition = -1;
seekBarUpdater = new SeekBarUpdater();
this.activity = activity;
}
#Override
public AudioItemsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//put YourItemsLayout;
return new AudioItemsViewHolder(LayoutInflater.from(parent.getContext()).inflate(YourItemsLayout, parent, false));
}
#Override
public void onBindViewHolder(AudioItemsViewHolder holder, int position) {
if (position == currentPlayingPosition) {
playingHolder = holder;
updatePlayingView();
} else {
updateNonPlayingView(holder);
}
}
private void updateNonPlayingView(AudioItemsViewHolder holder) {
holder.sbProgress.removeCallbacks(seekBarUpdater);
holder.sbProgress.setEnabled(false);
holder.sbProgress.setProgress(0);
holder.ivPlayPause.setImageResource(R.drawable.ic_baseline_play_arrow_24);
}
private void updatePlayingView() {
playingHolder.sbProgress.setMax(mediaPlayer.getDuration());
playingHolder.sbProgress.setProgress(mediaPlayer.getCurrentPosition());
playingHolder.sbProgress.setEnabled(true);
if (mediaPlayer.isPlaying()) {
playingHolder.sbProgress.postDelayed(seekBarUpdater, 100);
playingHolder.ivPlayPause.setImageResource(R.drawable.ic_pause);
} else {
playingHolder.sbProgress.removeCallbacks(seekBarUpdater);
playingHolder.ivPlayPause.setImageResource(R.drawable.ic_baseline_play_arrow_24);
}
}
private class SeekBarUpdater implements Runnable {
#Override
public void run() {
if (null != playingHolder && null != mediaPlayer) {
playingHolder.sbProgress.setProgress(mediaPlayer.getCurrentPosition());
playingHolder.sbProgress.postDelayed(this, 100);
}
}
}
#Override
public int getItemCount() {
return audioItems.size();
}
class AudioItemsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, SeekBar.OnSeekBarChangeListener {
SeekBar sbProgress;
ImageView ivPlayPause;
AudioItemsViewHolder(View itemView) {
super(itemView);
ivPlayPause = itemView.findViewById(R.id.sound_btn);
ivPlayPause.setOnClickListener(this);
sbProgress = itemView.findViewById(R.id.seekBar);
sbProgress.setOnSeekBarChangeListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.seekBar:
break;
case R.id.sound_btn: {
if (getAdapterPosition() == currentPlayingPosition) {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.pause();
} else {
if (mediaPlayer != null)
mediaPlayer.start();
}
} else {
currentPlayingPosition = getAdapterPosition();
if (mediaPlayer != null) {
if (null != playingHolder) {
updateNonPlayingView(playingHolder);
}
mediaPlayer.release();
}
playingHolder = this;
PlaySound(YOUR AUDIO FILE);//put your audio file
}
if (mediaPlayer != null)
updatePlayingView();
}
break;
}
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
mediaPlayer.seekTo(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
private void PlaySound(File filesound) {
mediaPlayer = MediaPlayer.create(activity, Uri.parse(String.valueOf(filesound)));
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
releaseMediaPlayer();
}
});
mediaPlayer.start();
}
private void releaseMediaPlayer() {
if (null != playingHolder) {
updateNonPlayingView(playingHolder);
}
if (outputFile.exists())
outputFile.delete();
mediaPlayer.release();
mediaPlayer = null;
currentPlayingPosition = -1;
}
}
I am using the lists of audio on my Recyclview and it is working correct means I am able to play the audio file on my Recyclview.
As i am using the Seekbar with my audio file on my Recyclview , the problem is generating that when i am scrolling the Recyclview the other items's of Recyclview Seekbar is changing (Seekbar i am using for the progress of the audio file play.)
What i want that other Seekbar item of Recyclview sholud not be change when i scroll the Recyclview
Please check my code for it ,Inside the onBindViewHolder for my Recyclview , i am using the following code, please check it once.
((MyAudioChat) holder).sbMyAudio.setTag(position);
((MyAudioChat) holder).imgPlayAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((MyAudioChat) holder).sbMyAudio.removeCallbacks(null);
((MyAudioChat) holder).sbMyAudio.setProgress(0);
if (mediaPlayer == null) {
mediaPlayer();
((MyAudioChat) holder).sbMyAudio.setMax(mediaPlayer.getDuration());
} else {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer();
((MyAudioChat) holder).sbMyAudio.setMax(mediaPlayer.getDuration());
}
((MyAudioChat) holder).sbMyAudio.getTag();
((MyAudioChat) holder).sbMyAudio.setMax(mediaPlayer.getDuration()); // Set the Maximum range of the
((MyAudioChat) holder).sbMyAudio.setProgress(mediaPlayer.getCurrentPosition());// set current progress to song's
Runnable moveSeekBarThread = new Runnable() {
public void run() {
if (mediaPlayer.isPlaying()) {
int mediaPos_new = mediaPlayer.getCurrentPosition();
int mediaMax_new = mediaPlayer.getDuration();
((MyAudioChat) holder).sbMyAudio.setMax(mediaMax_new);
((MyAudioChat) holder).sbMyAudio.setProgress(mediaPos_new);
((MyAudioChat) holder).sbMyAudio.postDelayed(this, 100); //Looping the thread after 0.1 second
((MyAudioChat) holder).sbMyAudio.getTag();
}
}
};
((MyAudioChat) holder).sbMyAudio.removeCallbacks(moveSeekBarThread);
((MyAudioChat) holder).sbMyAudio.postDelayed(moveSeekBarThread, 100);
}
});
I have visited the following site on SO but did not get the relevant solution
1 .First Link
2. Second Link
Can we use the setTag() and getTag() to get rid of from this problem. I have used the setTag() on my above code. Please check it once.
Although, you have asked only about correct SeekBar updates, I am assuming (because you haven't shard complete source) that soon you will face following issues which are linked to the Adapter implementation:
How do I remove the seekBar updater, when MediaPlayer completes the playback of audio?
How do I release the MediaPlayer when activity is paused?
Anonymous View.OnClickListeners and Runnables are being allocated on every onBindViewHolder call. How do I minimize their unnecessary allocation?
You can find complete working solution here - GitHub
Following source tries to fix all above issues. Certain data structures/classes are assumed based on your nomenclature.
public class MainActivity extends Activity {
private MediaPlayer mediaPlayer;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView rv = (RecyclerView) findViewById(R.id.rv);
rv.setLayoutManager(new LinearLayoutManager(this));
AudioChat audioChats[] = new AudioChat[128];
rv.setAdapter(new MyAdapter(Arrays.asList(audioChats)));
}
#Override
protected void onPause() {
super.onPause();
if (null != mediaPlayer) {
mediaPlayer.release();
mediaPlayer = null;
}
}
private class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyAudioChat> {
private List<AudioChat> audioChats;
private int currentPlayingPosition;
private SeekBarUpdater seekBarUpdater;
MyAdapter(List<AudioChat> audioChats) {
this.audioChats = audioChats;
this.currentPlayingPosition = -1;
seekBarUpdater = new SeekBarUpdater();
}
#Override
public MyAudioChat onCreateViewHolder(ViewGroup parent, int viewType) {
return new MyAudioChat(LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false));
}
#Override
public void onBindViewHolder(MyAudioChat holder, int position) {
if (position == currentPlayingPosition) {
seekBarUpdater.playingHolder = holder;
holder.sbMyAudio.post(seekBarUpdater);
} else {
holder.sbMyAudio.removeCallbacks(seekBarUpdater);
holder.sbMyAudio.setProgress(0);
}
}
private class SeekBarUpdater implements Runnable {
MyAudioChat playingHolder;
#Override
public void run() {
if (null != mediaPlayer && playingHolder.getAdapterPosition() == currentPlayingPosition) {
playingHolder.sbMyAudio.setMax(mediaPlayer.getDuration());
playingHolder.sbMyAudio.setProgress(mediaPlayer.getCurrentPosition());
playingHolder.sbMyAudio.postDelayed(this, 100);
} else {
playingHolder.sbMyAudio.removeCallbacks(seekBarUpdater);
}
}
}
#Override
public int getItemCount() {
return audioChats.size();
}
class MyAudioChat extends RecyclerView.ViewHolder implements View.OnClickListener {
SeekBar sbMyAudio;
ImageView imgPlayAudio;
MyAudioChat(View itemView) {
super(itemView);
imgPlayAudio = (ImageView) itemView.findViewById(R.id.imgPlayAudio);
imgPlayAudio.setOnClickListener(this);
sbMyAudio = (SeekBar) itemView.findViewById(R.id.sbMyAudio);
}
#Override
public void onClick(View v) {
currentPlayingPosition = getAdapterPosition();
if (mediaPlayer != null) {
if (null != seekBarUpdater.playingHolder) {
seekBarUpdater.playingHolder.sbMyAudio.removeCallbacks(seekBarUpdater);
seekBarUpdater.playingHolder.sbMyAudio.setProgress(0);
}
mediaPlayer.release();
}
seekBarUpdater.playingHolder = this;
startMediaPlayer();
sbMyAudio.setMax(mediaPlayer.getDuration());
sbMyAudio.post(seekBarUpdater);
}
}
private void startMediaPlayer() {
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.mp3);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
seekBarUpdater.playingHolder.sbMyAudio.removeCallbacks(seekBarUpdater);
seekBarUpdater.playingHolder.sbMyAudio.setProgress(0);
mediaPlayer.release();
mediaPlayer = null;
currentPlayingPosition = -1;
}
});
mediaPlayer.start();
}
}
private class AudioChat {
}
}
I'm trying to implement live stream radio by using fragment and background service, however every time I click to radio button on navigation drawer I couldn't reach the player because it generates one more and I can only control the second one. Here is my fragment class.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_radio, container, false);
init(v);
ApiManager.getInstance().getRadioBroadcast(new ApiResponseLive.GetLiveBroadcastListener() {
#Override
public void onSuccess(StreamModel days) {
turnRadioOn(ApiManager.streamModel);
}
#Override
public void onFailure(String responseString) {
}
});
registerHandler(v);
return v;
}
private void turnRadioOn(StreamModel streamModel) {
HashMap<Integer, ArrayList<GenericStreamItem>> broadcastDays = new HashMap<>();
streamModel.setStreamAllArrays(broadcastDays);
BroadcastPagerAdapter radioPagerAdapter = new BroadcastPagerAdapter(getChildFragmentManager(), getContext(), TAG);
radioPager.setAdapter(radioPagerAdapter);
}
private void init(View v) {
radioPager = (ViewPager) v.findViewById(R.id.broadcastRadioPager);
radioTabLayout = (TabLayout) v.findViewById(R.id.tabsDays);
radioTabLayout.setupWithViewPager(radioPager);
radioPlay = (ToggleButton) v.findViewById(R.id.playButton);
radioScrollView = (ScrollView) v.findViewById(R.id.radioScroll);
}
private void start(String url) {
try {
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setDataSource(url);
mp.prepareAsync();
mp.setOnCompletionListener(this);
Log.e("Radio::", "Working");
} catch (Exception e) {
Log.e("StreamAudioDemo", e.getMessage());
e.printStackTrace();
}
}
private void stop() {
try {
mp.pause();
mp.stop();
mp.reset();
mp.release();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void stopRadio() {
try {
Log.e("stopRadio::", "Pause");
mp.pause();
mp.stop();
mp.reset();
mp.release();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
#Override
public void onCompletion(MediaPlayer mp) {
}
private void registerHandler(View v) {
radioPlay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Log.e("Toggle::", "Enabled");
radioService = new RadioService();
radioService.initMediaPlayer(ApiManager.RADIO_URL);
} else {
Log.e("Toggle::", "Disabled");
stop();
stopRadio();
radioService.onDestroy();
}
}
});
v.findViewById(R.id.radioBroadcast).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
radioScrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
});
}
public class RadioService extends Service implements MediaPlayer.OnErrorListener {
public void initMediaPlayer(String url) {
// ...initialize the MediaPlayer here...
ApiManager.getInstance().getRadioURL(new ApiResponseLive.GetTVStreamUrlListener() {
#Override
public void onSuccess(String tvUrl) {
start(ApiManager.RADIO_URL);
mp.setOnErrorListener(RadioService.this);
}
#Override
public void onFailure(String responseString) {
}
});
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// ... react appropriately ...
// The MediaPlayer has moved to the Error state, must be reset!
mp.reset();
return false;
}
#Override
public void onDestroy() {
if (mp != null) mp.release();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
}
Here is how I call fragment:
RadioFragment radioFragment = new RadioFragment();
fragment = fm.findFragmentByTag("radio");
radioDrawer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (fragment == null) {
fm.beginTransaction()
.remove(fm.findFragmentById(R.id.activity_content))
.add(R.id.activity_content, radioFragment,
"radio").addToBackStack("main").commit();
} else {
fm.beginTransaction().replace(R.id.activity_content,
radioFragment, "radio");
}
fullView.closeDrawers();
}
});
I created a Karaoke application. But I can't stop the MediaPlayer with out an error. When I press Back Button to go to home, I get "sorry ,Application has stopped working" The same thing happens if I try to start another activity
public class Main extends Activity implements MediaPlayerControl {
private MediaController mMediaController;
private MediaPlayer mMediaPlayer;
Handler mHandler = new Handler();
public TextView subtitles,subtitles2;
static Context context;
#SuppressLint("HandlerLeak")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.Main);
subtitles = (TextView) findViewById(R.id.subs2);
subtitles2 = (TextView) findViewById(R.id.subs21);
mMediaPlayer = new MediaPlayer();
mMediaController = new MediaController(this)
/*
* {
*
* #Override public void hide() { mMediaController.show(0); } }
*/;
mMediaController.setMediaPlayer(Main.this);
mMediaController.setAnchorView(findViewById(R.id.AudioView));
mMediaController.setPrevNextListeners(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Next button clicked
Intent intent = new Intent(Main.this, Hello.class);
startActivity(intent);
}
}, new View.OnClickListener() {
#Override
public void onClick(View v) {
// Previous button clicked
Intent intent = new Intent(Main.this, Sorry.class);
startActivity(intent);
}
});
// String audioFile = "" ;
try {
mMediaPlayer.setDataSource(this, Uri
.parse("android.resource://com.app.suadmon/raw/buchatri"));
mMediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
final long currentPos = mMediaPlayer.getCurrentPosition();
if (currentPos < 5130) {
subtitles.setText("1111+");
} else if (currentPos > 5130 && currentPos < 10572) {
subtitles.setText("555+");
} else if (currentPos > 10572 && currentPos < 10597) {
subtitles.setText("666+");
} else if (currentPos > 15312 && currentPos < 18478) {
subtitles.setText("777+");
} else if (currentPos > 18478 && currentPos < 24191) {
subtitles.setText("888+");
} else if (currentPos > 24191 && currentPos < 28137) {
subtitles.setText("999+");
} else if (currentPos > 28137 && currentPos < 29500) {
subtitles.setText("Thank you");
subtitles2.setText(".............");
}
mHandler.sendEmptyMessageDelayed(0, 1);
}
};
mHandler.sendEmptyMessage(0);
mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mHandler.post(new Runnable() {
public void run() {
mMediaController.show(0);
// mMediaPlayer.reset();
mMediaPlayer.start();
}
});
}
});
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
Intent stopplay = new Intent(Main.this, Hello.class);
startActivity(stopplay);
}
});
}
protected void onDestroy() {
super.onDestroy();
mMediaPlayer.stop();
mMediaPlayer.release();
}
public void releaseMediaPlayer(){
if(mMediaPlayer != null){
mMediaPlayer.release();
mMediaPlayer = null;
}
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
public int getBufferPercentage() {
int percentage = (mMediaPlayer.getCurrentPosition() * 100)
/ mMediaPlayer.getDuration();
return percentage;
}
public int getCurrentPosition() {
return mMediaPlayer.getCurrentPosition();
}
public int getDuration() {
return mMediaPlayer.getDuration();
}
public boolean isPlaying() {
return mMediaPlayer.isPlaying();
}
public void seekTo(int pos) {
mMediaPlayer.seekTo(pos);
}
#Override
public void pause() {
// TODO Auto-generated method stub
mMediaPlayer.pause();
}
protected void onPause() {
super.onPause();
mMediaPlayer.getCurrentPosition();
mMediaPlayer.pause();
}
protected void onResume() {
super.onResume();
mMediaPlayer.seekTo(0);
mMediaPlayer.start();
}
// public void onUserLeaveHint(){
// mMediaPlayer.stop();
// super.onUserLeaveHint();
// }
/*
* public void stopPlayback(){ mMediaPlayer.stop(); }
*/
public void start() {
mMediaPlayer.start();
}
public boolean onTouchEvent(MotionEvent event) {
mMediaController.show(0);
return false;
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
finish();
Intent intent = new Intent(Main.this, Show.class);
startActivity(intent);
super.onBackPressed();
}
}
and Log Cat's here.
How can I fix this. I have no idea.
Can anyone help me. Please !!!
You need to stop and release the media player before your activity finishes. Try adding this to your activity:
#Override
protected void onDestroy() {
super.onDestroy();
if(mMediaPlayer != null)
{
mMediaPlayer.stop();
mMediaPlayer.release();
}
}