Using seekbar with music in android - android

I am actually creating an app with a button, a seekbar and an an image. The button is used to Play/Pause the music. the music played smooth before adding the seekbar. But, after writing the code for seekbar to progress with the position of music, the music seems to be a bit choppy.
Also, i want to reset the position of seekbar to start and change the text on button to "Play" after the music is finished playing.
Can any one tell me why the music is choppy after implementing seekbar?
Also, suggest me how to deal after the music is finished playing.
The coded i used is below:
public class MainActivity extends ActionBarActivity {
private MediaPlayer song;
private SeekBar seekbar;
private final Handler handler = new Handler();
private final Runnable updatePositionRunnable = new Runnable() {
public void run() {
updatePosition();
}
};
//private boolean isPlaying = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
seekbar = (SeekBar)findViewById(R.id.musicSeekBar);
song = MediaPlayer.create( MainActivity.this, R.raw.xyz);
seekbar.setMax(song.getDuration());
final Button playButton = (Button)findViewById(R.id.playButton);
playButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(song.isPlaying()){
playButton.setText("Play");
song.pause();
//isPlaying = false;
handler.removeCallbacks(updatePositionRunnable);
}
else{
playButton.setText("Pause");
song.start();
//isPlaying = true;
updatePosition();
}
}
});
song.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
playButton.setText("Play");
//seekbar.setProgress(0);
//mp.stop();
}
});
seekbar.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) {
song.seekTo(progress);
}
});
private void updatePosition(){
handler.removeCallbacks(updatePositionRunnable);
seekbar.setProgress(song.getCurrentPosition());
handler.postDelayed(updatePositionRunnable, 2000);
}
#Override
public void onBackPressed() {
super.onBackPressed();
song.stop();
song.release();
}

When you update the progress on the seekbar from your updatePosition method every 2 seconds, the onProgressChanged method in your listener will be called, which will set the position of the playback and cause a slight blip. You might expect onProgressChanged to be called only when the user interacts with the SeekBar but unfortunately that isn't the case.
I'm not aware of a clean solution to this. What you can do is set a boolean flag in your code immediately before calling seekbar.setProgress that indicates the next onProgressChanged callback was not caused by the user, so you can ignore it. You should use an AtomicBoolean for this purpose because the events may come from different threads.

this worked for me:
sBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
boolean userTouch;
#Override
public void onStopTrackingTouch(SeekBar arg0) {
userTouch = false;
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
userTouch = true;
}
#Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
if(mPlayer.isPlaying() && arg2)
mPlayer.seekTo(arg1);
}
});

Related

SeekBar is not updating music is playing but the seekBar stay idle

I am playing mp3 file from url, but SeekBar is not updating while playing song.
It showing a buffering but not moving automatically when song starts.
When i am trying to move forcefully then also it working fine.
Below code i am using to play and update SeekBar.
I wanted to create a seekBar that track the progress of a mediaplayer but it doesnt work out quite well, the music is playing but the seekbar stay idle. Is there something that I left out?
Please help me i am new in android.
public class XYZ extends Fragment implements MediaPlayer.OnBufferingUpdateListener,MediaPlayer.OnCompletionListener{
private SeekBar seekBar;
private MediaPlayer mediaPlayer;
private int mediaFileLength;
final Handler handler = new Handler();
private int realtimeLength;
Button b,b3,b4;
private double startTime = 0;
private double finalTime = 0;
public static int oneTimeOnly = 0;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_outside, container,
false);
rootView.setBackgroundResource(R.drawable.jotirling);
seekBar = rootView.findViewById(R.id.seekbar);
seekBar.setMax(99); // 100% (0~99)
seekBar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (mediaPlayer.isPlaying()) {
SeekBar seekBar = (SeekBar) v;
int playPosition = (mediaFileLength / 100) * seekBar.getProgress();
mediaPlayer.seekTo(playPosition);
}
return false;
}
});
b3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog mDialog = new ProgressDialog(getActivity());
#SuppressLint("StaticFieldLeak") AsyncTask<String, String, String> mp3Play = new AsyncTask<String, String, String>() {
#Override
protected void onPreExecute() {
mDialog.setMessage("Please wait It will take time according to your network speed...!");
mDialog.show();
mDialog.setCancelable(false);
}
#Override
protected String doInBackground(String... params) {
try {
mediaPlayer.setDataSource(params[0]);
mediaPlayer.prepare();
} catch (Exception ignored) {
}
return "";
}
#Override
protected void onPostExecute(String s) {
mediaFileLength = mediaPlayer.getDuration();
realtimeLength = mediaFileLength;
if (!mediaPlayer.isPlaying()) {
p=1;
mediaPlayer.start();
Toast.makeText(getActivity(), "Playing sound", Toast.LENGTH_SHORT).show();
finalTime = mediaPlayer.getDuration();
startTime = mediaPlayer.getCurrentPosition();
b3.setBackgroundResource(R.drawable.pp);
if (oneTimeOnly == 0) {
oneTimeOnly = 1;
}
} else {
p=0;
mediaPlayer.pause();
Toast.makeText(getActivity(), "Pausing "+
"sound",Toast.LENGTH_SHORT).show();
b3.setBackgroundResource(R.drawable.p);
}
updateSeekBar();
mDialog.dismiss();
}
};
mp3Play.execute("URL"); // direct link mp3 file
}
});
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
return rootView;
}
private void updateSeekBar() {
seekBar.setProgress((int) (((float) mediaPlayer.getCurrentPosition() / mediaFileLength) * 100));
if (mediaPlayer.isPlaying()) {
Runnable updater = new Runnable() {
#Override
public void run() {
updateSeekBar();
}
};
}
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
seekBar.setSecondaryProgress(percent);
}
}
You should consider using setOnSeekbarChangeListener()
Reference : setOnSeekBarChangeListener()
Simple example would be
seekBar.setOnSeekBarChangeListener(new 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){
//do your things, like updating time durations etc.
}
}
});
Also if u a want working example, look at this link for code (i have just used circularSeekbar instead of regular one) https://github.com/iamSahdeep/Bop/blob/master/app/src/main/java/com/sahdeepsingh/Bop/Activities/PlayerView.java#L324
More Examples : https://www.javatips.net/api/android.widget.seekbar.onseekbarchangelistener
You can create use Timer for this:
seekBar.setMax(mediaPlayer.getDuration());
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
seekBar.setProgress(mediaPlayer.getCurrentPosition());
}
},0,1000);
You are defining Runnable updater but not calling it.
if (mediaPlayer.isPlaying()) {
Runnable updater = new Runnable() {
#Override
public void run() {
updateSeekBar();
}
};
seekBar.post(updater)
}

Created simple media player but after clicking each button five or six time it stop playing

I have created a simple media player. After clicking each button five or six times, it stops playing sound. But the app is not crashing and not showing any error. The app is playing sound without any problem at the first time. Plus, in my function where I have created onClick method, can I apply the stop or pause function to stop the previous playing sound?
Here is the code:
public class MainActivity extends AppCompatActivity {
MediaPlayer mymediaplayer;
AudioManager myaudiomanager;
public void playone(View view)
{
mymediaplayer=MediaPlayer.create(this,R.raw.one);
mymediaplayer.start();
}
public void playtwo(View view)
{
mymediaplayer=MediaPlayer.create(this,R.raw.two);
mymediaplayer.start();
}
public void playthree(View view)
{
mymediaplayer=MediaPlayer.create(this,R.raw.three);
mymediaplayer.start();
}
public void playfour(View view)
{
mymediaplayer=MediaPlayer.create(this,R.raw.four);
mymediaplayer.start();
}
public void playfive(View view)
{
mymediaplayer=MediaPlayer.create(this,R.raw.five);
mymediaplayer.start();
}
public void playsix(View view)
{
mymediaplayer=MediaPlayer.create(this,R.raw.six);
mymediaplayer.start();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myaudiomanager=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
int max=myaudiomanager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int progress=myaudiomanager.getStreamVolume(AudioManager.STREAM_MUSIC);
SeekBar volume=(SeekBar)findViewById(R.id.seekBar);
volume.setMax(max);
volume.setProgress(progress);
volume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
myaudiomanager.setStreamVolume(AudioManager.STREAM_MUSIC,i,0);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
}
You should release media player before starting to play new item. I did change playone as example:
public void playone(View view)
{
releaseMediaPlayer(mymediaplayer);//release previous player if there are any
mymediaplayer=MediaPlayer.create(this,R.raw.one);
mymediaplayer.start();
}
void releaseMediaPlayer(MediaPlayer mPlayer){
if(mPlayer!=null)
{
mPlayer.release();
}
}

Why isn't the seekbar moving as youtube video is playing in android?

I've implemented a youtube player (fragment) in my android project. I'm tryin' to play the video in chromeless player style, while implementing player control on my own. Play and pause buttons are working fine, however seekbar isn't moving as the video is progressing. Though, I'm able to skip video through it (play video ahead), but the seekbar isn't moving on it's own. Where did I go wrong?
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
if (!b) {
YPlayer = youTubePlayer;
displayCurrentTime(); // It displays current progress of video in --:-- format. It's working fine...
YPlayer.loadVideo(id); // id -> YouTube video id
YPlayer.play();
YPlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);
YPlayer.setPlayerStateChangeListener(new YouTubePlayer.PlayerStateChangeListener() {
#Override
public void onLoading() {
}
#Override
public void onLoaded(String s) {
}
#Override
public void onAdStarted() {
}
#Override
public void onVideoStarted() {
seekBar.setMax(YPlayer.getDurationMillis()/1000);
}
#Override
public void onVideoEnded() {
}
#Override
public void onError(YouTubePlayer.ErrorReason errorReason) {
}
});
YPlayer.setPlaybackEventListener(new YouTubePlayer.PlaybackEventListener() {
#Override
public void onPlaying() {
handler.postDelayed(runnable, 100); //Handler's instance initialized as instance variable
displayCurrentTime();
}
#Override
public void onPaused() {
handler.removeCallbacks(runnable);
}
#Override
public void onStopped() {
}
#Override
public void onBuffering(boolean b) {
handler.postDelayed(runnable, 1000);
}
#Override
public void onSeekTo(int i) {
handler.removeCallbacks(runnable);
}
});
playerControl.setVisibility(View.VISIBLE); //Layout with play (and pause) button, Seekbar (which isn't moving along with the video), and timer (string being returned by the above displayCurrentTime() method)
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
});
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
long lengthPlayed = (YPlayer.getDurationMillis() * progress) / 100;
YPlayer.seekToMillis((int) lengthPlayed);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
runOnUiThread(new Runnable() {
#Override
public void run() {
while(YPlayer != null && seekBar.getMax() > YPlayer.getCurrentTimeMillis())
{
int videoProgressed = 0;
try
{
Thread.sleep(1000);
videoProgressed = YPlayer.getCurrentTimeMillis();
}
catch (Exception e)
{
e.printStackTrace();
}
seekBar.setProgress(videoProgressed);
}
}
});
private void displayCurrentTime() {
if (YPlayer != null) {
String formattedTime = formatTime(YPlayer.getCurrentTimeMillis());
playTime.setText(formattedTime);
}
}
private String formatTime(int millis) {
int seconds = millis / 1000;
int minutes = seconds / 60;
return String.format("%02d:%02d", minutes % 60, seconds % 60);
}
private Runnable runnable = new Runnable() {
#Override
public void run() {
if(YPlayer != null) {
displayCurrentTime();
}
handler.postDelayed(this, 1000);
}
};
USE THIS CODE
Custom youtube player CHROMELESS style - set SeekBar Progress and Seek Bar TrackingTouch Forward/backward,
mSeekBar = (SeekBar) findViewById(R.id.video_seekbar);
mSeekBar.setOnSeekBarChangeListener(mVideoSeekBarChangeListener)
SeekBar.OnSeekBarChangeListener mVideoSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
long lengthPlayed = (mYouTubePlayer.getDurationMillis() * seekBar.getProgress()) / 100;
mYouTubePlayer.seekToMillis((int) lengthPlayed);
}
};
private Runnable runnable = new Runnable() {
#Override
public void run(){
displayCurrentTime();
mHandler.postDelayed(this, 100);
}
};
private void displayCurrentTime() {
if (null == mYouTubePlayer) return;
String formattedTime = formatTime(mYouTubePlayer.getDurationMillis() - mYouTubePlayer.getCurrentTimeMillis());
play_timetv.setText(formattedTime);
playPercent = (int) (((float) mYouTubePlayer.getCurrentTimeMillis()/(float) mYouTubePlayer.getDurationMillis()) * 100);
System.out.println("get youtube displayTime 2 : "+playPercent);
// update live progress
mSeekBar.setProgress(playPercent, true);
}
Check this tutorial if it can help you. This tutorial is all about Android Building Audio Player. It discuss here on how to build a simple audio player with basic controls like play, pause, forward, backward, next, previous, playlist and seekbar.
Just check the code in where the tutorial explain on how to update progress bar timer implemented in a background thread which runs in background using a Handler. You can check here how the seekbar being implemented.
For more information, check this related SO question.
Add youtubeSeekBar.setProgress(yPlayer.getCurrentTimeMillis()/100); in on playing() event
YPlayer.setPlaybackEventListener(new YouTubePlayer.PlaybackEventListener() {
#Override
public void onPlaying() {
handler.postDelayed(runnable, 100); //Handler's instance initialized as instance variable
displayCurrentTime();
youtubeSeekBar.setProgress(yPlayer.getCurrentTimeMillis()/100); //this is your key of success
}
#Override
public void onPaused() {
handler.removeCallbacks(runnable);
}
#Override
public void onStopped() {
}
#Override
public void onBuffering(boolean b) {
handler.postDelayed(runnable, 1000);
}
#Override
public void onSeekTo(int i) {
handler.removeCallbacks(runnable);
}
});
playerControl.setVisibility(View.VISIBLE); //Layout with play (and pause) button, Seekbar (which isn't moving along with the video), and timer (string being returned by the above displayCurrentTime() method)
}

How to control the audio using Android Media Player seek bar?

I am able to use the android media player to play audio files. I can display the progress bar and attached 2 buttons to pause and play the audio track. My problem is I cannot control the track using the progress bar. I want to playing audio track to update depending of where I drag the progress bar to.
Below is my code
public class MyMediaPlayerView extends AppCompatActivity implements View.OnClickListener {
/**
* var for controller
* restore timestamp today 12:11
*/
SeekBar seek_bar;
Button play_button, pause_button;
MediaPlayer player;
TextView text_shown;
Handler seekHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launch_webview);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getInit();
seekUpdation();
}
Runnable run = new Runnable() {
#Override public void run() {
seekUpdation();
}
};
public void seekUpdation() {
seek_bar.setProgress(player.getCurrentPosition());
seekHandler.postDelayed(run, 1000);
onProgressChanged(seek_bar, seek_bar.getProgress());
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.play_button: text_shown.setText("Playing...");
player.start();
break; case R.id.pause_button: player.pause();
text_shown.setText("Paused...");
}
}
public void onProgressChanged(SeekBar seek_Bar, int progress,
boolean fromUser) {
player.seekTo(progress);
}
}
Im doing it like this
seek_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(fromUser)
player.seekTo(progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
u forget to add listener
put this in your onCreate() :
seek_bar = (SeekBar)findViewById(R.id.yourseekbarhere);
seek_bar.setOnSeekBarChangeListener(this);
Should help u out

Can't pass an int from button if / else case to media player

how are you supposed to let the mediaplayer know what it is supposed to play?
wholeTextPlayer = MediaPlayer.create(Lesson1Reading.this, engAu);
It works fine if I declare the file in the top:
MediaPlayer wholeTextPlayer;
private int engAu = R.raw.l1r_en_l10;
Button btn_default_acc_whole;
It doesn't work from within a button click if / else statement wherever I try to put it with the following combination:
MediaPlayer wholeTextPlayer;
private int engAu;
Button btn_default_acc_whole;
The button click:
final Button btn_default_acc_whole = (Button) findViewById(R.id.btn_default_acc_whole);
btn_default_acc_whole.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
if (wholeTextPlayer.isPlaying()) {
wholeTextPlayer.pause();
} else {
wholeTextPlayer.start();
startPlayProgressUpdater();
}
setEngAu(R.raw.l1r_en_l10); //this line doesn't want to fit anywhere
}
});
The setter:
public void setEngAu(int engAu) {
this.engAu = engAu;
}
Of course they are separately placed in the activity, I just copied and pasted the relevant bits from it.
Thanks guys.
Here is the whole code:
'public class Lesson1Grammar extends Activity {
private SeekBar seekBar;
MediaPlayer wholeTextPlayer;
private int engAu;
private final Handler handler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lesson1grammar);
WholeDefAccPlayer();
final RelativeLayout playerScreen = (RelativeLayout)findViewById(R.id.playerScreen);
final ImageButton btn_player_screen = (ImageButton) findViewById(R.id.btn_player_screen);
btn_player_screen.setOnClickListener(new View.OnClickListener() {
//this hides/unhides the part of the layout in which the player is
#Override
public void onClick(View arg0) {
if (playerScreen.isShown()) {
playerScreen.setVisibility(View.GONE);
} else {
playerScreen.setVisibility(View.VISIBLE);
}
}
});
final Button btn_default_acc_whole = (Button) findViewById(R.id.btn_default_acc_whole);
btn_default_acc_whole.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
if (wholeTextPlayer.isPlaying()) {
wholeTextPlayer.pause();
} else {
setEngAu(R.raw.default_acc_audio);
wholeTextPlayer.start();
startPlayProgressUpdater();
}
}
});
}
public void setEngAu(int engAu) {
this.engAu = engAu;
}
private void WholeDefAccPlayer() {
wholeTextPlayer = MediaPlayer.create(Lesson1Grammar.this, engAu);
((TextView) findViewById(R.id.getTitleOfAccent)).setText(R.string.btn_lesson1reading);
seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.setMax(wholeTextPlayer.getDuration());
seekBar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
seekChange(v);
return false;
}
});
}
public void startPlayProgressUpdater() {
seekBar.setProgress(wholeTextPlayer.getCurrentPosition());
if (wholeTextPlayer.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
startPlayProgressUpdater();
}
};
handler.postDelayed(notification, 1000);
}
else wholeTextPlayer.pause();
}
// This is event handler thumb moving event
private void seekChange(View v){
if(wholeTextPlayer.isPlaying()){
SeekBar sb = (SeekBar)v;
wholeTextPlayer.seekTo(sb.getProgress());
}
}
}
'
if your plan is to make the method setEngAu() is the controller as you mentioned in the comment. then you you need to use that method like this
public void setEngAu(int enAu)
{
this.EngAu = enAu;
wholeTextPlayer.setDataSource(engAu);
wholeTextPlayer.prepare();
}
you need to implement onPrepared listener from the media player
I do not know your classes but I assume where you say something like;
wholeTextPlayer = new MediaPlayer();
wholeTextPlayer.setOnPreparedListener(this);
here you start the player after it became prepared
public void onPrepared(MediaPlayer player)
{
player.start();
}
Remember to you will need to call wholeTextPlayer.release() if you do not want the player to hold on that resource anymore( think of it as memory issues - recommended if you check the documentation)
EDIT :
I adjusted your code a little, please take a look and let me know.
private SeekBar seekBar;
MediaPlayer wholeTextPlayer;
private int engAu;
final Handler handler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.lesson1grammar);
WholeDefAccPlayer();
final RelativeLayout playerScreen = (RelativeLayout) findViewById(R.id.playerScreen);
final ImageButton btn_player_screen = (ImageButton) findViewById(R.id.btn_player_screen);
btn_player_screen.setOnClickListener(new View.OnClickListener()
{
//this hides/unhides the part of the layout in which the player is
#Override
public void onClick(View arg0)
{
if(playerScreen.isShown())
{
playerScreen.setVisibility(View.GONE);
}
else
{
playerScreen.setVisibility(View.VISIBLE);
}
}
});
final Button btn_default_acc_whole = (Button) findViewById(R.id.btn_default_acc_whole);
btn_default_acc_whole.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{//problem here is
if(playerState == PlayerState_Playing)
{
wholeTextPlayer.pause();
setPlayerState(PlayerState_Paused);
}
else if(playerState == PlayerState_Paused)
{
wholeTextPlayer.start();
setPlayerState(PlayerState_Playing);
}
else
{
setEngAu(R.raw.default_acc_audio);
wholeTextPlayer.start();
startPlayProgressUpdater();
setPlayerState(PlayerState_Playing);
}
}
});
}
public void setEngAu(int engAu)
{
this.engAu = engAu;
if(wholeTextPlayer !=null)
{//just in case you call this method and player was not initialized yet
wholeTextPlayer.release();
}
setPlayerState(PlayerState_Preparing);
wholeTextPlayer = MediaPlayer.create(this, engAu);
}
private void WholeDefAccPlayer()
{
//this line probably will fail because engAu is not really initialized yet, unless you have default value for it
wholeTextPlayer = MediaPlayer.create(this, engAu);
((TextView) findViewById(R.id.getTitleOfAccent)).setText(R.string.btn_lesson1reading);
seekBar = (SeekBar) findViewById(R.id.seekBar);
//you can not call getDuration unless the player is prepared, so this might crash you
// seekBar.setMax(wholeTextPlayer.getDuration());
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
{
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b)
{
if(playerState != PlayerState_Preparing)
{//if player state is preparing it means we can not seek yet, player.start() must be called first
wholeTextPlayer.seekTo(i);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar)
{
}
#Override
public void onStopTrackingTouch(SeekBar seekBar)
{
}
});
}
public void startPlayProgressUpdater()
{
if(seekBar.getMax() != wholeTextPlayer.getDuration())
{//in case you change track later, this will check if the seek bar max value with track duration.
// if they are not the same, then it will adjust it for you
seekBar.setMax(wholeTextPlayer.getDuration());
}
seekBar.setProgress(wholeTextPlayer.getCurrentPosition());
if(wholeTextPlayer.isPlaying())
{
Runnable notification = new Runnable()
{
public void run()
{
startPlayProgressUpdater();
}
};
handler.postDelayed(notification, 1000);
}
else wholeTextPlayer.pause();
}
// This is event handler thumb moving event
private void seekChange(View v)
{
if(wholeTextPlayer.isPlaying())
{
SeekBar sb = (SeekBar) v;
wholeTextPlayer.seekTo(sb.getProgress());
}
}
private final int PlayerState_Preparing = 0;
private final int PlayerState_Playing = 1;
private final int PlayerState_Paused = 2;
private int playerState;
private void setPlayerState(int state)
{//this is used to track the player state, because wholeTextPlayer.isPlaying() can return false in many conditions ( too general )
//you can check in the media player documentation to know more details about this
playerState = state;
}

Categories

Resources