Hi Community,
I'm developing whats-app like application.In that I am facing a
problem in recycle view while scrolling the items.The problem is even
specific to audio files itself.These files were playing irrelevant to
item data position.Please help me to resolve this issue.
MyAdapterClass:
#Override
public void onBindViewHolder(SwappingHolder holder, int position) {
MessageDetails messageData = messagesList.get(position);
if (messageData != null) {
switch (messageData.getMessageType()) {
case MessageDetails.MESSAGE_TEXT_TYPE:
TextTypeViewHolder textViewHolder = (TextTypeViewHolder) holder;
textViewHolder.updateView(messageData);
break;
case MessageDetails.MESSAGE_IMAGE_TYPE:
ImageTypeViewHolder imageViewHolder = (ImageTypeViewHolder) holder;
imageViewHolder.updateImageFile(messageData);
break;
case MessageDetails.MESSAGE_AUDIO_TYPE:
AudioTypeViewHolder audioHolder = (AudioTypeViewHolder) holder;
audioHolder.initializeAudioPlayer(messageData);
break;
case MessageDetails.MESSAGE_VIDEO_TYPE:
VideoTypeViewHolder videoHolder = (VideoTypeViewHolder) holder;
videoHolder.updateVideoMessage(messageData);
break;
case MessageDetails.MESSAGE_LOCATION_TYPE:
MapTypeHolder mapHolder = (MapTypeHolder) holder;
mapHolder.loadMapThumbView(messageData);
break;
case MessageDetails.MESSAGE_CONTACT_TYPE:
ContactsTypeHolder contactsHolder = (ContactsTypeHolder) holder;
contactsHolder.setContactData(messageData);
break;
case MessageDetails.MESSAGE_FILE_TYPE:
FileTypeHolder fileTypeHolder = (FileTypeHolder)holder;
fileTypeHolder.updateFileData(messageData);
}
}
}
MyHolderClass:
public class AudioTypeViewHolder extends SwappingHolder implements View.OnClickListener, View.OnLongClickListener {
SeekBar seekBar;
TextView timer, tv_time;
ImageView btn_play, iv_smile;
CardView cardView;
RelativeLayout parentView;
CustomizedAudioPlayer player;
MessageDetails messageDetails;
MediaPlayer mediaPlayer;
public AudioTypeViewHolder(View itemView) {
super(itemView, multiSelector);
this.timer = (TextView) itemView.findViewById(R.id.timer);
this.seekBar = (SeekBar) itemView.findViewById(R.id.audio_seekBar);
this.btn_play = (ImageView) itemView.findViewById(R.id.btnPlay);
this.tv_time = (TextView) itemView.findViewById(R.id.timeright);
this.cardView = (CardView) itemView.findViewById(R.id.card_view);
this.parentView = (RelativeLayout) itemView.findViewById(R.id.parent_view);
this.iv_smile =(ImageView) itemView.findViewById(R.id.smile1);
this.mediaPlayer = new MediaPlayer();
btn_play.setOnClickListener(this);
player = new CustomizedAudioPlayer(mediaPlayer, seekBar, btn_play, timer);
itemView.setOnLongClickListener(this);
itemView.setLongClickable(true);
btn_play.setOnLongClickListener(this);
btn_play.setLongClickable(true);
}
void initializeAudioPlayer(MessageDetails messageDetails) {
int colorId, gravity;
this.messageDetails = messageDetails;
if(messageDetails.getAudioPlayer() == null)
messageDetails.setAudioPlayer(player);
if (messageDetails.getSender().equals("to")) {
colorId = mContext.getResources().getColor(R.color.color_recevied_item);
gravity = Gravity.LEFT;
iv_smile.setVisibility(View.GONE);
} else {
colorId = mContext.getResources().getColor(R.color.color_sent_item);
gravity = Gravity.RIGHT;
iv_smile.setVisibility(View.VISIBLE);
iv_smile.setBackgroundResource(updateMessageStatus(messageDetails.getMstatus()));
}
player.initializePlayer(messageDetails.getMessage());
tv_time.setText(messageDetails.getTime());
cardView.setCardBackgroundColor(colorId);
parentView.setGravity(gravity);
}
#Override
public void onClick(View view) {
int id = view.getId();
if (id == R.id.btnPlay) {
if (!mediaPlayer.isPlaying()) {
// check my player is playing
//if not, stop if any other player is playing
for (MessageDetails messageDetails : messagesList) {
CustomizedAudioPlayer customPlayer = messageDetails.getAudioPlayer();
if(customPlayer != null)
customPlayer.stopTheMediaPlay();
}
//start my player
btn_play.setImageResource(R.drawable.img_pause);
player.startThePlayer();
notifyDataSetChanged();
} else {
btn_play.setImageResource(R.drawable.img_play);
player.stopTheMediaPlay();
}
}
}
#Override
public boolean onLongClick(View view) {
onItemLongPressed(this, messageDetails);
return true;
}
}
My Custom Audio Player
public class CustomizedAudioPlayer implements SeekBar.OnSeekBarChangeListener,MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener {
private Handler myHandler = new Handler();
SeekBar seekbar;
MediaPlayer mediaPlayer;
boolean isPaused;
ImageView playBtn;
TextView timer;
StringBuilder mFormatBuilder;
Formatter mFormatter;
int totalDuration, currentDuration;
String path, chatId;
public CustomizedAudioPlayer(MediaPlayer mediaPlayer, SeekBar seekbar, ImageView view, TextView timer){
this.seekbar = seekbar;
this.playBtn = view;
this.timer = timer;
this.mediaPlayer = mediaPlayer;
mFormatBuilder = new StringBuilder();
mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
this.seekbar.setProgress(0);
this.seekbar.setMax(100);
this.seekbar.setOnSeekBarChangeListener(this);
}
public void initializePlayer(String filePath){
try{
if(path == null){
this.path = filePath;
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setDataSource(path);
mediaPlayer.prepare();
timer.setText(stringForTime( mediaPlayer.getDuration()));
}
}catch (Exception e){
}
}
public void startThePlayer(){
totalDuration = mediaPlayer.getDuration();
mediaPlayer.seekTo(currentDuration);
myHandler.postDelayed(updateProgress,100);
mediaPlayer.start();
}
public void stopTheMediaPlay(){
if(mediaPlayer.isPlaying()){
playBtn.setImageResource(R.drawable.img_play);
currentDuration = mediaPlayer.getCurrentPosition();
timer.setText(stringForTime( mediaPlayer.getDuration()));
myHandler.removeCallbacks(updateProgress);
mediaPlayer.pause();
}
}
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
playBtn.setImageResource(R.drawable.img_play);
seekbar.setProgress(0);
timer.setText(stringForTime( mediaPlayer.getDuration()));
myHandler.removeCallbacks(updateProgress);
}
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
myHandler.removeCallbacks(updateProgress);
playBtn.setImageResource(R.drawable.img_play);
mediaPlayer.pause();
isPaused = true;
}
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
currentDuration = progressToTimer(seekBar.getProgress(), totalDuration);
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
if(fromUser){
mediaPlayer.seekTo(currentDuration);
}
} else if (mediaPlayer == null) {
seekBar.setProgress(0);
}
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
currentDuration = progressToTimer(seekBar.getProgress(), totalDuration);
if (mediaPlayer.isPlaying() && mediaPlayer != null || (isPaused && mediaPlayer != null)) {
isPaused = false;
mediaPlayer.seekTo(currentDuration);
myHandler.postDelayed(updateProgress,100);
mediaPlayer.start();
playBtn.setImageResource(R.drawable.img_pause);
}
}
#Override
public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
return false;
}
private Runnable updateProgress = new Runnable() {
public void run() {
totalDuration = mediaPlayer.getDuration();
currentDuration = mediaPlayer.getCurrentPosition();
int progress = getProgressPercentage();
float progressPer = ((float)progress/100);
float newPosition = (totalDuration) * progressPer;
seekbar.setProgress(progress);
timer.setText(stringForTime( (int) newPosition));
myHandler.postDelayed(this, 100);
}
};
private String stringForTime(int timeMs) {
int totalSeconds = timeMs / 1000;
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
mFormatBuilder.setLength(0);
if (hours > 0) {
return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
} else {
return mFormatter.format("%02d:%02d", minutes, seconds).toString();
}
}
public int getProgressPercentage(){
long currentSeconds = (currentDuration / 1000);
long totalSeconds = (totalDuration / 1000);
Double percentage =(((double)currentSeconds)/totalSeconds)*100;
return percentage.intValue();
}
public int progressToTimer(int progress, int totalDuration) {
totalDuration = (totalDuration / 1000);
int currentDuration = (int) ((((double)progress) / 100) * totalDuration);
// return current duration in milliseconds
return currentDuration * 1000;
}
}
I even tried by placing
setIsRecyclable(false);
Using this, the positions of items are stable, but the item not updating while playing audio file(i.e. seekbar, file time not updating)
You can closely find my problem in following screenshot
Related
I've just developed a simple media player that sounds a song and it has a seekbar that regulate the song volume.
That's my code:
public class MainActivity extends AppCompatActivity {
Button playBtn;
SeekBar positionBar;
SeekBar volumeBar;
TextView elapsedTimeLabel;
TextView remainingTimeLabel;
MediaPlayer mp;
int totalTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playBtn = (Button) findViewById(R.id.playBtn);
elapsedTimeLabel = (TextView) findViewById(R.id.elapsedTimeLabel);
remainingTimeLabel = (TextView) findViewById(R.id.remainingTimeLabel);
// Media Player
mp = MediaPlayer.create(this, R.raw.song);
mp.setLooping(true);
mp.seekTo(0);
mp.setVolume(0.5f, 0.5f);
totalTime = mp.getDuration();
// Position Bar
positionBar = (SeekBar) findViewById(R.id.positionBar);
positionBar.setMax(totalTime);
positionBar.setOnSeekBarChangeListener(
new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
mp.seekTo(progress);
positionBar.setProgress(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
);
// Volume Bar
volumeBar = (SeekBar) findViewById(R.id.volumeBar);
volumeBar.setOnSeekBarChangeListener(
new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
float volumeNum = progress / 100f;
mp.setVolume(volumeNum, volumeNum);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
);
// Thread (Update positionBar & timeLabel)
new Thread(new Runnable() {
#Override
public void run() {
while (mp != null) {
try {
Message msg = new Message();
msg.what = mp.getCurrentPosition();
handler.sendMessage(msg);
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
}
}).start();
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
int currentPosition = msg.what;
// Update positionBar.
positionBar.setProgress(currentPosition);
// Update Labels.
String elapsedTime = createTimeLabel(currentPosition);
elapsedTimeLabel.setText(elapsedTime);
String remainingTime = createTimeLabel(totalTime-currentPosition);
remainingTimeLabel.setText("- " + remainingTime);
}
};
public String createTimeLabel(int time) {
String timeLabel = "";
int min = time / 1000 / 60;
int sec = time / 1000 % 60;
timeLabel = min + ":";
if (sec < 10) timeLabel += "0";
timeLabel += sec;
return timeLabel;
}
public void playBtnClick(View view) {
if (!mp.isPlaying()) {
// Stopping
mp.start();
playBtn.setBackgroundResource(R.drawable.ic_stop);
} else {
// Playing
mp.pause();
playBtn.setBackgroundResource(R.drawable.ic_play);
}
} }
Now, when I regulate the volume with the media player seekbar, the phone system volume didn't change and the other way around.
How can I syncronize the volume seekbar with the phone system volume so as to adjust the volume with both?
Using the Audio Manager to Raise and Down Volume.
AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
//Using volume control UI visibility
//To increase media player volume
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
//To decrease media player volume
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
//Without volume control UI
//To increase media player volume
audioManager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND);
//To decrease media player volume
audioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);
I want to to add the media controller on VLC player android integration but i didn't find any option to do that i am sharing the code -
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.otherformat);
load = (ProgressBar) this.findViewById(R.id.load);
intent = getIntent();
load.setVisibility(View.VISIBLE);
handler = new Handler();
mFilePath ="http://mm2.pcslab.com/mm/7h800.mp4";
Log.e(TAG, "Playing: " + mFilePath);
mSurface = (SurfaceView) findViewById(R.id.surface);
holder = mSurface.getHolder();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setSize(mVideoWidth, mVideoHeight);
}
#Override
protected void onResume() {
super.onResume();
createPlayer(mFilePath);
}
#Override
protected void onPause() {
super.onPause();
releasePlayer();
}
#Override
protected void onDestroy() {
super.onDestroy();
releasePlayer();
}
/**
* Used to set size for SurfaceView
*
* #param width
* #param height
*/
private void setSize(int width, int height) {
mVideoWidth = width;
mVideoHeight = height;
if (mVideoWidth * mVideoHeight <= 1)
return;
if (holder == null || mSurface == null)
return;
int w = getWindow().getDecorView().getWidth();
int h = getWindow().getDecorView().getHeight();
boolean isPortrait = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
if (w > h && isPortrait || w < h && !isPortrait) {
int i = w;
w = h;
h = i;
}
float videoAR = (float) mVideoWidth / (float) mVideoHeight;
float screenAR = (float) w / (float) h;
if (screenAR < videoAR)
h = (int) (w / videoAR);
else
w = (int) (h * videoAR);
holder.setFixedSize(mVideoWidth, mVideoHeight);
ViewGroup.LayoutParams lp = mSurface.getLayoutParams();
lp.width = w;
lp.height = h;
mSurface.setLayoutParams(lp);
mSurface.invalidate();
}
/**
* Creates MediaPlayer and plays video
*
* #param media
*/
private void createPlayer(String media) {
releasePlayer();
try {
if (media.length() > 0) {
Toast toast = Toast.makeText(this, media, Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0,
0);
//toast.show();
}
// Create LibVLC
// TODO: make this more robust, and sync with audio demo
ArrayList<String> options = new ArrayList<String>();
//options.add("--subsdec-encoding <encoding>");
options.add("--aout=opensles");
options.add("--audio-time-stretch"); // time stretching
options.add("-vvv"); // verbosity
libvlc = new LibVLC(this, options);
holder.setKeepScreenOn(true);
// Creating media player
mMediaPlayer = new MediaPlayer(libvlc);
mMediaPlayer.setEventListener(mPlayerListener);
mMediaPlayer.setVideoTrackEnabled(true);
// Seting up video output
final IVLCVout vout = mMediaPlayer.getVLCVout();
vout.setVideoView(mSurface);
//vout.setSubtitlesView(mSurfaceSubtitles);
vout.addCallback(this);
vout.attachViews();
Media m = new Media(libvlc, Uri.parse(media));
mMediaPlayer.setMedia(m);
mMediaPlayer.play();
////////////////////////////////////////////////
/* //mController = new MediaController(this);
mController = (MediaController)findViewById(R.id.mediaController);
mController.setVisibility(View.VISIBLE);
mController.setAnchorView(mSurface);
mController.show(0);*/
/*mController = new MediaController(this);
mController.setAnchorView(mSurface);
handler.post(new Runnable() {
public void run() {
mController.show();
}
});*/
} catch (Exception e) {
Log.e("Err", e.getMessage()+"");
Toast.makeText(this, "Error in creating player!"+e.getMessage(), Toast
.LENGTH_LONG).show();
}
}
private void releasePlayer() {
if (libvlc == null)
return;
mMediaPlayer.stop();
final IVLCVout vout = mMediaPlayer.getVLCVout();
vout.removeCallback(this);
vout.detachViews();
holder = null;
libvlc.release();
libvlc = null;
mVideoWidth = 0;
mVideoHeight = 0;
}
/**
* Registering callbacks
*/
private MediaPlayer.EventListener mPlayerListener = new MyPlayerListener(this);
#Override
public void onNewLayout(IVLCVout vout, int width, int height, int visibleWidth, int visibleHeight, int sarNum, int sarDen) {
if (width * height == 0)
return;
// store video size
mVideoWidth = width;
mVideoHeight = height;
setSize(mVideoWidth, mVideoHeight);
}
#Override
public void onSurfacesCreated(IVLCVout vout) {
}
#Override
public void onSurfacesDestroyed(IVLCVout vout) {
}
#Override
public void onHardwareAccelerationError(IVLCVout vlcVout) {
Log.e(TAG, "Error with hardware acceleration");
this.releasePlayer();
Toast.makeText(this, "Error with hardware acceleration", Toast.LENGTH_LONG).show();
}
private static class MyPlayerListener implements MediaPlayer.EventListener {
private WeakReference<OtherFormat> mOwner;
public MyPlayerListener(OtherFormat owner) {
mOwner = new WeakReference<OtherFormat>(owner);
}
#Override
public void onEvent(MediaPlayer.Event event) {
OtherFormat player = mOwner.get();
switch (event.type) {
case MediaPlayer.Event.EndReached:
Log.d(TAG, "MediaPlayerEndReached");
player.releasePlayer();
break;
case MediaPlayer.Event.Playing:
load.setVisibility(View.GONE);
break;
case MediaPlayer.Event.Paused:
case MediaPlayer.Event.Buffering:
float percent = event.getBuffering(); /* from 0.0f to 100f */
Log.e("Percent><><",""+percent);
break;
case MediaPlayer.Event.Stopped:
default:
break;
}
}
}}
XML for this activity -
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<SurfaceView
android:id="#+id/surface"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center" />
<ProgressBar
android:id="#+id/load"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:visibility="visible"
android:layout_gravity="center"
/>
<MediaController
android:id="#+id/mediaController"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" >
</MediaController>
</FrameLayout>
By this code mediacontrollers not showing please help me how to show media controllers for pause, play and seekbar for video position in surfaceview of vlc media player.
I had the same issue and have found a solution.
Sure, it's too late for answer, but maybe I will save some time to someone.
To add default media control you need to implement it in following way
remove MediaController from layout and add some container for media control to to your activity (it will be added programmatically).
<FrameLayout
android:id="#+id/video_surface_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:foregroundGravity="clip_horizontal|clip_vertical"
tools:ignore="true">
<SurfaceView
android:id="#+id/surface"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center" />
</FrameLayout>
add controller init to onStart activity or to onCreate
import android.widget.MediaController;
private MediaController controller;
#Override
protected void onStart() {
super.onStart();
....
controller = new MediaController(this);
controller.setMediaPlayer(findViewByid(R.id.video_surface_frame));
controller.setAnchorView(mVideoSurfaceFrame);
mVideoSurfaceFrame.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
controller.show(10000);
}
});
}
to define playerInterface, you need to implement the MediaController.MediaPlayerControl interface like this
private MediaController.MediaPlayerControl playerInterface = new MediaController.MediaPlayerControl() {
public int getBufferPercentage() {
return 0;
}
public int getCurrentPosition() {
float pos = mLibVlc.getPosition();
return (int)(pos * getDuration());
}
public int getDuration() {
return (int)mLibVlc.getLength();
}
public boolean isPlaying() {
return mLibVlc.isPlaying();
}
public void pause() {
mLibVlc.pause();
}
public void seekTo(int pos) {
mLibVlc.setPosition((float)pos / getDuration());
}
public void start() {
mLibVlc.play();
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
return 0;
}
};
launch your app and tap on video. You will see default media control and it will hide in 10 sec
Good luck!
Link to VideoLan sample on github:
https://code.videolan.org/videolan/vlc-android/blob/f3db2e4a33bf96c03056874322fb5b9304f92259/vlc-android/src/vlc/android/VLC.java
public class Show_Array extends AppCompatActivity implements IVLCVout.Callback {
private TextView container_extension;
private String stream_typee,stream_idd,container_extensionn ;
private String SAMPLE_URL = "";
public int mHeight;
public int mWidth;
private SurfaceView mVideoSurface = null;
private FrameLayout sdk;
private IVLCVout vlcVout;
private LibVLC mLibVlc = null;
private MediaPlayer mMediaPlayer = null;
private int flag = 0;
private ImageButton Resize;
private Media media;
private ArrayList<String> args;
private SurfaceHolder mSurfaceHolderVideo;
private MediaController controller;
#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.show__array);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//Referances
Resize = findViewById(R.id.Resize);
mVideoSurface = findViewById(R.id.video_surface);
stream_typee = getIntent().getExtras().getString("stream_type");
stream_idd = getIntent().getExtras().getString("stream_id");
container_extensionn = getIntent().getExtras().getString("container_extension");
args = new ArrayList<>();
args.add("-vvv");
mLibVlc = new LibVLC(this, args);
mMediaPlayer = new MediaPlayer(mLibVlc);
vlcVout = mMediaPlayer.getVLCVout();
sdk = findViewById(R.id.sdk);
Resize_video();
setup_url();
controller = new MediaController(this);
controller.setMediaPlayer(playerInterface);
controller.setAnchorView(mVideoSurface);
mVideoSurface.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
controller.show(10000);
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
mMediaPlayer.release();
mLibVlc.release();
}
void Resize_video()
{
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
mHeight = displayMetrics.heightPixels;
mWidth = displayMetrics.widthPixels;
Resize.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
flag+=1;
int width = 1000;
int height = 560;
if(flag%2!=0) {
LinearLayout.LayoutParams myImageLayout = new LinearLayout.LayoutParams(width, height);
myImageLayout.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL;
sdk.setLayoutParams(myImageLayout);
vlcVout.setWindowSize(width,height);
}
else
{
LinearLayout.LayoutParams myImageLayout = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
myImageLayout.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL;
sdk.setLayoutParams(myImageLayout);
vlcVout.setWindowSize(mWidth,mHeight);
}
}
});
}
void setup_url()
{
//TextView
container_extension = findViewById(R.id.URL);
if (stream_typee.equals("live"))
{
SAMPLE_URL = "http://uautv.ru:2095/"+stream_typee+"/webserver/6tE#BzW73#sX/"+stream_idd+".ts";
container_extension.setText( SAMPLE_URL);
}else
{
SAMPLE_URL = "http://uautv.ru:2095/"+stream_typee+"/webserver/6tE#BzW73#sX/"+stream_idd+"."+container_extensionn;
container_extension.setText( SAMPLE_URL);
}
}
#Override
protected void onStart() {
super.onStart();
vlcVout.setWindowSize(mWidth,mHeight);
vlcVout.setVideoView(mVideoSurface);
vlcVout.attachViews();
mMediaPlayer.getVLCVout().addCallback(this);
if(!SAMPLE_URL.isEmpty()) {
media = new Media(mLibVlc, Uri.parse(SAMPLE_URL));
mMediaPlayer.setMedia(media);
media.release();
mMediaPlayer.play();
}else
{
Toast.makeText(getApplicationContext(),"URL EMPTY",Toast.LENGTH_LONG).show();
}
}
#Override
protected void onStop() {
super.onStop();
mMediaPlayer.stop();
mMediaPlayer.getVLCVout().detachViews();
mMediaPlayer.getVLCVout().removeCallback(this);
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
public void onNewLayout(IVLCVout vlcVout, int width, int height, int visibleWidth, int visibleHeight, int sarNum, int sarDen)
{ }
#Override
public void onSurfacesCreated(IVLCVout vlcVout) {
}
#Override
public void onSurfacesDestroyed(IVLCVout vlcVout) {
}
private MediaController.MediaPlayerControl playerInterface = new MediaController.MediaPlayerControl() {
public int getBufferPercentage() {
return 0;
}
public int getCurrentPosition() {
float pos = mMediaPlayer.getPosition();
return (int)(pos * getDuration());
}
public int getDuration() {
return (int)mMediaPlayer.getLength();
}
public boolean isPlaying() {
return mMediaPlayer.isPlaying();
}
public void pause() {
mMediaPlayer.pause();
}
public void seekTo(int pos) {
mMediaPlayer.setPosition((float)pos / getDuration());
}
public void start() {
mMediaPlayer.play();
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
return 0;
}
};
}
everybody.
First of all, I'm a newbie. I created an activity to play a specific mp3 from raw folder. It works fine and playing it well. I implemented the Media Player as you will see in my code below. But the problem is when I change the orientation of my smartphone , the player continues playing the sound, but a new activity is opened/ updated with the same elements reseted and if I click on PLAY button, the mp3 starts playing, but the old activity stills running on back, playing the mp3.... so, there are 2 same songs playing now...
I don't want to update the activity or open a new one. I just want to continue playing the song where it was playing before I change the smartphone orientation.
Here is my code:
MP3PlayerActivity.java (main)
public class Mp3PlayerActivity extends Activity implements OnPreparedListener {
/** Called when the activity is first created. */
private Button btnPlay;
private Button btnPause;
private int current = 0;
private boolean running = true;
private int duration = 0;
private MediaPlayer mPlayer;
private SeekBar mSeekBarPlayer;
private TextView mMediaTime;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
mPlayer = MediaPlayer.create(getApplicationContext(), R.raw.goodthings);
btnPlay = (Button) findViewById(R.id.button1);
btnPause = (Button) findViewById(R.id.button2);
mMediaTime = (TextView)findViewById(R.id.mediaTime);
mSeekBarPlayer = (SeekBar)findViewById(R.id.progress_bar);
mPlayer.setOnPreparedListener(this);
mSeekBarPlayer.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(fromUser){
mPlayer.seekTo(progress);
updateTime();
}
}
});
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mPlayer.start();
mSeekBarPlayer.postDelayed(onEverySecond, 1000);
}
public void onCompletion( MediaPlayer mPlayer)
{
mPlayer.release();
}
});
btnPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mPlayer.pause();
}
public void onCompletion( MediaPlayer mPlayer)
{
mPlayer.release();
}
});
}
private Runnable onEverySecond = new Runnable() {
#Override
public void run(){
if(true == running){
if(mSeekBarPlayer != null) {
mSeekBarPlayer.setProgress(mPlayer.getCurrentPosition());
}
if(mPlayer.isPlaying()) {
mSeekBarPlayer.postDelayed(onEverySecond, 1000);
updateTime();
}
}
}
};
private void updateTime(){
do {
current = mPlayer.getCurrentPosition();
System.out.println("duration - " + duration + " current- "
+ current);
int dSeconds = (int) (duration / 1000) % 60 ;
int dMinutes = (int) ((duration / (1000*60)) % 60);
int dHours = (int) ((duration / (1000*60*60)) % 24);
int cSeconds = (int) (current / 1000) % 60 ;
int cMinutes = (int) ((current / (1000*60)) % 60);
int cHours = (int) ((current / (1000*60*60)) % 24);
if(dHours == 0){
mMediaTime.setText(String.format("%02d:%02d / %02d:%02d", cMinutes, cSeconds, dMinutes, dSeconds));
}else{
mMediaTime.setText(String.format("%02d:%02d:%02d / %02d:%02d:%02d", cHours, cMinutes, cSeconds, dHours, dMinutes, dSeconds));
}
try{
Log.d("Value: ", String.valueOf((int) (current * 100 / duration)));
if(mSeekBarPlayer.getProgress() >= 100){
break;
}
}catch (Exception e) {}
}while (mSeekBarPlayer.getProgress() <= 100);
}
#Override
public void onPrepared(MediaPlayer arg0) {
// TODO Auto-generated method stub
duration = mPlayer.getDuration();
mSeekBarPlayer.setMax(duration);
mSeekBarPlayer.postDelayed(onEverySecond, 1000);
}
}
when you rotate your device, onCreate() is called again, so all the stuff you do in onCreate() is done all over again - which means recreating your MediaPlayer and re-setting all of the variables.
What you need to do is only create those things if this is the first time onCreate() is being called.
Have a look here for more info on that.:
http://developer.android.com/guide/topics/resources/runtime-changes.html
This sort of question seems to have come up a here a lot, but they are all a slightly different case to mine and have just confused me. I am trying to get my SeekBar to synchronise with a single and specified mp3. With the code below, the audio plays and if you move the SeekBar the audio DOES seek, however the SeekBar does not move on its own to update with the music. Could someone please see if they can find the problem that is stopping the SeekBar from updating?
FIXED NOW but don't know why it fixed.
This is my FIXED Java code. Changes in bold:
MediaPlayer mediaPlayer;
Button buttonPlayPause;
ImageView Image;
SeekBar seekBar;
Handler handler;
private int stateMediaPlayer;
private final int stateMP_NotStarter = 0;
private final int stateMP_Playing = 1;
private final int stateMP_Pausing = 2;
private int mediaPos;
private int mediaMax;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playerwere);
Image = (ImageView) findViewById(R.id.pdfview);
Image.setImageResource(R.drawable.wereim);
seekBar = (SeekBar) findViewById(R.id.seekBar);
buttonPlayPause = (Button) findViewById(R.id.playpause);
buttonPlayPause.setOnClickListener(buttonPlayPauseOnClickListener);
seekBar.setOnSeekBarChangeListener(seekBarOnSeekChangeListener);
initMediaPlayer();
mediaPos = mediaPlayer.getCurrentPosition();
mediaMax = mediaPlayer.getDuration();
seekBar.setMax(mediaMax); // Set the Maximum range of the
// seekBar.setProgress(mediaPos);// set
// current progress to song's
seekBar.setProgress(mediaPos);// set current progress to song's
handler.removeCallbacks(moveSeekBarThread);
handler.postDelayed(moveSeekBarThread, 100);
}
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
// seconds
} **else {
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
// seconds
}**
}
};
private void initMediaPlayer() {
handler = new Handler();
mediaPlayer = new MediaPlayer();
mediaPlayer = MediaPlayer.create(were.this, R.raw.were);
stateMediaPlayer = stateMP_NotStarter;
}
Button.OnClickListener buttonPlayPauseOnClickListener = new Button.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (stateMediaPlayer) {
case stateMP_NotStarter:
mediaPlayer.start();
buttonPlayPause
.setBackgroundResource(android.R.drawable.ic_media_pause);
stateMediaPlayer = stateMP_Playing;
break;
case stateMP_Playing:
mediaPlayer.pause();
buttonPlayPause
.setBackgroundResource(android.R.drawable.ic_media_play);
stateMediaPlayer = stateMP_Pausing;
break;
case stateMP_Pausing:
mediaPlayer.start();
buttonPlayPause
.setBackgroundResource(android.R.drawable.ic_media_pause);
stateMediaPlayer = stateMP_Playing;
break;
}
}
};
SeekBar.OnSeekBarChangeListener seekBarOnSeekChangeListener = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
mediaPlayer.seekTo(progress);
seekBar.setProgress(progress);
}
}
};
}
I have a Fragment within a FrameLayout. The Fragment contains a VideoView amongst other things. If I modify the FrameLayout's left position (by calling its layout(...) method), the FrameLayout including the Fragment showing within it re-position themselves correctly, all except the VideoView, which sometimes re-positions itself but most often stays put. Anyone know why possibly the VideoView is not re-positioning itself along with its parent, and how I might be able to get it to do so?
Gave up in the end. Doesn't seem to be a straightforward workaround for re-positioning a VideoView, or any workaround for that matter. What I'm doing now instead is to play the video full screen in a new activity.
Try to use this source code for you VideoView.
public class CustomMediaController extends FrameLayout {
/**
* Public interface to handle FullScreenRequest. User can implement this
* interface to make the VideoPlayer Change to FullScreen. The user must
* handle show/hide of views. If the user do not add a Handler the
* FullScreen control button will be hided.
*
* #author Anis
*
*/
public interface FullScreenMediaPlayer {
/**
* Event callback when the MediaPlayer request the FullScreen.
*/
public void onFullScreenRequest();
/**
* Event callback when the MediaPlayer request the go back to normal
* size.
*/
public void onStreatchScreenRequest();
/**
* CallBackEvent when the MediaPlayer is Playing
*/
public void onPlaying();
}
private MediaPlayerControl mPlayer;
private final Context mContext;
private View mAnchor;
private View mRoot;
private View mDecor;
private ProgressBar mProgress;
private TextView mEndTime, mCurrentTime;
private boolean mShowing;
private boolean mDragging;
private static final int sDefaultTimeout = 3000;
private static final int FADE_OUT = 1;
private static final int SHOW_PROGRESS = 2;
private final boolean mUseFastForward;
private boolean mFromXml;
private boolean mListenersSet;
private View.OnClickListener mNextListener, mPrevListener;
StringBuilder mFormatBuilder;
Formatter mFormatter;
private ImageButton mPauseButton;
private ImageButton mFfwdButton;
private ImageButton mRewButton;
private ImageButton mNextButton;
private ImageButton mPrevButton;
// Add Streach colomn
private ImageButton mFullScreenButton;
private boolean isFullSreen;
private FullScreenMediaPlayer fullScreenListener;
public CustomMediaController(Context context, AttributeSet attrs) {
super(context, attrs);
mRoot = this;
mContext = context;
mUseFastForward = true;
mFromXml = true;
isFullSreen = false;
}
#Override
public void onFinishInflate() {
if (mRoot != null)
initControllerView(mRoot);
}
public CustomMediaController(Context context, boolean useFastForward) {
super(context);
mContext = context;
mUseFastForward = useFastForward;
initFloatingWindow();
}
public CustomMediaController(Context context) {
super(context);
mContext = context;
mUseFastForward = true;
initFloatingWindow();
}
private void initFloatingWindow() {
mDecor = this;
mDecor.setOnTouchListener(mTouchListener);
setFocusable(true);
setFocusableInTouchMode(true);
setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
requestFocus();
}
private final OnTouchListener mTouchListener = new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (mShowing) {
hide();
}
}
return false;
}
};
public void setMediaPlayer(MediaPlayerControl player) {
mPlayer = player;
updatePausePlay();
}
/**
* Set the view that acts as the anchor for the control view. This can for
* example be a VideoView, or your Activity's main view.
*
* #param view
* The view to which to anchor the controller when it is visible.
*/
public void setAnchorView(View view) {
mAnchor = view;
FrameLayout.LayoutParams frameParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT);
removeAllViews();
View v = makeControllerView();
addView(v, frameParams);
}
/**
* Create the view that holds the widgets that control playback. Derived
* classes can override this to create their own.
*
* #return The controller view.
* #hide This doesn't work as advertised
*/
protected View makeControllerView() {
LayoutInflater inflate = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mRoot = inflate.inflate(R.layout.media_controller, null);
initControllerView(mRoot);
return mRoot;
}
private void initControllerView(View v) {
mPauseButton = (ImageButton) v.findViewById(R.id.pause);
if (mPauseButton != null) {
mPauseButton.requestFocus();
mPauseButton.setOnClickListener(mPauseListener);
}
mFfwdButton = (ImageButton) v.findViewById(R.id.ffwd);
if (mFfwdButton != null) {
mFfwdButton.setOnClickListener(mFfwdListener);
if (!mFromXml) {
mFfwdButton.setVisibility(mUseFastForward ? View.VISIBLE : View.GONE);
}
}
mRewButton = (ImageButton) v.findViewById(R.id.rew);
if (mRewButton != null) {
mRewButton.setOnClickListener(mRewListener);
if (!mFromXml) {
mRewButton.setVisibility(mUseFastForward ? View.VISIBLE : View.GONE);
}
}
// By default these are hidden. They will be enabled when
// setPrevNextListeners() is called
mNextButton = (ImageButton) v.findViewById(R.id.next);
if (mNextButton != null && !mFromXml && !mListenersSet) {
mNextButton.setVisibility(View.GONE);
}
mPrevButton = (ImageButton) v.findViewById(R.id.prev);
if (mPrevButton != null && !mFromXml && !mListenersSet) {
mPrevButton.setVisibility(View.GONE);
}
mProgress = (ProgressBar) v.findViewById(R.id.mediacontroller_progress);
if (mProgress != null) {
if (mProgress instanceof SeekBar) {
SeekBar seeker = (SeekBar) mProgress;
seeker.setOnSeekBarChangeListener(mSeekListener);
}
mProgress.setMax(1000);
}
mEndTime = (TextView) v.findViewById(R.id.time);
mCurrentTime = (TextView) v.findViewById(R.id.time_current);
mFormatBuilder = new StringBuilder();
mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
mFullScreenButton = (ImageButton) v.findViewById(R.id.video_fullscreen);
installFullScreenListener();
installPrevNextListeners();
}
/**
* Show the controller on screen. It will go away automatically after 3
* seconds of inactivity.
*/
public void show() {
show(sDefaultTimeout);
}
/**
* Show the controller on screen. It will go away automatically after
* 'timeout' milliseconds of inactivity.
*
* #param timeout
* The timeout in milliseconds. Use 0 to show the controller
* until hide() is called.
*/
public void show(int timeout) {
if (!mShowing && mAnchor != null) {
setProgress();
addToFrameAncherLayout();
mShowing = true;
}
updatePausePlay();
// cause the progress bar to be updated even if mShowing
// was already true. This happens, for example, if we're
// paused with the progress bar showing the user hits play.
mHandler.sendEmptyMessage(SHOW_PROGRESS);
Message msg = mHandler.obtainMessage(FADE_OUT);
if (timeout != 0) {
mHandler.removeMessages(FADE_OUT);
mHandler.sendMessageDelayed(msg, timeout);
}
}
private void addToFrameAncherLayout() {
if ((mDecor != null) && (mDecor.getParent() == null)) {
if (mAnchor instanceof FrameLayout) {
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.BOTTOM;
((FrameLayout) mAnchor).addView(mDecor, params);
mDecor.setVisibility(View.VISIBLE);
} else {
// int[] anchorpos = new int[2];
// mAnchor.getLocationOnScreen(anchorpos);
//
// WindowManager.LayoutParams p = new
// WindowManager.LayoutParams();
// p.gravity = Gravity.TOP;
// p.width = mAnchor.getWidth();
// p.height = LayoutParams.WRAP_CONTENT;
// p.x = anchorpos[0];
// p.y = anchorpos[1] + mAnchor.getHeight() -
// mDecor.getHeight();
// p.format = PixelFormat.TRANSLUCENT;
// p.type = WindowManager.LayoutParams.TYPE_APPLICATION_PANEL;
// p.flags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
// p.token = null;
// p.windowAnimations = 0; //
// android.R.style.DropDownAnimationDown;
// mWindowManager.addView(mDecor, p);
// Logger.e("Ancher is not a Frame Layout usinf a Blocking Window");
}
}
mDecor.setVisibility(View.VISIBLE);
}
public boolean isShowing() {
return mShowing;
}
/**
* Remove the controller from the screen.
*/
public void hide() {
if (mAnchor == null)
return;
if (mShowing) {
try {
mHandler.removeMessages(SHOW_PROGRESS);
// TODO must be a New View
if (mDecor != null) {
if (mAnchor instanceof FrameLayout) {
// ((FrameLayout) mAnchor).removeView(mDecor);
mDecor.setVisibility(View.GONE);
} else {
// mWindowManager.removeView(mRoot);
}
}
} catch (IllegalArgumentException ex) {
Log.w("MediaController", "already removed");
}
mShowing = false;
}
}
static class ProgressHandler extends Handler {
WeakReference<CustomMediaController> mediaControllerReference;
ProgressHandler(CustomMediaController mediaController) {
mediaControllerReference = new WeakReference<CustomMediaController>(mediaController);
}
#Override
public void handleMessage(Message msg) {
CustomMediaController mediaController = mediaControllerReference.get();
if (mediaController != null) {
int pos;
switch (msg.what) {
case FADE_OUT:
mediaController.hide();
break;
case SHOW_PROGRESS:
pos = mediaController.setProgress();
if (!mediaController.mDragging && mediaController.mShowing
&& mediaController.mPlayer.isPlaying()) {
msg = obtainMessage(SHOW_PROGRESS);
sendMessageDelayed(msg, 1000 - (pos % 1000));
}
break;
}
}
}
}
private final Handler mHandler = new ProgressHandler(this);
private String stringForTime(int timeMs) {
int totalSeconds = timeMs / 1000;
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
mFormatBuilder.setLength(0);
if (hours > 0) {
return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
} else {
return mFormatter.format("%02d:%02d", minutes, seconds).toString();
}
}
private int setProgress() {
if (mPlayer == null || mDragging) {
return 0;
}
int position = mPlayer.getCurrentPosition();
int duration = mPlayer.getDuration();
if (mProgress != null) {
if (duration > 0) {
// use long to avoid overflow
long pos = 1000L * position / duration;
mProgress.setProgress((int) pos);
}
int percent = mPlayer.getBufferPercentage();
mProgress.setSecondaryProgress(percent * 10);
}
if (mEndTime != null)
mEndTime.setText(stringForTime(duration));
if (mCurrentTime != null)
mCurrentTime.setText(stringForTime(position));
return position;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
show(sDefaultTimeout);
return true;
}
#Override
public boolean onTrackballEvent(MotionEvent ev) {
show(sDefaultTimeout);
return false;
}
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
int keyCode = event.getKeyCode();
if (event.getRepeatCount() == 0
&& (keyCode == KeyEvent.KEYCODE_HEADSETHOOK || keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE || keyCode == KeyEvent.KEYCODE_SPACE)) {
doPauseResume();
show(sDefaultTimeout);
return true;
} else if (keyCode == KeyEvent.KEYCODE_MEDIA_STOP) {
if (mPlayer.isPlaying()) {
mPlayer.pause();
updatePausePlay();
}
return true;
} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
// don't show the controls for volume adjustment
return super.dispatchKeyEvent(event);
} else if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_MENU) {
hide();
return true;
} else {
show(sDefaultTimeout);
}
return super.dispatchKeyEvent(event);
}
private final View.OnClickListener mPauseListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
doPauseResume();
show(sDefaultTimeout);
}
};
private void updatePausePlay() {
if (mRoot == null)
return;
ImageButton button = (ImageButton) mRoot.findViewById(R.id.pause);
if (button == null)
return;
if (mPlayer.isPlaying()) {
button.setImageResource(R.drawable.ic_media_pause);
} else {
button.setImageResource(R.drawable.ic_media_play);
}
}
private void doPauseResume() {
if (mPlayer.isPlaying()) {
mPlayer.pause();
} else {
mPlayer.start();
}
updatePausePlay();
}
private final OnSeekBarChangeListener mSeekListener = new OnSeekBarChangeListener() {
long duration;
#Override
public void onStartTrackingTouch(SeekBar bar) {
show(3600000);
duration = mPlayer.getDuration();
}
#Override
public void onProgressChanged(SeekBar bar, int progress,
boolean fromtouch) {
if (fromtouch) {
mDragging = true;
duration = mPlayer.getDuration();
long newposition = (duration * progress) / 1000L;
mPlayer.seekTo((int) newposition);
if (mCurrentTime != null)
mCurrentTime
.setText(stringForTime((int) newposition));
} else {
if ((fullScreenListener != null) && (progress > 0)) {
fullScreenListener.onPlaying();
}
}
}
#Override
public void onStopTrackingTouch(SeekBar bar) {
mDragging = false;
setProgress();
updatePausePlay();
show(sDefaultTimeout);
}
};
#Override
public void setEnabled(boolean enabled) {
if (mPauseButton != null) {
mPauseButton.setEnabled(enabled);
}
if (mFfwdButton != null) {
mFfwdButton.setEnabled(enabled);
}
if (mRewButton != null) {
mRewButton.setEnabled(enabled);
}
if (mNextButton != null) {
mNextButton.setEnabled(enabled && mNextListener != null);
}
if (mPrevButton != null) {
mPrevButton.setEnabled(enabled && mPrevListener != null);
}
if (mProgress != null) {
mProgress.setEnabled(enabled);
}
super.setEnabled(enabled);
}
private final View.OnClickListener mRewListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = mPlayer.getCurrentPosition();
pos -= 5000; // milliseconds
mPlayer.seekTo(pos);
setProgress();
show(sDefaultTimeout);
}
};
private final View.OnClickListener mFfwdListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = mPlayer.getCurrentPosition();
pos += 15000; // milliseconds
mPlayer.seekTo(pos);
setProgress();
show(sDefaultTimeout);
}
};
private void installPrevNextListeners() {
if (mNextButton != null) {
mNextButton.setOnClickListener(mNextListener);
mNextButton.setEnabled(mNextListener != null);
}
if (mPrevButton != null) {
mPrevButton.setOnClickListener(mPrevListener);
mPrevButton.setEnabled(mPrevListener != null);
}
}
private void installFullScreenListener() {
if (mFullScreenButton != null) {
mFullScreenButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View aView) {
Preconditions.checkNotNull(fullScreenListener,
"IllegalStateExeption, FullScreen Button pressed with a nullable Listener");
if (isFullSreen) {
// send the request to handle normal size;
fullScreenListener.onStreatchScreenRequest();
isFullSreen = false;
updateFullScreenButton();
} else {
// Send request to go FullScreen
fullScreenListener.onFullScreenRequest();
isFullSreen = true;
updateFullScreenButton();
}
}
});
if (fullScreenListener == null) {
mFullScreenButton.setVisibility(View.GONE);
} else {
mFullScreenButton.setVisibility(View.VISIBLE);
}
}
}
/**
* Toggle the Full Screen Buttons
*/
private void updateFullScreenButton() {
if (isFullSreen) {
mFullScreenButton.setImageResource(R.drawable.windowmin);
} else {
mFullScreenButton.setImageResource(R.drawable.windowmax);
}
}
public void setPrevNextListeners(View.OnClickListener next, View.OnClickListener prev) {
mNextListener = next;
mPrevListener = prev;
mListenersSet = true;
if (mRoot != null) {
installPrevNextListeners();
if (mNextButton != null && !mFromXml) {
mNextButton.setVisibility(View.VISIBLE);
}
if (mPrevButton != null && !mFromXml) {
mPrevButton.setVisibility(View.VISIBLE);
}
}
}
public MediaPlayerControl getmPlayer() {
return mPlayer;
}
public void setmPlayer(MediaPlayerControl mPlayer) {
this.mPlayer = mPlayer;
}
#Override
public void dispatchWindowVisibilityChanged(int visibility) {
hide();
}
/**
* #return the fullScreenListener or null if any Listener is registred.
*/
public FullScreenMediaPlayer getFullScreenListener() {
return fullScreenListener;
}
/**
* #param aFullScreenListener
* the fullScreenListener.
*/
public void registerFullScreenListener(FullScreenMediaPlayer aFullScreenListener) {
Preconditions.checkNotNull(aFullScreenListener, "FullScreenListener cannot be null ");
fullScreenListener = aFullScreenListener;
installFullScreenListener();
}
public void removeFullScreenListerer() {
fullScreenListener = null;
installFullScreenListener();
}
/*
* (non-Javadoc)
*
* #see android.view.View#onDetachedFromWindow()
*/
#Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
hide();
}
}