Wowza sample link not working in android - android

I am doing to run wowza sample link in android. Wowza sample link is
here. but it is not working in android.
My code is here.
HelloAndroidActivity(MainActivity)
public class HelloAndroidActivity extends Activity implements OnClickListener {
private static String TAG = "androidEx2";
private Button buttonVideoSample;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate");
setContentView(R.layout.main);
buttonVideoSample = (Button) findViewById(R.id.buttonVideoSample);
buttonVideoSample.setOnClickListener(this);
}
public void onClick(View v) {
if (v.getId() == R.id.buttonVideoSample) {
String video_uri = "rtsp://184.72.239.149/vod/mp4:BigBuckBunny_115k.mov";
Intent intent = new Intent(this, VideoSample.class);
intent.putExtra("video_path", video_uri);
startActivity(intent);
}
}
}
Utils.java
public class Utils {
public static String durationInSecondsToString(int sec){
int hours = sec / 3600;
int minutes = (sec / 60) - (hours * 60);
int seconds = sec - (hours * 3600) - (minutes * 60) ;
String formatted = String.format("%d:%02d:%02d", hours, minutes, seconds);
return formatted;
}
}
VideoSampleActivity
public class VideoSample extends Activity implements OnSeekBarChangeListener, Callback, OnPreparedListener, OnCompletionListener, OnBufferingUpdateListener,
OnClickListener, OnSeekCompleteListener, AnimationListener {
private TextView textViewPlayed;
private TextView textViewLength;
private SeekBar seekBarProgress;
private SurfaceView surfaceViewFrame;
private ImageView imageViewPauseIndicator;
private MediaPlayer player;
private SurfaceHolder holder;
private ProgressBar progressBarWait;
private Timer updateTimer;
private Bundle extras;
private Animation hideMediaController;
private LinearLayout linearLayoutMediaController;
private static final String TAG = "log_tag";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videosample);
extras = getIntent().getExtras();
linearLayoutMediaController = (LinearLayout) findViewById(R.id.linearLayoutMediaController);
linearLayoutMediaController.setVisibility(View.GONE);
hideMediaController = AnimationUtils.loadAnimation(this, R.anim.disapearing);
hideMediaController.setAnimationListener(this);
imageViewPauseIndicator = (ImageView) findViewById(R.id.imageViewPauseIndicator);
imageViewPauseIndicator.setVisibility(View.GONE);
if (player != null) {
if (!player.isPlaying()) {
imageViewPauseIndicator.setVisibility(View.VISIBLE);
}
}
textViewPlayed = (TextView) findViewById(R.id.textViewPlayed);
textViewLength = (TextView) findViewById(R.id.textViewLength);
surfaceViewFrame = (SurfaceView) findViewById(R.id.surfaceViewFrame);
surfaceViewFrame.setOnClickListener(this);
surfaceViewFrame.setClickable(false);
seekBarProgress = (SeekBar) findViewById(R.id.seekBarProgress);
seekBarProgress.setOnSeekBarChangeListener(this);
seekBarProgress.setProgress(0);
progressBarWait = (ProgressBar) findViewById(R.id.progressBarWait);
holder = surfaceViewFrame.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
player = new MediaPlayer();
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnBufferingUpdateListener(this);
player.setOnSeekCompleteListener(this);
player.setScreenOnWhilePlaying(true);
player.setDisplay(holder);
}
private void playVideo() {
if (extras.getString("video_path").equals("VIDEO_URI")) {
showToast("Please, set the video URI in HelloAndroidActivity.java in onClick(View v) method");
} else {
new Thread(new Runnable() {
public void run() {
try {
player.setDataSource(VideoSample.this, Uri.parse(extras.getString("video_path")));
//player.setDataSource(extras.getString("video_path"));
//player.start();
player.prepare();
} catch (IllegalArgumentException e) {
showToast("Error while playing video");
Log.i(TAG, e.getMessage());
e.printStackTrace();
} catch (IllegalStateException e) {
showToast("Error while playing video");
Log.i(TAG, e.getMessage());
e.printStackTrace();
} catch (IOException e) {
showToast("Error while playing video. Please, check your network connection.");
Log.i(TAG, e.getMessage());
e.printStackTrace();
}
}
}).start();
}
}
private void showToast(final String string) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(VideoSample.this, string, Toast.LENGTH_LONG).show();
finish();
}
});
}
private void hideMediaController() {
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(5000);
runOnUiThread(new Runnable() {
public void run() {
linearLayoutMediaController.startAnimation(hideMediaController);
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
Log.i(TAG, "========== onProgressChanged : " + progress + " from user: " + fromUser);
if (!fromUser) {
textViewPlayed.setText(Utils.durationInSecondsToString(progress));
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
if (player.isPlaying()) {
progressBarWait.setVisibility(View.VISIBLE);
player.seekTo(seekBar.getProgress() * 1000);
Log.i(TAG, "========== SeekTo : " + seekBar.getProgress());
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
public void surfaceCreated(SurfaceHolder holder) {
playVideo();
}
public void surfaceDestroyed(SurfaceHolder holder) {
}
public void onPrepared(MediaPlayer mp) {
Log.i(TAG, "========== onPrepared ===========");
int duration = mp.getDuration() / 1000; // duration in seconds
seekBarProgress.setMax(duration);
textViewLength.setText(Utils.durationInSecondsToString(duration));
progressBarWait.setVisibility(View.GONE);
// Get the dimensions of the video
int videoWidth = player.getVideoWidth();
int videoHeight = player.getVideoHeight();
float videoProportion = (float) videoWidth / (float) videoHeight;
Log.i(TAG, "VIDEO SIZES: W: " + videoWidth + " H: " + videoHeight + " PROP: " + videoProportion);
// Get the width of the screen
int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
int screenHeight = getWindowManager().getDefaultDisplay().getHeight();
float screenProportion = (float) screenWidth / (float) screenHeight;
Log.i(TAG, "VIDEO SIZES: W: " + screenWidth + " H: " + screenHeight + " PROP: " + screenProportion);
// Get the SurfaceView layout parameters
android.view.ViewGroup.LayoutParams lp = surfaceViewFrame.getLayoutParams();
if (videoProportion > screenProportion) {
lp.width = screenWidth;
lp.height = (int) ((float) screenWidth / videoProportion);
} else {
lp.width = (int) (videoProportion * (float) screenHeight);
lp.height = screenHeight;
}
// Commit the layout parameters
surfaceViewFrame.setLayoutParams(lp);
// Start video
if (!player.isPlaying()) {
player.start();
updateMediaProgress();
linearLayoutMediaController.setVisibility(View.VISIBLE);
hideMediaController();
}
surfaceViewFrame.setClickable(true);
}
public void onCompletion(MediaPlayer mp) {
mp.stop();
if (updateTimer != null) {
updateTimer.cancel();
}
finish();
}
/**
* Change progress of mediaController
* */
private void updateMediaProgress() {
updateTimer = new Timer("progress Updater");
updateTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
seekBarProgress.setProgress(player.getCurrentPosition() / 1000);
}
});
}
}, 0, 1000);
}
public void onBufferingUpdate(MediaPlayer mp, int percent) {
int progress = (int) ((float) mp.getDuration() * ((float) percent / (float) 100));
seekBarProgress.setSecondaryProgress(progress / 1000);
}
public void onClick(View v) {
if (v.getId() == R.id.surfaceViewFrame) {
if (linearLayoutMediaController.getVisibility() == View.GONE) {
linearLayoutMediaController.setVisibility(View.VISIBLE);
hideMediaController();
} else if (player != null) {
if (player.isPlaying()) {
player.pause();
imageViewPauseIndicator.setVisibility(View.VISIBLE);
} else {
player.start();
imageViewPauseIndicator.setVisibility(View.GONE);
}
}
}
}
public void onSeekComplete(MediaPlayer mp) {
progressBarWait.setVisibility(View.GONE);
}
public void onAnimationEnd(Animation animation) {
}
public void onAnimationRepeat(Animation animation) {
}
public void onAnimationStart(Animation animation) {
linearLayoutMediaController.setVisibility(View.GONE);
}
}

I don't think there would be room in comments...
The view:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/hls_frame"
android:background="#000000"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<VideoView
android:id="#+id/video_player"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_gravity="center"
/>
<include layout="#layout/player_bar" />
</FrameLayout>
In the following code, the activity is passed in to a separate class (this would normally happen in the activity itself, but I need to support multiple players for older devices). The method of interest:
public void loadPlayer() {
_activity.setContentView(R.layout.hls_video_view);
if (_activity.url == null) {
Development.ExceptionMsg("Video Url is Null!");
return;
}
VideoView view = (VideoView) _activity.findViewById(R.id.video_player);
if (!_activity.isLive) {
//MediaController for vod only
MediaController controller = new MediaController(_activity);
controller.setAnchorView(view);
view.setMediaController(controller);
}
_activity.LogStreamStart();
_activity.HideBuffering();
view.setOnCompletionListener(this);
view.setOnPreparedListener(this);
view.setOnErrorListener(this);
//this is important, and should perhaps be part of the interface
view.setOnTouchListener(_activity);
view.setVideoURI(Uri.parse(_activity.url));
view.requestFocus();
view.start();
}

Related

When i rotate to landscape and then rotate back to portrait and choose next song it doesn't update the songinfo

Ok so I have an activity where I display a song that's playing, and I created another layout for landscape mode, I have an imageview that displays the album art from that song and a title in the actionbar, all display information of the playing song, but when I rotate the screen and then rotate back to portrait mode and switch song with my next button and then rotate on that other song, it still displays information of the previous song.
My first activity (displays all songs)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_songs);
recyclerView = findViewById(R.id.recyclerView);
if (recyclerView != null) {
recyclerView.setHasFixedSize(true);
}
songAdapter = new SongAdapter(this, songList);
recyclerView.setAdapter(songAdapter);
songAdapter.notifyDataSetChanged();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), linearLayoutManager.getOrientation());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.addItemDecoration(dividerItemDecoration);
//RelativeLayouts
mainLayout = findViewById(R.id.mainLayout);
secondLayout = findViewById(R.id.secondLayout);
currSong = findViewById(R.id.currSong);
//LinearLayouts
songThumbnail = findViewById(R.id.songThumbnail);
mToolbar = findViewById(R.id.mToolbar);
setSupportActionBar(mToolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(R.string.library);
}
tvCurrSongTitle = findViewById(R.id.tvCurrSongTitle);
tvCurrSongArtist = findViewById(R.id.tvCurrSongArtist);
recyclerView.addOnItemTouchListener(new OnItemClickListeners(this, new OnItemClickListeners.OnItemClickListener() {
#TargetApi(Build.VERSION_CODES.O)
#Override
public void onItemClick(View view, int position) {
songIndex = position;
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(songList.get(songIndex).getData());
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
Toast.makeText(getApplicationContext(), "You Clicked position: " + position + " " + songList.get(position).getData(), Toast.LENGTH_SHORT).show();
tvCurrSongTitle.setText(songList.get(position).getTitle());
tvCurrSongArtist.setText(songList.get(position).getArtist());
} catch (Exception e) {
e.printStackTrace();
}
}
}));
currSong.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent currSong = new Intent(getApplicationContext(), SongActivity.class);
currSong.putExtra("songIndex", songIndex);
startActivity(currSong);
}
});
My Song activity class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_song);
albumArtLarge = findViewById(R.id.albumArtLarge);
albumArt = findViewById(R.id.albumArt);
mBtnPlayPause = findViewById(R.id.mBtnPlayPause);
mBtnNext = findViewById(R.id.mBtnNext);
mBtnPrev = findViewById(R.id.mBtnPrev);
mBtnShuffle = findViewById(R.id.mBtnShuffle);
mBtnRepeat = findViewById(R.id.mBtnRepeat);
seekBar = findViewById(R.id.seekBar);
tvSongCurrentTime = findViewById(R.id.tvSongCurrentTime);
tvSongTotalTime = findViewById(R.id.tvSongTotalTime);
tvSongListSize = findViewById(R.id.tvSongListSize);
//Listeners
seekBar.setOnSeekBarChangeListener(this);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
Intent currSong = getIntent();
b = currSong.getExtras();
mCurrentIndex = (int) b.get("songIndex");
songActivityToolbar = findViewById(R.id.songActivityToolbar);
setSupportActionBar(songActivityToolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(songList.get(songIndex).getTitle());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
// Load album art clicked song
Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, songList.get(songIndex).getAlbumid());
Picasso.with(this)
.load(albumArtUri)
.error(R.drawable.blackgreygradientbackground)
.into(albumArtLarge);
Picasso.with(this)
.load(albumArtUri)
.error(R.drawable.albumcover)
.resize(500,500)
.into(albumArt);
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mBtnPlayPause.setImageResource(R.drawable.ic_action_pause_white);
tvSongListSize.setText((mCurrentIndex + 1) + "/" + songList.size());
updateProgressBar();
}
}
mBtnShuffle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isShuffle){
isShuffle = false;
Toast.makeText(getApplicationContext(), "Shuffle is off", Toast.LENGTH_SHORT ).show();
mBtnShuffle.setImageResource(R.drawable.ic_action_shuffle);
}else{
isShuffle = true;
Toast.makeText(getApplicationContext(), "Shuffle is on", Toast.LENGTH_SHORT).show();
mBtnShuffle.setImageResource(R.drawable.ic_shuffle_on);
isRepeat = false;
mBtnRepeat.setImageResource(R.drawable.ic_action_repeat);
}
}
});
mBtnRepeat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isRepeat){
isRepeat = false;
Toast.makeText(getApplicationContext(), "Repeat is off", Toast.LENGTH_SHORT).show();
mBtnRepeat.setImageResource(R.drawable.ic_action_repeat);
}else{
isRepeat = true;
Toast.makeText(getApplicationContext(), "Repeat is on", Toast.LENGTH_SHORT).show();
mBtnRepeat.setImageResource(R.drawable.ic_repeat_on);
isShuffle = false;
mBtnShuffle.setImageResource(R.drawable.ic_action_shuffle);
}
}
});
mBtnPlayPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
mBtnPlayPause.setImageResource(R.drawable.ic_action_play);
} else {
mediaPlayer.start();
mBtnPlayPause.setImageResource(R.drawable.ic_action_pause_white);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
mBtnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
nextSong();
}
});
mBtnPrev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
prevSong();
}
});
}
private void playSongNumber(final int index) {
try{
mediaPlayer.reset();
mediaPlayer.setDataSource(songList.get(index).getData());
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(songList.get(index).getTitle());
}
//Load album art
Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, songList.get(index).getAlbumid());
Picasso.with(getApplicationContext())
.load(albumArtUri)
.error(R.drawable.blackgreygradientbackground)
.into(albumArtLarge);
Picasso.with(getApplicationContext())
.load(albumArtUri)
.error(R.drawable.albumcover)
.resize(500,500)
.into(albumArt);
updateProgressBar();
}
});
seekBar.setProgress(0);
seekBar.setMax(100);
}catch (Exception e){
e.printStackTrace();
}
}
private void nextSong(){
mCurrentIndex++;
mCurrentIndex %= songList.size();
playSongNumber(mCurrentIndex);
mBtnPlayPause.setImageResource(R.drawable.ic_action_pause_white);
tvSongListSize.setText((mCurrentIndex + 1) + "/" + songList.size());
Toast.makeText(getApplicationContext(), "You Clicked position: " + mCurrentIndex + " " + songList.get(mCurrentIndex).getData(), Toast.LENGTH_SHORT).show();
}
private void prevSong(){
mCurrentIndex = mCurrentIndex > 0 ? mCurrentIndex - 1 : songList.size() - 1;
playSongNumber(mCurrentIndex);
mBtnPlayPause.setImageResource(R.drawable.ic_action_pause_white);
tvSongListSize.setText((mCurrentIndex + 1) + "/" + songList.size());
Toast.makeText(getApplicationContext(), "You Clicked position: " + mCurrentIndex + " " + songList.get(mCurrentIndex).getData(), Toast.LENGTH_SHORT).show();
}
#Override
public void onCompletion(MediaPlayer mp) {
if (isRepeat){
playSongNumber(mCurrentIndex);
}else if(isShuffle){
Random random = new Random();
mCurrentIndex = random.nextInt((songList.size() - 1) + 1);
tvSongListSize.setText((mCurrentIndex + 1) + "/" + songList.size());
playSongNumber(mCurrentIndex);
}else if (mCurrentIndex < songList.size()-1){
mediaPlayer.reset();
nextSong();
tvSongListSize.setText((mCurrentIndex + 1) + "/" + songList.size());
}else{
playSongNumber(0);
tvSongListSize.setText((1) + "/" + songList.size());
}
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(getApplicationContext(), "what:" + what + "extra:" +extra , Toast.LENGTH_SHORT).show();
return true;
}
private Runnable mUpdateTime = new Runnable() {
#Override
public void run() {
long songCurrentTime = mediaPlayer.getCurrentPosition();
long songTotalTime = mediaPlayer.getDuration();
tvSongCurrentTime.setText(""+utilities.msToTimer(songCurrentTime));
tvSongTotalTime.setText(""+utilities.msToTimer(songTotalTime));
int progress = (int)(utilities.getProgressPercentage(songCurrentTime, songTotalTime));
seekBar.setProgress(progress);
mHandler.postDelayed(this, 100);
}
};
public void updateProgressBar(){
mHandler.postDelayed(mUpdateTime, 100);
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
mHandler.removeCallbacks(mUpdateTime);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mHandler.removeCallbacks(mUpdateTime);
int songTotalTime = mediaPlayer.getDuration() ;
int currentPosition = utilities.progressToTimer(seekBar.getProgress(), songTotalTime);
mediaPlayer.seekTo(currentPosition);
updateProgressBar();
}
}
How can I update the album art on rotation, it only occurs when I rotate the screen, in portrait mode it all works fine and updates the information when I change the song.

Android media player seek bar not working

I am using seek bar media player in dialog, but seek bar does not work when I click on it
I am making call recorder application and using seek to play audio file. When I click on seek bar, it goes forward, but after 1 second it is set back to previous location.
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final Holder holder = new Holder();
View rowView;
rowView = inflater.inflate(R.layout.audio_calls_list_row, null);
holder.playpauseView = (LinearLayout) rowView.findViewById(R.id.play_pause_view);
holder.playpausebtn = (ImageButton) rowView.findViewById(R.id.play_pause_btn);
holder.callfileName = (TextView) rowView.findViewById(R.id.audiofileName);
holder.totaltime = (TextView) rowView.findViewById(R.id.durationtiming);
holder.callstatus1 = (ImageView) rowView.findViewById(R.id.callstatusid);
holder.btnshare = (ImageView) rowView.findViewById(R.id.btn_share);
holder.number = (TextView) rowView.findViewById(R.id.txt_number);
holder.filetimecreated = (TextView) rowView.findViewById(R.id.myaudiofiletime);
holder.filedatecreated = (TextView) rowView.findViewById(R.id.myaudiofiledate);
if (audioFileList.size() > 0) {
try {
mmr = new MediaMetadataRetriever();
mmr.setDataSource(audioFileList.get(position).getMyfilepath());
String durationStr = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
int millSecond = Integer.parseInt(durationStr);
//setting listview totaltime
holder.totaltime.setText(String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours((long) millSecond),
TimeUnit.MILLISECONDS.toMinutes((long) millSecond),
TimeUnit.MILLISECONDS.toSeconds((long) millSecond) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.
toMinutes((long) millSecond))));
String filename = audioFileList.get(position).filename;
final String call_type = filename.substring(25, 33);
int numlastpositionstr = filename.lastIndexOf("_");
String call_number = filename.substring(34, numlastpositionstr);
String call_time = filename.substring(16, 21);
String call_date = filename.substring(5, 15);
char[] call_timeArray = call_time.toCharArray();
for (int x = 0; x < call_timeArray.length; x++) {
if (call_timeArray[x] == '.') {
call_timeArray[x] = ':';
}
}
call_time = String.valueOf(call_timeArray);
holder.filetimecreated.setText(call_time);
holder.filedatecreated.setText(call_date);
String name = getContactDisplayNameByNumber(call_number, context);
holder.number.setText(call_number);
holder.callfileName.setText(name);
//status incomming or outgoing.
if (filename.contains(CallStatus.INCOMING) || filename.contains (CallStatus.incoming)) {
// if (call_type.equals(CallStatus.INCOMING) || call_type.equals(CallStatus.incoming)) {
holder.callstatus1.setBackgroundResource(R.drawable.ic_call_received_black_24dp);
} else {
holder.callstatus1.setBackgroundResource(R.drawable.ic_call_made_black_24dp);
}
// if (call_type.equals(CallStatus.OUTGOING) || call_type.equals(CallStatus.outgoing)) {
// holder.callstatus1.setBackgroundResource(android.R.drawable.sym_call_outgoing);
// }
} catch (Exception e) {
System.out.println("Exaption is here " + e);
}
} else {
Log.d("audiofilesize", "Audio file size is 0");
}
holder.playpausebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final AlertDialog.Builder audioPlayDialog = new AlertDialog.Builder(context, R.style.DialogTheme);
LayoutInflater inflater1 = LayoutInflater.from(context.getApplicationContext());
LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View layout1 = inflater1.inflate(R.layout.dialoguelayout, null);
audioPlayDialog.setView(layout1)
.setNeutralButton("", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
mediaPlayer.pause();
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
myHandler.removeCallbacks(UpdateSongTime);
filecompleted = false;
running = false;
}
});
audioPlayDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
try {
mediaPlayer.pause();
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
myHandler.removeCallbacks(UpdateSongTime);
filecompleted = false;
running = false;
} catch (Exception e) {
}
}
});
audioPlayDialog.setCancelable(true);
final ImageButton audioPlayDialogButton = (ImageButton) layout1.findViewById(R.id.your_dialog_button);
audioPlayDialogSeekBar = (SeekBar) layout1.findViewById(R.id.your_dialog_seekbar);
dfilename = (TextView) layout1.findViewById(R.id.dcallnameid);
remaingtime = (TextView) layout1.findViewById(R.id.dremaingtime);
totaltime = (TextView) layout1.findViewById(R.id.dtotaltime);
callstatus = (TextView) layout1.findViewById(R.id.dcallstatus);
audioPlayDialog.create();
audioPlayDialog.show();
String[] call_type1 = getcallstatus(position);
callstatus.setText(call_type1[0]);
if (call_type1[1].equals("")) {
dfilename.setText(call_type1[2]);
} else {
dfilename.setText(call_type1[1]);
}
audioPlayDialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (filecompleted == true) {
updateTime();
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
audioPlayDialogButton.setBackgroundResource(R.drawable.ic_play_circle_outline_black_48dp);
}
} else {
mediaPlayer.start();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
audioPlayDialogButton.setBackgroundResource(R.drawable.ic_pause_circle_outline_black_48dp);
}
}
} else {
try {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
audioPlayDialogButton.setBackgroundResource(R.drawable.ic_play_circle_outline_black_48dp);
}
} else {
mediaPlayer.start();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
audioPlayDialogButton.setBackgroundResource(R.drawable.ic_pause_circle_outline_black_48dp);
}
}
} catch (Exception e) {
}
}
}
});
audioPlayDialogSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
Log.d("Progress changed", "progress changed" + progress);
audioPlayDialogSeekBar.setMax((int) finalTime);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
Log.d("starttracking", "progress starTT");
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
final Uri data = Uri.parse(audioFileList.get(position).getMyfilepath());
System.out.println("file Path is here" + data.getPath());
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(context, data);
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
finalTime = mp.getDuration();
running = true;
mp.start();
// audioPlayDialogSeekBar = true;
audioPlayDialogSeekBar.setMax(mediaPlayer.getDuration());
if (finalTime != 0) {
totaltime.setText(String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours((long) finalTime),
TimeUnit.MILLISECONDS.toMinutes((long) finalTime),
TimeUnit.MILLISECONDS.toSeconds((long) finalTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.
toMinutes((long) finalTime))));
}
}
});
} catch (Exception e) {
}
myHandler = new Handler();
totaltime.setText(String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours((long) finalTime),
TimeUnit.MILLISECONDS.toMinutes((long) finalTime),
TimeUnit.MILLISECONDS.toSeconds((long) finalTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.
toMinutes((long) finalTime))));
updateTime();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
audioPlayDialogButton.setBackgroundResource (R.drawable.ic_pause_circle_outline_black_48dp);
}
firsttime = false;
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
audioPlayDialogSeekBar.setProgress(0);
audioPlayDialogButton.setBackgroundResource (R.drawable.ic_play_circle_outline_black_48dp);
filecompleted = true;
startTime = 0;
mediaPlayer.pause();
checkpoint = true;
mp.seekTo(10);
mp.pause();
}
});
mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
});
}
private void updateTime() {
UpdateSongTime = new Runnable() {
public void run() {
if (running == true) {
startTime = mediaPlayer.getCurrentPosition();
}
if (filecompleted == true) {
if (checkpoint) {
startTime = 0;
checkpoint = false;
}
}
if (startTime > (finalTime - 100)) {
remaingtime.setText("00:00:00");
} else {
remaingtime.setText(String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours((long) startTime),
TimeUnit.MILLISECONDS.toMinutes((long) startTime),
TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.
toMinutes((long) startTime))));
audioPlayDialogSeekBar.setProgress((int) startTime);
myHandler.postDelayed(this, 100);
}
}
};
myHandler1 = new Handler();
UpdateSongTime1 = new Runnable() {
public void run() {
myHandler.postDelayed(this, 100);
}
};
startTime = mediaPlayer.getCurrentPosition();
audioPlayDialogSeekBar.setProgress((int) startTime);
myHandler.postDelayed(UpdateSongTime, 100);
}
});
holder.btnshare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// final Uri data = Uri.parse(audioFileList.get(position).getMyfilepath());
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("audio/*");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File (audioFileList.get(position).getMyfilepath())));
context.startActivity(intent);
}
});
return rowView;
}
Where did you call the media.seekTo(position)? As far as I can see, you have not called that on your seekbarchangelistener.
And as you are always setting the seekbar position relative to your song progress.. it will always go back to the previous state..
Solution:
In your seekbarchangelistener.. use the onSeekbarchanged and use (Media player).seekTo(position)
try {
if (mediaPlayer.isPlaying() || mediaPlayer != null) {
if (fromUser)
mediaPlayer.seekTo(progress);
} else if (mediaPlayer == null) {
Toast.makeText(context.getApplicationContext(), "Media is not running",
Toast.LENGTH_SHORT).show();
seekBar.setProgress(0);
}
} catch (Exception e) {
Log.e("seek bar", "" + e);
seekBar.setEnabled(false);
}
I use this code and issue resolved

Android Vitamio 4.2 update 5.0 crash

I updated Vitamio 4.2.2 to 5.0.0 as Google requested because of security issues in developer console. But with the same codes. Only changed Vitamio.isInitialized(getApplicationContext()); There is not error. Application was installed. But video not playing. How can i do for this?
public class MainActivity extends Activity implements MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnVideoSizeChangedListener, SurfaceHolder.Callback {
private static String TAG = MainActivity.class.getSimpleName();
private static String ShowTV = "http://mn-i.mncdn.com/showtv_ios/smil:showtv.smil/playlist.m3u8";";
private TextView tvLoader;
private int mVideoWidth;
private int mVideoHeight;
public MediaPlayer mMediaPlayer;
private SurfaceView mPreview;
private SurfaceHolder holder;
private boolean mIsVideoSizeKnown = false;
private boolean mIsVideoReadyToBePlayed = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Vitamio.isInitialized(getApplicationContext());
if (Build.VERSION.SDK_INT < 16)
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
else
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
tvLoader = (TextView) findViewById(R.id.tvLoader);
mPreview = (SurfaceView) findViewById(R.id.surface);
holder = mPreview.getHolder();
holder.addCallback(this);
holder.setFormat(PixelFormat.RGBA_8888);
}
public void playVideo() {
doCleanUp();
try {
// Create a new media player and set the listeners
mMediaPlayer = new MediaPlayer(this);
mMediaPlayer.setDataSource(ShowTv);
mMediaPlayer.setDisplay(holder);
mMediaPlayer.prepareAsync();
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
} catch (Exception e) {
Log.e(TAG, "error: " + e.getMessage(), e);
}
}
public void onBufferingUpdate(MediaPlayer arg0, int percent) {
// Log.d(TAG, "onBufferingUpdate percent:" + percent);
}
public void onCompletion(MediaPlayer arg0) {
Log.d(TAG, "onCompletion called");
}
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
Log.v(TAG, "onVideoSizeChanged called");
if (width == 0 || height == 0) {
Log.e(TAG, "invalid video width(" + width + ") or height(" + height + ")");
return;
}
mIsVideoSizeKnown = true;
mVideoWidth = width;
mVideoHeight = height;
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
public void onPrepared(MediaPlayer mediaplayer) {
Log.d(TAG, "onPrepared called");
mIsVideoReadyToBePlayed = true;
tvLoader.setVisibility(View.GONE);
if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
startVideoPlayback();
}
}
public void surfaceChanged(SurfaceHolder surfaceholder, int i, int j, int k) {
Log.d(TAG, "surfaceChanged called");
}
public void surfaceDestroyed(SurfaceHolder surfaceholder) {
Log.d(TAG, "surfaceDestroyed called");
}
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "surfaceCreated called");
playVideo();
}
#Override
protected void onPause() {
super.onPause();
releaseMediaPlayer();
doCleanUp();
}
#Override
protected void onDestroy() {
super.onDestroy();
releaseMediaPlayer();
doCleanUp();
}
public void releaseMediaPlayer() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
private void doCleanUp() {
tvLoader = (TextView) findViewById(R.id.tvLoader);
tvLoader.setVisibility(View.VISIBLE);
mVideoWidth = 0;
mVideoHeight = 0;
mIsVideoReadyToBePlayed = false;
mIsVideoSizeKnown = false;
}
private void startVideoPlayback() {
Log.v(TAG, "startVideoPlayback");
holder.setFixedSize(mVideoWidth, mVideoHeight);
mMediaPlayer.start();
}
}

MediaPlayer.prepare() THROWS illegeal state exception

I am trying to stream a Video in android. For one uri it works fine if i go to another it throws illegalstateexception. Actually my code is
public class VideoSample extends Activity implements OnSeekBarChangeListener, Callback, OnPreparedListener, OnCompletionListener, OnBufferingUpdateListener,
OnClickListener, OnSeekCompleteListener, AnimationListener {
private TextView textViewPlayed;
private TextView textViewLength;
private SeekBar seekBarProgress;
private SurfaceView surfaceViewFrame;
private ImageView imageViewPauseIndicator;
private MediaPlayer player;
private SurfaceHolder holder;
private ProgressBar progressBarWait;
private Timer updateTimer;
private Bundle extras;
private Animation hideMediaController;
private LinearLayout linearLayoutMediaController;
private static final String TAG = "androidEx2 = VideoSample";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videosample);
extras = getIntent().getExtras();
linearLayoutMediaController = (LinearLayout) findViewById(R.id.linearLayoutMediaController);
linearLayoutMediaController.setVisibility(View.GONE);
hideMediaController = AnimationUtils.loadAnimation(this, R.anim.disapearing);
hideMediaController.setAnimationListener(this);
imageViewPauseIndicator = (ImageView) findViewById(R.id.imageViewPauseIndicator);
imageViewPauseIndicator.setVisibility(View.GONE);
if (player != null) {
if (!player.isPlaying()) {
imageViewPauseIndicator.setVisibility(View.VISIBLE);
}
}
textViewPlayed = (TextView) findViewById(R.id.textViewPlayed);
textViewLength = (TextView) findViewById(R.id.textViewLength);
surfaceViewFrame = (SurfaceView) findViewById(R.id.surfaceViewFrame);
surfaceViewFrame.setOnClickListener(this);
surfaceViewFrame.setClickable(false);
seekBarProgress = (SeekBar) findViewById(R.id.seekBarProgress);
seekBarProgress.setOnSeekBarChangeListener(this);
seekBarProgress.setProgress(0);
progressBarWait = (ProgressBar) findViewById(R.id.progressBarWait);
holder = surfaceViewFrame.getHolder();
holder.addCallback(this);
player = new MediaPlayer();
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnBufferingUpdateListener(this);
player.setOnSeekCompleteListener(this);
player.setScreenOnWhilePlaying(true);
}
private void playVideo() {
if (extras.getString("video_path").equals("VIDEO_URI")) {
showToast("Please, set the video URI in HelloAndroidActivity.java in onClick(View v) method");
} else {
new Thread(new Runnable() {
public void run() {
try {
player.setDataSource(extras.getString("video_path"));
Log.i(TAG, extras.getString("video_path"));
player.prepare();
} catch (IllegalArgumentException e) {
showToast("Error while playing video Argument");
Log.i(TAG, "========== IllegalArgumentException ===========");
e.printStackTrace();
} catch (IllegalStateException e) {
showToast("Error while playing video State");
Log.i(TAG, "========== IllegalStateException ===========");
e.printStackTrace();
} catch (IOException e) {
showToast("Error while playing video. Please, check your network connection.");
Log.i(TAG, "========== IOException ===========");
e.printStackTrace();
}
}
}).start();
}
}
private void showToast(final String string) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(VideoSample.this, string, Toast.LENGTH_LONG).show();
finish();
}
});
}
private void hideMediaController() {
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(5000);
runOnUiThread(new Runnable() {
public void run() {
linearLayoutMediaController.startAnimation(hideMediaController);
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
Log.i(TAG, "========== onProgressChanged : " + progress + " from user: " + fromUser);
if (!fromUser) {
textViewPlayed.setText(Utils.durationInSecondsToString(progress));
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar) {
if (player.isPlaying()) {
progressBarWait.setVisibility(View.VISIBLE);
player.seekTo(seekBar.getProgress() * 1000);
Log.i(TAG, "========== SeekTo : " + seekBar.getProgress());
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub
}
public void surfaceCreated(SurfaceHolder holder) {
player.setDisplay(holder);
playVideo();
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
public void onPrepared(MediaPlayer mp) {
Log.i(TAG, "========== onPrepared ===========");
int duration = mp.getDuration() / 1000; // duration in seconds
seekBarProgress.setMax(duration);
textViewLength.setText(Utils.durationInSecondsToString(duration));
progressBarWait.setVisibility(View.GONE);
// Get the dimensions of the video
int videoWidth = player.getVideoWidth();
int videoHeight = player.getVideoHeight();
float videoProportion = (float) videoWidth / (float) videoHeight;
Log.i(TAG, "VIDEO SIZES: W: " + videoWidth + " H: " + videoHeight + " PROP: " + videoProportion);
// Get the width of the screen
int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
int screenHeight = getWindowManager().getDefaultDisplay().getHeight();
float screenProportion = (float) screenWidth / (float) screenHeight;
Log.i(TAG, "VIDEO SIZES: W: " + screenWidth + " H: " + screenHeight + " PROP: " + screenProportion);
// Get the SurfaceView layout parameters
android.view.ViewGroup.LayoutParams lp = surfaceViewFrame.getLayoutParams();
if (videoProportion > screenProportion) {
lp.width = screenWidth;
lp.height = (int) ((float) screenWidth / videoProportion);
} else {
lp.width = (int) (videoProportion * (float) screenHeight);
lp.height = screenHeight;
}
// Commit the layout parameters
surfaceViewFrame.setLayoutParams(lp);
// Start video
if (!player.isPlaying()) {
player.start();
updateMediaProgress();
linearLayoutMediaController.setVisibility(View.VISIBLE);
hideMediaController();
}
surfaceViewFrame.setClickable(true);
}
public void onCompletion(MediaPlayer mp) {
mp.stop();
if (updateTimer != null) {
updateTimer.cancel();
}
finish();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
player.release();
}
/**
* Change progress of mediaController
* */
private void updateMediaProgress() {
updateTimer = new Timer("progress Updater");
updateTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
seekBarProgress.setProgress(player.getCurrentPosition() / 1000);
}
});
}
}, 0, 1000);
}
public void onBufferingUpdate(MediaPlayer mp, int percent) {
int progress = (int) ((float) mp.getDuration() * ((float) percent / (float) 100));
seekBarProgress.setSecondaryProgress(progress / 1000);
}
public void onClick(View v) {
if (v.getId() == R.id.surfaceViewFrame) {
if (linearLayoutMediaController.getVisibility() == View.GONE) {
linearLayoutMediaController.setVisibility(View.VISIBLE);
hideMediaController();
} else if (player != null) {
if (player.isPlaying()) {
player.pause();
imageViewPauseIndicator.setVisibility(View.VISIBLE);
} else {
player.start();
imageViewPauseIndicator.setVisibility(View.GONE);
}
}
}
}
public void onSeekComplete(MediaPlayer mp) {
progressBarWait.setVisibility(View.GONE);
}
public void onAnimationEnd(Animation animation) {
// TODO Auto-generated method stub
}
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
public void onAnimationStart(Animation animation) {
linearLayoutMediaController.setVisibility(View.GONE);
}
}
This is the working uri http://www.pocketjourney.com/downloads/pj/video/famous.3gp
This one throws illegalstateexception at mp.prepare() http://www.fieldandrurallife.tv/videos/Benltey%20Mulsanne.mp4
In order to stream video on android devices, you can use VideoView class.
The VideoView class can load images from various sources, takes care of computing its measurement from the video so that it can be used in any layout manager, and provides various display options such as scaling and tinting.
i've tried the video that gave you an error and it worked well.
You will find below the code that I've used to test your link for streaming the video:
VideoView videoview;
videoview = (VideoView) findViewById(R.id.VideoView);
try {
MediaController mediacontroller = new MediaController(VideoViewerActivity.this);
mediacontroller.setAnchorView(videoview);
Uri video = Uri.parse("http://www.fieldandrurallife.tv/videos/Benltey%20Mulsanne.mp4");
videoview.setMediaController(mediacontroller);
videoview.setVideoURI(video);
} catch (Exception e) {
e.printStackTrace();
}
videoview.requestFocus();
videoview.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
videoview.setZOrderOnTop(true);
videoview.start();
}
});
And don't forget to put the videoView in your .xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<VideoView
android:id="#+id/VideoView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
/>
</RelativeLayout>
If you have any question related to my answer, do not hesitate to contact me.
Good luck
As you are getting illegal state exception for player.prepare(), you can try restarting MediaPlayer object in respective catch block like in below code snippet. (Also its better to call start() only after mediaPlayer is prepared):
try{
player.prepare();
}catch (IllegalStateException e) {
player = new MediaPlayer();
player.setDataSource(extras.getString("video_path"));
Log.i(TAG, extras.getString("video_path"));
player.prepare();
player.setOnPreparedListener(new OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mp){
mp.start();
}
});
}

getDuration is throwing Attepmt to call on Invalid media player When calling media player second time?

below is the code that I am using . I am using a vimeo video url it is working fine when I first load the activity but gets problem when calling the activity second time it show message Attempt to call getDuration on invalid media player.
public class VideoActivity extends Activity {
public LinearLayout main_Lay;
private TextView textViewPlayed;
private TextView textViewLength;
private SeekBar seekBarProgress;
private SurfaceView surfaceViewFrame;
private ImageView imageViewPauseIndicator;
private MediaPlayer player;
private SurfaceHolder holder;
private ProgressBar progressBarWait;
private Timer updateTimer;
// private Bundle extras;
private Animation hideMediaController;
private LinearLayout linearLayoutMediaController;
private static final String TAG = "androidEx2 = VideoSample";
public boolean isFullScreen = false;
private Context m_context;
public GestureDetector ggg;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.video_layout);
this.m_context = this;
main_Lay = (LinearLayout) findViewById(R.id.main_lay);
main_Lay.startAnimation(AnimationUtils.loadAnimation(this,
R.anim.slide_out_up));
surfaceViewFrame = (SurfaceView) findViewById(R.id.surfaceViewFrame);
final Button button = (Button) findViewById(R.id.full);
ggg = new GestureDetector(new OnGestureListener() {
public boolean onSingleTapUp(MotionEvent arg0) {
// TODO Auto-generated method stub
try {
if (player != null) {
if (player.isPlaying())
player.stop();
player.reset();
player.release();
if (updateTimer != null) {
updateTimer.cancel();
}
finish();
}
} catch (Exception ex) {
ex.printStackTrace();
player.reset();
player.release();
if (updateTimer != null) {
updateTimer.cancel();
}
finish();
}
return true;
}
public void onShowPress(MotionEvent arg0) {
// TODO Auto-generated method stub
}
public boolean onScroll(MotionEvent arg0, MotionEvent arg1,
float arg2, float arg3) {
// TODO Auto-generated method stub
return false;
}
public void onLongPress(MotionEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean onFling(MotionEvent arg0, MotionEvent arg1,
float arg2, float arg3) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onDown(MotionEvent arg0) {
// TODO Auto-generated method stub
return false;
}
});
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (player != null) {
if (!isFullScreen) {
isFullScreen = true;
button.setBackgroundResource(R.drawable.fullscreen_exit_alt);
// Get the width of the screen
int screenWidth = ((Activity) m_context)
.getWindowManager().getDefaultDisplay()
.getWidth();
int screenHeight = ((Activity) m_context)
.getWindowManager().getDefaultDisplay()
.getHeight();
WidthResizeAnimation zoom_out = new WidthResizeAnimation(
main_Lay, screenWidth, screenHeight, false);
zoom_out.setDuration(600);
zoom_out.setFillAfter(true);
WidthResizeAnimation zoom_outt = new WidthResizeAnimation(
surfaceViewFrame, screenWidth, screenHeight,
false);
zoom_outt.setDuration(600);
zoom_outt.setFillAfter(true);
surfaceViewFrame.startAnimation(zoom_outt);
main_Lay.startAnimation(zoom_out);
} else {
isFullScreen = false;
button.setBackgroundResource(R.drawable.fullscreen_alt);
int videoWidth = player.getVideoWidth();
int videoHeight = player.getVideoHeight();
float videoProportion = (float) videoWidth
/ (float) videoHeight;
Log.i(TAG, "VIDEO SIZES: W: " + videoWidth + " H: "
+ videoHeight + " PROP: " + videoProportion);
// Get the width of the screen
int screenWidth = ((Activity) m_context)
.getWindowManager().getDefaultDisplay()
.getWidth();
int screenHeight = ((Activity) m_context)
.getWindowManager().getDefaultDisplay()
.getHeight();
float screenProportion = (float) screenWidth
/ (float) screenHeight;
Log.i(TAG, "VIDEO SIZES: W: " + screenWidth + " H: "
+ screenHeight + " PROP: " + screenProportion);
// Get the SurfaceView layout
// parameters
android.view.ViewGroup.LayoutParams lp = surfaceViewFrame
.getLayoutParams();
android.view.ViewGroup.LayoutParams mainLayoutParam = main_Lay
.getLayoutParams();
if (videoProportion > screenProportion) {
lp.width = screenWidth;
lp.height = (int) ((float) screenWidth / videoProportion);
lp.width = (lp.width / 100) * 80;
lp.height = (lp.height / 100) * 80;
} else {
lp.width = (int) (videoProportion * (float) screenHeight);
lp.height = screenHeight;
lp.width = (lp.width / 100) * 70;
lp.height = (lp.height / 100) * 70;
}
WidthResizeAnimation zoom_in = new WidthResizeAnimation(
main_Lay, lp.width, lp.height, false);
zoom_in.setDuration(600);
zoom_in.setFillAfter(true);
// zoom_in.start();
WidthResizeAnimation zoom_inn = new WidthResizeAnimation(
surfaceViewFrame, lp.width, lp.height, false);
zoom_inn.setDuration(600);
zoom_inn.setFillAfter(true);
// zoom_in.start();
surfaceViewFrame.startAnimation(zoom_inn);
main_Lay.startAnimation(zoom_in);
}
}
}
});
final Button pause = (Button) findViewById(R.id.pause);
pause.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (player != null) {
if (player.isPlaying()) {
player.pause();
pause.setBackgroundResource(R.drawable.play);
imageViewPauseIndicator.setVisibility(View.GONE);
} else {
pause.setBackgroundResource(R.drawable.pause);
player.start();
imageViewPauseIndicator.setVisibility(View.GONE);
}
}
}
});
linearLayoutMediaController = (LinearLayout) findViewById(R.id.linearLayoutMediaController);
linearLayoutMediaController.setVisibility(View.GONE);
hideMediaController = AnimationUtils.loadAnimation(m_context,
R.anim.disapearing);
hideMediaController.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation arg0) {
// TODO Auto-generated
// method stub
linearLayoutMediaController.setVisibility(View.GONE);
}
#Override
public void onAnimationRepeat(Animation arg0) {
// TODO Auto-generated
// method stub
}
#Override
public void onAnimationEnd(Animation arg0) {
// TODO Auto-generated
// method stub
}
});
imageViewPauseIndicator = (ImageView) findViewById(R.id.imageViewPauseIndicator);
imageViewPauseIndicator.setVisibility(View.GONE);
if (player != null) {
if (!player.isPlaying()) {
imageViewPauseIndicator.setVisibility(View.GONE);
}
}
textViewPlayed = (TextView) findViewById(R.id.textViewPlayed);
textViewLength = (TextView) findViewById(R.id.textViewLength);
surfaceViewFrame.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated
// method stub
if (arg0.getId() == R.id.surfaceViewFrame) {
if (linearLayoutMediaController.getVisibility() == View.GONE) {
linearLayoutMediaController.setVisibility(View.VISIBLE);
hideMediaController();
}
}
}
});
surfaceViewFrame.setClickable(false);
seekBarProgress = (SeekBar) findViewById(R.id.seekBarProgress);
seekBarProgress
.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated
// method stub
if (player.isPlaying()) {
progressBarWait.setVisibility(View.VISIBLE);
player.seekTo(arg0.getProgress() * 1000);
Log.i(TAG,
"========== SeekTo : " + arg0.getProgress());
}
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated
// method stub
}
#Override
public void onProgressChanged(SeekBar seekBar,
int progress, boolean fromUser) {
Log.i(TAG, "========== onProgressChanged : " + progress
+ " from user: " + fromUser);
if (!fromUser) {
textViewPlayed
.setText(durationInSecondsToString(progress));
}
}
});
seekBarProgress.setProgress(0);
progressBarWait = (ProgressBar) findViewById(R.id.progressBarWait);
holder = surfaceViewFrame.getHolder();
holder.addCallback(new Callback() {
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
player.setDisplay(holder);
playVideo();
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
player = new MediaPlayer();
player.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer arg0) {
// TODO Auto-generated method stub
Log.i(TAG, "========== onPrepared ===========");
try {
int duration = player.getDuration() / 1000; // duration
// in
// seconds
seekBarProgress.setMax(duration);
textViewLength.setText(durationInSecondsToString(duration));
progressBarWait.setVisibility(View.GONE);
// Get the dimensions of the video
int videoWidth = player.getVideoWidth();
int videoHeight = player.getVideoHeight();
float videoProportion = (float) videoWidth
/ (float) videoHeight;
Log.i(TAG, "VIDEO SIZES: W: " + videoWidth + " H: "
+ videoHeight + " PROP: " + videoProportion);
player.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
// Get the width of the screen
int screenWidth = ((Activity) m_context).getWindowManager()
.getDefaultDisplay().getWidth();
int screenHeight = ((Activity) m_context)
.getWindowManager().getDefaultDisplay().getHeight();
float screenProportion = (float) screenWidth
/ (float) screenHeight;
Log.i(TAG, "VIDEO SIZES: W: " + screenWidth + " H: "
+ screenHeight + " PROP: " + screenProportion);
// Get the SurfaceView layout
// parameters
android.view.ViewGroup.LayoutParams lp = surfaceViewFrame
.getLayoutParams();
android.view.ViewGroup.LayoutParams mainLayoutParam = main_Lay
.getLayoutParams();
if (videoProportion > screenProportion) {
lp.width = screenWidth;
lp.height = (int) ((float) screenWidth / videoProportion);
lp.width = (lp.width / 100) * 80;
lp.height = (lp.height / 100) * 80;
} else {
lp.width = (int) (videoProportion * (float) screenHeight);
lp.height = screenHeight;
lp.width = (lp.width / 100) * 90;
lp.height = (lp.height / 100) * 90;
}
// Commit the layout parameters
surfaceViewFrame.setLayoutParams(lp);
RelativeLayout.LayoutParams rr = new RelativeLayout.LayoutParams(
lp.width, lp.height);
rr.addRule(RelativeLayout.CENTER_IN_PARENT);
main_Lay.setLayoutParams(rr);
// Start video
if (!player.isPlaying()) {
player.start();
updateMediaProgress();
linearLayoutMediaController.setVisibility(View.VISIBLE);
hideMediaController();
}
surfaceViewFrame.setClickable(true);
} catch (Exception ex) {
player.release();
finish();
ex.printStackTrace();
}
;
}
});
player.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
if (arg0.isPlaying()) {
arg0.stop();
}
arg0.release();
finish();
Log.e("Lrapp", "Error code" + arg1);
return true;
}
});
player.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
arg0.stop();
arg0.release();
if (updateTimer != null) {
updateTimer.cancel();
}
finish();
}
});
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
#Override
public void onBufferingUpdate(MediaPlayer arg0, int arg1) {
// TODO Auto-generated method stub
int progress = (int) ((float) arg0.getDuration() * ((float) arg1 / (float) 100));
seekBarProgress.setSecondaryProgress(progress / 1000);
}
});
player.setOnSeekCompleteListener(new OnSeekCompleteListener() {
#Override
public void onSeekComplete(MediaPlayer arg0) {
// TODO Auto-generated method stub
progressBarWait.setVisibility(View.GONE);
}
});
player.setScreenOnWhilePlaying(true);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
return ggg.onTouchEvent(event);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
try {
if (player != null) {
if (player.isPlaying())
player.stop();
player.release();
if (updateTimer != null) {
updateTimer.cancel();
}
finish();
}
} catch (Exception ex) {
ex.printStackTrace();
player.release();
if (updateTimer != null) {
updateTimer.cancel();
}
finish();
}
}
private void playVideo() {
new Thread(new Runnable() {
public void run() {
try {
player.setDataSource("video url");
player.prepareAsync();
} catch (IllegalArgumentException e) {
showToast("Error while playing video. Please, check your network connection.");
Log.i(TAG,
"========== IllegalArgumentException ===========");
e.printStackTrace();
if (player.isPlaying())
player.stop();
player.release();
player = null;
if (updateTimer != null) {
updateTimer.cancel();
}
finish();
} catch (IllegalStateException e) {
showToast("Error while playing video. Please, check your network connection.");
Log.i(TAG, "========== IllegalStateException ===========");
e.printStackTrace();
if (player.isPlaying())
player.stop();
player.release();
player = null;
if (updateTimer != null) {
updateTimer.cancel();
}
finish();
} catch (IOException e) {
showToast("Error while playing video. Please, check your network connection.");
Log.i(TAG, "========== IOException ===========");
e.printStackTrace();
if (player.isPlaying())
player.stop();
player.release();
player = null;
if (updateTimer != null) {
updateTimer.cancel();
}
finish();
}
}
}).start();
}
private void showToast(final String string) {
((Activity) m_context).runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(m_context, string, Toast.LENGTH_LONG).show();
;
}
});
}
private void hideMediaController() {
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(5000);
((Activity) m_context).runOnUiThread(new Runnable() {
public void run() {
linearLayoutMediaController
.startAnimation(hideMediaController);
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
private void updateMediaProgress() {
updateTimer = new Timer("progress Updater");
updateTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
((Activity) m_context).runOnUiThread(new Runnable() {
public void run() {
try {
seekBarProgress.setProgress(player
.getCurrentPosition() / 1000);
} catch (Exception ex) {
ex.printStackTrace();
player.release();
}
}
});
}
}, 0, 1000);
}
public static String durationInSecondsToString(int sec) {
int hours = sec / 3600;
int minutes = (sec / 60) - (hours * 60);
int seconds = sec - (hours * 3600) - (minutes * 60);
String formatted = String.format("%d:%02d:%02d", hours, minutes,
seconds);
return formatted;
}
}
After you open the activity the second time, the surface callback is called -> playVideo() -> player doesn't init well.
The solution may be:
Insert this into the playVideo() method:
if (player != null)
{
player.reset();
} else
{
player = new MediaPlayer();
}
//init

Categories

Resources