In my application I can successfully call a method flash_toggle_times(progress); when toggle Button is pressed. But when I am calling same method in public void onStopTrackingTouch(SeekBar seekBar) It is not being called. Do not know why?
Here is complete code
public class MainActivity extends ActionBarActivity implements OnSeekBarChangeListener {
SeekBar seekBar;
TextView textView;
ToggleButton toggleButton;
boolean positionON = false;
private Camera mCamera;
private Camera.Parameters mParams;
boolean lightON = false;
boolean changeIntensity = false;
int progress = 0;
private String TAG = "SeekBar LOG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeVariables();
textView.setText("Covered : " + seekBar.getProgress() + "/" + seekBar.getMax());
seekBar.setOnSeekBarChangeListener(this);
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// positionON = (isChecked) ? true : false;
positionON = isChecked;
if (isChecked) {
//Here flash_toggle_times(progress) is being called successfully
// flash_toggle_times(progress);
} else {
}
}
});
}
private void initializeVariables() {
seekBar = (SeekBar) findViewById(R.id.m_seekbar);
textView = (TextView) findViewById(R.id.m_tv);
toggleButton = (ToggleButton) findViewById(R.id.m_toggle_button);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
textView.setText("Covered On Stop: " + progress + "/" + seekBar.getMax() + "\n" + changeIntensity);
// If button is On, Turn on Light
Toast.makeText(getApplicationContext(), "StopTrackingTouch: " + progress, Toast.LENGTH_SHORT).show();
if(progress > 0){
//Here when this method is not being called.
flash_toggle_times(progress);
Toast.makeText(getApplicationContext(), "Calling in if", Toast.LENGTH_SHORT).show();
}
Log.d(TAG, "StopTrackingTouch");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
Log.d(TAG , "StartTrackingTouch()");
}
#Override
public void onProgressChanged(SeekBar seekBar, int progressValue, boolean fromUser) {
progress = progressValue;
// Toast.makeText(getApplicationContext(), "ProgressChanged : " + progress, Toast.LENGTH_SHORT).show();
Log.d(TAG,"ProgressChanged");
}
public void flash_toggle_times(final int delay) {
mCamera = Camera.open();
final Parameters p = mCamera.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
Thread t = new Thread() {
public void run() {
try {
// Switch on the cam for app's life
if (mCamera == null) {
// Turn on Cam
mCamera = Camera.open();
try {
mCamera.setPreviewDisplay(null);
} catch (IOException e) {
e.printStackTrace();
}
mCamera.startPreview();
}
final int[] counter = {delay};
while(positionON )
{
if(counter[0] > 0){
toggleFlashLight();
sleep(counter[0]*100);
}
}
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
} catch (Exception e){
e.printStackTrace();
}
}
};
t.start();
}
public void turnOn(){
if (mCamera != null) {
// Turn on LED
mParams = mCamera.getParameters();
mParams.setFlashMode(Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(mParams);
}
lightON = true;
}
public void turnOff(){
// Turn off flashlight
if (mCamera != null) {
mParams = mCamera.getParameters();
if (mParams.getFlashMode().equals(Parameters.FLASH_MODE_TORCH)) {
mParams.setFlashMode(Parameters.FLASH_MODE_OFF);
mCamera.setParameters(mParams);
}
}
lightON = false;
}
private void toggleFlashLight() {
if (!lightON) {
turnOn();
} else {
turnOff();
}
}
}
Related
In my android application while I'm playing a music, the seekbar bar is staying still. The timer of the music is running fine & the music plays from the touched position of the seek bar.
But the problem is that the seekbar is still and not moving while touching on the seekbar .
Any one help me to find a solution for this .. Thank You ..
My Activity code is ....
public class Device_AudioPlayerActivity extends Activity implements Runnable,
OnClickListener, SeekBar.OnSeekBarChangeListener {
Button btnBack;
static Button btnPause;
private Handler mHandler;
Button btnNext;
static Button btnPlay;
static TextView textNowPlaying;
static TextView textAlbumArtist;
static TextView textComposer;
static LinearLayout linearLayoutPlayer;
SeekBar progressBar;
static Context context;
TextView textBufferDuration, textDuration;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//getActionBar().hide();
setContentView(R.layout.device_audio_player);
context = this;
progressBar=(SeekBar)findViewById(R.id.progressBar);
init();
progressBar.setMax(Device_SongService.mp.getDuration());
new Thread().start();
progressBar.setOnSeekBarChangeListener(this);
progressBar.setEnabled(true);
//-=--------------------------------------
}
private void init() {
getViews();
setListeners();
progressBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.white), Mode.SRC_IN);
Device_PlayerConstants.PROGRESSBAR_HANDLER = new Handler() {
#Override
public void handleMessage(Message msg) {
Integer i[] = (Integer[]) msg.obj;
textBufferDuration.setText(Device_UtilFunctions.getDuration(i[0]));
textDuration.setText(Device_UtilFunctions.getDuration(i[1]));
progressBar.setProgress(i[2]);
}
};
}
private void setListeners() {
btnBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Device_Controls.previousControl(getApplicationContext());
}
});
btnPause.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Device_Controls.pauseControl(getApplicationContext());
}
});
btnPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Device_Controls.playControl(getApplicationContext());
}
});
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Device_Controls.nextControl(getApplicationContext());
}
});
}
public static void changeUI() {
updateUI();
changeButton();
}
private void getViews() {
btnBack = (Button) findViewById(R.id.btnBack);
btnPause = (Button) findViewById(R.id.btnPause);
btnNext = (Button) findViewById(R.id.btnNext);
btnPlay = (Button) findViewById(R.id.btnPlay);
textNowPlaying = (TextView) findViewById(R.id.textNowPlaying);
linearLayoutPlayer = (LinearLayout) findViewById(R.id.linearLayoutPlayer);
textAlbumArtist = (TextView) findViewById(R.id.textAlbumArtist);
textComposer = (TextView) findViewById(R.id.textComposer);
progressBar = (SeekBar) findViewById(R.id.progressBar);
textBufferDuration = (TextView) findViewById(R.id.textBufferDuration);
textDuration = (TextView) findViewById(R.id.textDuration);
textNowPlaying.setSelected(true);
textAlbumArtist.setSelected(true);
}
#Override
protected void onResume() {
super.onResume();
boolean isServiceRunning = Device_UtilFunctions.isServiceRunning(Device_SongService.class.getName(), getApplicationContext());
if (isServiceRunning) {
updateUI();
}
changeButton();
}
public static void changeButton() {
if (Device_PlayerConstants.SONG_PAUSED) {
btnPause.setVisibility(View.GONE);
btnPlay.setVisibility(View.VISIBLE);
} else {
btnPause.setVisibility(View.VISIBLE);
btnPlay.setVisibility(View.GONE);
}
}
private static void updateUI() {
try {
String songName = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getTitle();
String artist = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getArtist();
String album = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getAlbum();
String composer = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getComposer();
textNowPlaying.setText(songName);
textAlbumArtist.setText(artist + " - " + album);
if (composer != null && composer.length() > 0) {
textComposer.setVisibility(View.VISIBLE);
textComposer.setText(composer);
} else {
textComposer.setVisibility(View.GONE);
}
} catch (Exception e) {
e.printStackTrace();
}
try {
long albumId = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getAlbumId();
Bitmap albumArt = Device_UtilFunctions.getAlbumart(context, albumId);
if (albumArt != null) {
linearLayoutPlayer.setBackgroundDrawable(new BitmapDrawable(albumArt));
} else {
linearLayoutPlayer.setBackgroundDrawable(new BitmapDrawable(Device_UtilFunctions.getDefaultAlbumArt(context)));
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onClick(View view) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
try {
if (Device_SongService.mp.isPlaying() || Device_SongService.mp != null) {
if (b)
Device_SongService.mp.seekTo(i);
} else if (Device_SongService.mp == null) {
Toast.makeText(getApplicationContext(), "Media is not running",
Toast.LENGTH_SHORT).show();
seekBar.setProgress(0);
}
} catch (Exception e) {
Log.e("seek bar", "" + e);
seekBar.setEnabled(false);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void run() {
int currentPosition = Device_SongService.mp.getCurrentPosition();
int total = Device_SongService.mp.getDuration();
while (Device_SongService.mp != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = Device_SongService.mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
progressBar.setProgress(currentPosition);
}
}
}
Have a look at this link.
Try using a thread in progress changed.
you have to use thread on onprogresschnaged....
#Override
public void onProgressChanged(SeekBar arg0, final int progress, boolean arg2) {
Thread thread = new Thread() {
#Override
public void run() {
try {
while(true) {
//here write your code
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
}
I am trying to make the background flash when music plays in my app but it isn't working as expected.
The music plays when a button is pressed. The background should be yellow when the music is off but flash quickly between yellow and purple when the music is playing.
At the moment it is yellow when off, changes to some dull grey when the music is playing and does not return to yellow when the music is off.
public class InstaRave extends Activity {
private static final String TAG = "InstaRave";
private static int isPlaying = 0; // 0 is not playing 1 is playing
private MediaPlayer mp;
public static int mPurple = color.mPurple;
public static int mYellow = color.mYellow;
public static int currentBackground = mYellow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insta_rave);
final Button play_button = (Button)this.findViewById(R.id.raveButton);
final RelativeLayout mRelativeLayout = (RelativeLayout) this.findViewById(R.id.topLevelLayout);
mp = MediaPlayer.create(this, R.raw.rave_mk);
Log.v(TAG, "Initializing sounds...");
play_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch (isPlaying){
case 0:
changeBackground(mRelativeLayout);
startMusic();
isPlaying = 1;
rave();
break;
case 1:
changeBackground(mRelativeLayout);
stopMusic();
isPlaying = 0;
rave();
break;
default:
Log.e(TAG, "Ooops something went wrong");
}
}
private void stopMusic(){
Log.v(TAG, "Stopping sound...");
mp.stop();
//isPlaying = 0;
mp.prepareAsync();
}
private void startMusic(){
Log.v(TAG, "Playing sound...");
mp.start();
//isPlaying = 1;
}
private void rave(){
Log.v(TAG, String.valueOf(isPlaying));
if (isPlaying == 1){
Log.v(TAG, "Raving....");
new Rave().execute();
} else {
Log.v(TAG, "End the rave the po po is here...");
}
}
});
}
protected void onPause(){
super.onPause();
mp.release();
mp = null;
}
private void changeBackground(RelativeLayout mRelativeLayout){
if (currentBackground == mYellow){
currentBackground = mPurple;
mRelativeLayout.setBackgroundColor(currentBackground);
Log.v(TAG, "Background is: " + String.valueOf(currentBackground));
}
currentBackground = mYellow;
mRelativeLayout.setBackgroundColor(currentBackground);
Log.v(TAG, "Background is: " + String.valueOf(currentBackground));
}
private class Rave extends AsyncTask<Void, Void, Void> {
final RelativeLayout mRelativeLayout = (RelativeLayout) findViewById(R.id.topLevelLayout);
#Override
protected Void doInBackground(Void... params) {
while (isPlaying ==1){
try {
Thread.sleep(75);
publishProgress();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
protected void onProgressUpdate(Void... progress){
changeBackground(mRelativeLayout);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.insta_rave, menu);
return true;
}
}
Change your changeBackground() method to this:
private void changeBackground(RelativeLayout mRelativeLayout){
if (currentBackground == mYellow){
currentBackground = mPurple;
mRelativeLayout.setBackgroundColor(currentBackground);
Log.v(TAG, "Background is: " + String.valueOf(currentBackground));
}
else
{
currentBackground = mYellow;
mRelativeLayout.setBackgroundColor(currentBackground);
Log.v(TAG, "Background is: " + String.valueOf(currentBackground));
}
}
I created a Karaoke application. But I can't stop the MediaPlayer with out an error. When I press Back Button to go to home, I get "sorry ,Application has stopped working" The same thing happens if I try to start another activity.
This my code.
public class Main extends Activity implements MediaPlayerControl, OnClickListener {
private MediaController mMediaController;
private MediaPlayer mMediaPlayer;
public TextView subtitles;
Handler mHandler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
subtitles = (TextView) findViewById(R.id.subs1);
Button btnvol = (Button) findViewById(R.id.volc);
btnvol.setOnClickListener(this);
mMediaPlayer = new MediaPlayer();
mMediaController = new MediaController(this);
mMediaController.setMediaPlayer(Main.this);
mMediaController.setAnchorView(findViewById(R.id.audioView));
try {
mMediaPlayer
.setDataSource(
this,
Uri.parse("android.resource://com.app.audioplayer/raw/buchatri"));
mMediaPlayer.prepare();
} catch (IllegalStateException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
final long currentPos = mMediaPlayer.getCurrentPosition();
if (currentPos < 5130) {
subtitles.setText("Stupid");
} else if (currentPos > 5130 && currentPos < 10572) {
subtitles.setText("Sorry");
} else if (currentPos > 10572 && currentPos < 10597) {
subtitles.setText("555+");
} else if (currentPos > 15312 && currentPos < 18478) {
subtitles.setText("OMG");
} else if (currentPos > 18478 && currentPos < 24191) {
subtitles.setText("AFK");
} else if (currentPos > 24191 && currentPos < 28137) {
subtitles.setText("Help me !");
} else if (currentPos > 28137 && currentPos < 29500) {
subtitles.setText("Oh no !");
}
mHandler.sendEmptyMessageDelayed(0, 1);
}
};
mHandler.sendEmptyMessage(0);
mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mHandler.post(new Runnable() {
public void run() {
mMediaController.show(0);
mMediaPlayer.start();
}
});
}
});
}
protected void onDestroy() {
super.onDestroy();
mMediaPlayer.stop();
mMediaPlayer.release();
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
public int getBufferPercentage() {
int percentage = (mMediaPlayer.getCurrentPosition() * 100)
/ mMediaPlayer.getDuration();
return percentage;
}
public int getCurrentPosition() {
return mMediaPlayer.getCurrentPosition();
}
public int getDuration() {
return mMediaPlayer.getDuration();
}
public boolean isPlaying() {
return mMediaPlayer.isPlaying();
}
#Override
public void pause() {
// TODO Auto-generated method stub
super.onPause();
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
public void seekTo(int pos) {
mMediaPlayer.seekTo(pos);
}
public void start() {
mMediaPlayer.start();
}
public boolean onTouchEvent(MotionEvent event) {
mMediaController.show(0);
return false;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
I think I have an error with "if else". How can I fix this ?
Try first mMediaPlayer.stop() and then release it by mMediaPlayer.release()
you can try this,
after release you should set mediaplayer null
private void releaseMediaPlayer() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
I am developing an application that, among other things, plays some video files (streaming). I would like to prepare the MediaPlayer in one activity but play the video once it is ready in another activity, so that the user can navigate through the content of the first activity to kill some time. Is this possible?
There is an static MediaPlayer defined in the Application class, like this:
public class EGDF_App extends Application {
private static MediaPlayer mediaPlayer = null;
public static MediaPlayer getMediaPlayer() {
if(mediaPlayer == null)
return new MediaPlayer();
else
return mediaPlayer;
}
}
I have a button with a text (Load video). This text is changed when the video is ready, and when the user clicks on it, it triggers the following activity.
The problem is that I get the following error in LogCat:
09-06 20:43:34.606: D/ChapterPlayer(31999): surfaceCreated called
09-06 20:43:34.684: V/ChapterPlayer(31999): startVideoPlayback
09-06 20:43:34.684: E/MediaPlayer(31999): start called in state 1
09-06 20:43:34.684: E/MediaPlayer(31999): error (-38, 0)
09-06 20:43:34.684: D/ChapterPlayer(31999): surfaceChanged called
09-06 20:43:34.700: E/MediaPlayer(31999): Attempt to call getDuration without a valid mediaplayer
09-06 20:43:34.715: E/MediaPlayer(31999): Error (-38,0)
09-06 20:43:34.715: D/ChapterPlayer(31999): onCompletion called
09-06 20:43:34.751: E/MediaPlayer(31999): Attempt to call getDuration without a valid mediaplayer
This is the code contained in the first Activity:
public void watchChapter(View view){
Log.i("Button", "Watch chapter button PRESSED");
Button b = (Button) view;
String loadChapter = getString(R.string.load_chapter_button_text);
String watchChapter = getString(R.string.watch_chapter_button_text);
if(((String) b.getText()).equals(loadChapter)){
prepareVideo(view);
}else if(((String) b.getText()).equals(watchChapter)){
Intent intent = new Intent(this,ChapterAsyncMediaPlayerActivity.class);
intent.putExtra(Constants.chapterVideoResParse, getIntent().getExtras().getString(Constants.chapterVideoResParse));
intent.putExtra("duration", String.valueOf(duration));
startActivity(intent);
}
}
private void prepareVideo(View view){
MediaPlayer mMediaPlayer;
String path;
final Button button = (Button) view;
String resource = extras.getString(Constants.chapterVideoResParse);
path = SecurityHandler.obtainURL(resource, this.getResources().openRawResource(R.raw.output), 10);
try {
// Gets the media player and set the listeners
mMediaPlayer = EGDF_App.getMediaPlayer();
mMediaPlayer.setDataSource(path);
mMediaPlayer.prepareAsync();
mMediaPlayer.setOnPreparedListener(new OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mp) {
button.setText(getString(R.string.watch_chapter_button_text));
Log.i("MediaPlayer", "MediaPlayer ready");
duration = mp.getDuration();
Log.i("Video duration", String.valueOf(mp.getDuration()));
}
});
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And this is the code in the second Activity:
public class ChapterAsyncMediaPlayerActivity extends Activity implements
OnBufferingUpdateListener, OnCompletionListener,
OnPreparedListener, OnVideoSizeChangedListener, SurfaceHolder.Callback, MediaPlayerControl {
private static final String TAG = "ChapterPlayer";
private int mVideoWidth;
private int mVideoHeight;
private MediaPlayer mMediaPlayer;
private MediaController mController;
private SurfaceView mPreview;
private SurfaceHolder holder;
// private String path;
// private boolean mIsVideoSizeKnown = false;
private boolean mIsVideoReadyToBePlayed = false;
private Handler handler = new Handler();
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chapter_media_player);
mPreview = (SurfaceView) findViewById(R.id.mediaPlayerSurface);
holder = mPreview.getHolder();
holder.addCallback(this);
holder.setKeepScreenOn(true);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
mController.show();
return false;
}
private void playVideo() {
doCleanUp();
try {
// Create a new media player and set the listeners
mMediaPlayer = EGDF_App.getMediaPlayer();
// mMediaPlayer.setDataSource(path);
mMediaPlayer.setDisplay(holder);
// mMediaPlayer.prepareAsync();
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setScreenOnWhilePlaying(true);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mController = new MediaController(this);
} catch (Exception e) {
Log.e(TAG, "error: " + e.getMessage(), e);
}
}
public void onPrepared(MediaPlayer mediaplayer) {
Log.d(TAG, "onPrepared called");
mIsVideoReadyToBePlayed = true;
mController.setMediaPlayer(this);
mController.setAnchorView(findViewById(R.id.mediaPlayerSurface));
handler.post(new Runnable(){
#Override
public void run() {
mController.setEnabled(true);
mController.show();
}
});
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();
mIsVideoReadyToBePlayed = true;
mController.setMediaPlayer(this);
mController.setAnchorView(findViewById(R.id.mediaPlayerSurface));
handler.post(new Runnable(){
#Override
public void run() {
mController.setEnabled(true);
mController.show();
}
});
if (mIsVideoReadyToBePlayed) {
startVideoPlayback();
}
}
#Override
protected void onPause() {
super.onPause();
mMediaPlayer.pause();
}
#Override
protected void onRestart() {
super.onPause();
mMediaPlayer.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
releaseMediaPlayer();
doCleanUp();
}
private void releaseMediaPlayer() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
private void doCleanUp() {
mVideoWidth = 0;
mVideoHeight = 0;
mIsVideoReadyToBePlayed = false;
}
private void startVideoPlayback() {
Log.v(TAG, "startVideoPlayback");
holder.setFixedSize(mVideoWidth, mVideoHeight);
mMediaPlayer.start();
mMediaPlayer.setScreenOnWhilePlaying(true);
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public int getCurrentPosition() {
if(mMediaPlayer != null)
return mMediaPlayer.getCurrentPosition();
else
return 0;
}
#Override
public int getDuration() {
if(mMediaPlayer != null)
return mMediaPlayer.getDuration();
else
return 0;
}
#Override
public boolean isPlaying() {
if(mMediaPlayer != null)
return mMediaPlayer.isPlaying();
else
return false;
}
#Override
public void pause() {
if(mMediaPlayer != null)
mMediaPlayer.pause();
}
#Override
public void seekTo(int pos) {
mMediaPlayer.seekTo(pos);
}
#Override
public void start() {
if(mMediaPlayer != null)
mMediaPlayer.start();
}
public void onBufferingUpdate(MediaPlayer arg0, int percent) {
Log.d(TAG, "onBufferingUpdate percent:" + percent);
}
public void onCompletion(MediaPlayer arg0) {
Log.d(TAG, "onCompletion called");
}
#Override
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;
}
mVideoWidth = width;
mVideoHeight = height;
if (mIsVideoReadyToBePlayed) {
startVideoPlayback();
}
}
}
I would appreciate some help or advice. Thanks!
I don't think you're saving the MediaPlayer in your application, you're just returning a new instance of it. Try changing it as so:
public static MediaPlayer getMediaPlayer() {
if(mediaPlayer == null) {
mediaPlayer = new MediaPlayer();
}
return mediaPlayer;
}
I am a Android newbie. I want to design my personal videoplayer to play streaming music, so I use MediaPlayer and SurfaceView. The project plays streaming video successfully, but it can't be setloop. I have google many articles and read Android Developer. I can't figure out why mediaPlayer.setLooping(true) don't work here. Thanks^^
mediaPlayer.reset();
mediaPlayer.setDataSource(videoUrl);
mediaPlayer.setLooping(true);
mediaPlayer.prepare();
The code includes two parts: 1.Test_Videoplayer.java 2.Player.java
1.Test_Videoplayer.java
public class Test_Videoplayer extends Activity {
private SurfaceView surfaceView;
private Button btnPause, btnPlayUrl, btnStop;
private SeekBar skbProgress;
private Player player;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
surfaceView = (SurfaceView) this.findViewById(R.id.surfaceView1);
btnPlayUrl = (Button) this.findViewById(R.id.btnPlayUrl);
btnPlayUrl.setOnClickListener(new ClickEvent());
btnPause = (Button) this.findViewById(R.id.btnPause);
btnPause.setOnClickListener(new ClickEvent());
btnStop = (Button) this.findViewById(R.id.btnStop);
btnStop.setOnClickListener(new ClickEvent());
skbProgress = (SeekBar) this.findViewById(R.id.skbProgress);
skbProgress.setOnSeekBarChangeListener(new SeekBarChangeEvent());
player = new Player(surfaceView, skbProgress);
}
class ClickEvent implements OnClickListener {
#Override
public void onClick(View arg0) {
if (arg0 == btnPause) {
player.pause();
} else if (arg0 == btnPlayUrl) {
String url = "http://sites.google.com/site/ronforwork/Home/android-2/littleMonster.3gp";
player.playUrl(url);
} else if (arg0 == btnStop) {
player.stop();
}
}
}
class SeekBarChangeEvent implements SeekBar.OnSeekBarChangeListener {
int progress;
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
this.progress = progress * player.mediaPlayer.getDuration()
/ seekBar.getMax();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
player.mediaPlayer.seekTo(progress);
}
}
}
2.Player.java <-- here is mediaPlayer.setLooping(true)
public class Player implements OnBufferingUpdateListener, OnCompletionListener,
MediaPlayer.OnPreparedListener, SurfaceHolder.Callback {
private int videoWidth;
private int videoHeight;
public MediaPlayer mediaPlayer;
private SurfaceHolder surfaceHolder;
private SeekBar skbProgress;
private Timer mTimer = new Timer();
public Player(SurfaceView surfaceView, SeekBar skbProgress) {
this.skbProgress = skbProgress;
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mTimer.schedule(mTimerTask, 0, 1000);
}
TimerTask mTimerTask = new TimerTask() {
#Override
public void run() {
if (mediaPlayer == null)
return;
if (mediaPlayer.isPlaying() && skbProgress.isPressed() == false) {
handleProgress.sendEmptyMessage(0);
}
}
};
Handler handleProgress = new Handler() {
public void handleMessage(Message msg) {
int position = mediaPlayer.getCurrentPosition();
int duration = mediaPlayer.getDuration();
if (duration > 0) {
long pos = skbProgress.getMax() * position / duration;
skbProgress.setProgress((int) pos);
}
};
};
public void play() {
mediaPlayer.start();
}
public void playUrl(String videoUrl) {
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(videoUrl);
mediaPlayer.setLooping(true);
mediaPlayer.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void pause() {
mediaPlayer.pause();
}
public void stop() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
Log.e("mediaPlayer", "surface changed");
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDisplay(surfaceHolder);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnPreparedListener(this);
} catch (Exception e) {
Log.e("mediaPlayer", "error", e);
}
Log.e("mediaPlayer", "surface created");
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
Log.e("mediaPlayer", "surface destroyed");
}
#Override
public void onPrepared(MediaPlayer arg0) {
videoWidth = mediaPlayer.getVideoWidth();
videoHeight = mediaPlayer.getVideoHeight();
if (videoHeight != 0 && videoWidth != 0) {
arg0.start();
}
Log.e("mediaPlayer", "onPrepared");
}
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
}
#Override
public void onBufferingUpdate(MediaPlayer arg0, int bufferingProgress) {
skbProgress.setSecondaryProgress(bufferingProgress);
int currentProgress = skbProgress.getMax()
* mediaPlayer.getCurrentPosition() / mediaPlayer.getDuration();
Log.e(currentProgress + "% play", bufferingProgress + "% buffer");
}
}