This is part of the code in my MainActivity.
stopwatch1 is an image button called in MainActivity:
stopwatch1 = (ImageButton)findViewById(R.id.stopwatch1);
I have tried searching for clues on how to use dialog.setOnDismissListener, however, there aren't proper answers to help me with the killing of the audio after deliberate or accidental exit of the dialog. Any help would be appreciated.
stopwatch1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog mmDialog1 = new Dialog(context);
mmDialog1.setContentView(R.layout.countdowntimer);
mmDialog1.setTitle("Stop-watch");
Button ddButton1 = (Button) mmDialog1.findViewById(R.id.countdown_exit);
final Button ddButton2 = (Button) mmDialog1.findViewById(R.id.countdown_start);
final TextView timeview = (TextView) mmDialog1.findViewById(R.id.timeview);
ddButton2.setTag(1);
ddButton2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final int status = (Integer) v.getTag();
if (status == 1) {
ddButton2.setText("Stop");
countDownTimer = new CountDownTimer(60000, 1000) {
public void onTick(long millisUntilFinished) {
int time = (int) (millisUntilFinished/1000);
timeview.setText(Integer.toString(time));
}
#Override
public void onFinish() {
timeview.setText("60");
ddButton2.setText("Start");
MediaPlayer stop = MediaPlayer.create(context, R.raw.stop);
stop.start();
}
}.start();
v.setTag(0);
} else {
ddButton2.setText("Start");
timeview.setText("60");
countDownTimer.cancel();
v.setTag(1);
}
}
});
ddButton1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mmDialog1.dismiss();
}
});
mmDialog1.show();
}
});
My suggestion would be to implement an interface. When the dialog closes, have the callback shut off the media player.
A quick example is this.
interface
public interface DialogClosed {
void shutDownMediaPlayer();
}
then implement the interface in the calling activity
activity
public class MainActivity extends Activity implements DialogClosed {
....
#Override
public void shutDownMediaPlayer() {
//shut down media player here
}
}
Also, you may add a boolean to check if the dialog is showing like this
boolean isShowing = mDialog.isShowing();
and then you can just shut off the media player at any point if this is false.
So I've used some pointers from Jawascript and also edited my code a little, now it works:
stopwatch1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog mmDialog1 = new Dialog(context);
mmDialog1.setContentView(R.layout.countdowntimer);
mmDialog1.setTitle("Stop-watch");
Button ddButton1 = (Button) mmDialog1.findViewById(R.id.countdown_exit);
final Button ddButton2 = (Button) mmDialog1.findViewById(R.id.countdown_start);
final TextView timeview = (TextView) mmDialog1.findViewById(R.id.timeview);
final MediaPlayer stop = MediaPlayer.create(context, R.raw.stop);
ddButton2.setTag(1);
mmDialog1.setCancelable(false);
if (mmDialog1.isShowing() == false) {
stop.stop();
}
ddButton2.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
final int status = (Integer) v.getTag();
if (status == 1) {
ddButton2.setText("Stop");
countDownTimer = new CountDownTimer(60000, 1000) {
public void onTick(long millisUntilFinished) {
int time = (int) (millisUntilFinished/1000);
timeview.setText(Integer.toString(time));
}
#Override
public void onFinish() {
timeview.setText("60");
ddButton2.setText("Start");
try {
stop.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
stop.start();
}
}.start();
v.setTag(0);
} else {
ddButton2.setText("Start");
timeview.setText("60");
countDownTimer.cancel();
v.setTag(1);
stop.stop();
}
}
});
ddButton1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mmDialog1.dismiss();
}
});
mmDialog1.show();
}
});
Related
This is my second activity and when open this activity threw button activity take load and open after some time and some times UI Freeze and some time black screen open for some seconds
public class AartiActivity extends AppCompatActivity {
final MediaPlayer player1 = new MediaPlayer();
private Button btn_playarti, btn_pausearti, btn_stoparti;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_aarti);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
btn_playarti = (Button) findViewById(R.id.btn_playarti);
btn_pausearti = (Button) findViewById(R.id.btn_pausearti);
btn_stoparti = (Button) findViewById(R.id.btn_stoparti);
try {
player1.setDataSource(STRING_URL);
player1.prepare();
} catch (IOException e) {
e.printStackTrace();
}
btn_playarti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
player1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer player) {
player.stop();
}
});
player1.start();
}
});
btn_pausearti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (player1.isPlaying()) {
player1.pause();
}
}
});
btn_stoparti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
player1.stop();
}
});
}
#Override
protected void onStop() {
super.onStop();
player1.stop();
}
}
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'm creating an audio playback application. I've currently just got two tracks added but eventually I need to add many more... I've currently created two different mediaplayers to run both the tracks, however as the number of tracks will increase using this procedure will lead to problems and lack of performance!
Is there some way I can code this better and more generically?
Here's the java code
public class ChantsFragment extends Fragment {
TextView text1, text2
ImageButton play1, play2, pause1, pause2, repeatoff1, repeatoff2, repeaton1, repeaton2, stop1, stop2;
MediaPlayer mediaPlayer1, mediaPlayer2;
Toast on, off;
public ChantsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_chants, container, false);
play1 = (ImageButton) view.findViewById(R.id.play1);
play2 = (ImageButton) view.findViewById(R.id.play2);
pause1 = (ImageButton) view.findViewById(R.id.pause1);
pause2 = (ImageButton) view.findViewById(R.id.pause2);
repeatoff1 = (ImageButton) view.findViewById(R.id.repeatoff1);
repeatoff2 = (ImageButton) view.findViewById(R.id.repeatoff2);
repeaton1 = (ImageButton) view.findViewById(R.id.repeaton1);
repeaton2 = (ImageButton) view.findViewById(R.id.repeaton2);
stop1 = (ImageButton) view.findViewById(R.id.stop1);
stop2 = (ImageButton) view.findViewById(R.id.stop2);
mediaPlayer1 = MediaPlayer.create(getActivity(), R.raw.audio1);
mediaPlayer2 = MediaPlayer.create(getActivity(), R.raw.audio2);
on = Toast.makeText(getActivity(), "The chant will repeat itself", Toast.LENGTH_LONG);
off = Toast.makeText(getActivity(), "The chant will no longer repeat itself", Toast.LENGTH_LONG);
//Track 1
text1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer1 != null && mediaPlayer1.isPlaying()) {
text1.setClickable(false);
}
if (mediaPlayer2 != null && mediaPlayer2.isPlaying()) {
mediaPlayer2.stop();
mediaPlayer2.release();
mediaPlayer2 = null;
play2.setVisibility(View.GONE);
pause2.setVisibility(View.GONE);
repeatoff2.setVisibility(View.GONE);
repeaton2.setVisibility(View.GONE);
stop2.setVisibility(View.GONE);
}
if (mediaPlayer1 == null) {
mediaPlayer1 = MediaPlayer.create(getActivity(), R.raw.audio1);
} else {
text1.setClickable(true);
mediaPlayer1.start();
play1.setVisibility(View.GONE);
pause1.setVisibility(View.VISIBLE);
repeatoff1.setVisibility(View.VISIBLE);
stop1.setVisibility(View.VISIBLE);
}
mediaPlayer1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
play1.setVisibility(View.GONE);
pause1.setVisibility(View.GONE);
repeatoff1.setVisibility(View.GONE);
repeaton1.setVisibility(View.GONE);
stop1.setVisibility(View.GONE);
}
});
}
});
play1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
play1.setVisibility(View.GONE);
pause1.setVisibility(View.VISIBLE);
mediaPlayer1.start();
}
});
pause1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
play1.setVisibility(View.VISIBLE);
pause1.setVisibility(View.GONE);
mediaPlayer1.pause();
}
});
repeatoff1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer1.setLooping(true);
repeatoff1.setVisibility(View.GONE);
repeaton1.setVisibility(View.VISIBLE);
on.show();
off.cancel();
}
});
repeaton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer1.setLooping(false);
repeaton1.setVisibility(View.GONE);
repeatoff1.setVisibility(View.VISIBLE);
off.show();
on.cancel();
}
});
stop1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer1.stop();
mediaPlayer1 = null;
text1.setClickable(true);
play1.setVisibility(View.GONE);
pause1.setVisibility(View.GONE);
repeatoff1.setVisibility(View.GONE);
repeaton1.setVisibility(View.GONE);
stop1.setVisibility(View.GONE);
}
});
//Track 2
text2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer2 != null && mediaPlayer2.isPlaying()) {
text2.setClickable(false);
}
if (mediaPlayer1 != null && mediaPlayer1.isPlaying()) {
mediaPlayer1.stop();
mediaPlayer1.release();
mediaPlayer1 = null;
play1.setVisibility(View.GONE);
pause1.setVisibility(View.GONE);
repeatoff1.setVisibility(View.GONE);
repeaton1.setVisibility(View.GONE);
stop1.setVisibility(View.GONE);
}
if (mediaPlayer2 == null) {
mediaPlayer2 = MediaPlayer.create(getActivity(), R.raw.audio2);
} else {
text2.setClickable(true);
mediaPlayer2.start();
play2.setVisibility(View.GONE);
pause2.setVisibility(View.VISIBLE);
repeatoff2.setVisibility(View.VISIBLE);
stop2.setVisibility(View.VISIBLE);
}
mediaPlayer2.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
play2.setVisibility(View.GONE);
pause2.setVisibility(View.GONE);
repeatoff2.setVisibility(View.GONE);
repeaton2.setVisibility(View.GONE);
stop2.setVisibility(View.GONE);
}
});
}
});
play2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
play2.setVisibility(View.GONE);
pause2.setVisibility(View.VISIBLE);
mediaPlayer2.start();
}
});
pause2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
play2.setVisibility(View.VISIBLE);
pause2.setVisibility(View.GONE);
mediaPlayer2.pause();
}
});
repeatoff2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer2.setLooping(true);
repeatoff2.setVisibility(View.GONE);
repeaton2.setVisibility(View.VISIBLE);
on.show();
off.cancel();
}
});
repeaton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer2.setLooping(false);
repeaton2.setVisibility(View.GONE);
repeatoff2.setVisibility(View.VISIBLE);
off.show();
on.cancel();
}
});
stop2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer2.stop();
mediaPlayer2 = null;
text2.setClickable(true);
play2.setVisibility(View.GONE);
pause2.setVisibility(View.GONE);
repeatoff2.setVisibility(View.GONE);
repeaton2.setVisibility(View.GONE);
stop2.setVisibility(View.GONE);
}
});
return view;
}
Edit
I've currently zeroed down on adding around 10 tracks to the application. I want playback to stop on the current track (if playing) the moment another track is selected and using media player to do the same would mean checking separately if 9 media players are playing! (Unless of course there's another way to do this which I've completely missed)
Well, for playing multiple audio files at once, SoundPool seems to be your best choice mainly because its much more lightweight and you can control the number of streams. You can create a new SoundPool instance as:
SoundPool soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 100); // 10 = maxStreams, 100 = quality
You can then start loading different sounds into it as:
int soundId1 = soundPool.load(context, R.raw.audio1, 1);
int soundId2 = soundPool.load(context, R.raw.audio2, 1);
...
You can control playback as:
int idBeingPlayed = soundPool.play (soundID, 1, 1, 1, -1, 1); // volume params, returns the streamId
Other controls:
soundPool.pause(streamID);
soundPool.resume(streamID);
For more info, visit the offfical docs. Hope this helps!
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;
}
I have been spending couple hours to try to update the textview inside the dialog, but failed.
When the option is clicked, there are new dialog is shown, and inside the dialog, there are textviews and button, when I click the button, the textview will be update.
Here is the code related to the button onClick listener:
start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
for (int i = 0; i < 50 ; i ++){
final String currentNum = String.valueOf(i + 1);
Thread t = new Thread() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(currentNum); //it is fine
currentNum.setText(currentNum); //it is the problem, the setText only work when the for loop is finished.
}
});
}
};
t.start();
}
}
});
Please let me know if you need more information. Thanks a lot in advance!
//it is a optionmenu
case R.id.action_refresh:
final TextView currentNum;
final ImageButton start;
String currentNum = Integer.toString(songList.size());
final Dialog lyricsAnalysis = new Dialog(this,R.style.cust_dialog);
lyricsAnalysis.requestWindowFeature(Window.FEATURE_NO_TITLE);
lyricsAnalysis.setContentView(R.layout.analysis);
lyricsAnalysis.setCancelable(true); //back button to cancel
lyricsAnalysis.setCanceledOnTouchOutside(true);
start = (ImageButton) lyricsAnalysis.findViewById(R.id.start);
//first value
currentNum.setText(String.valueOf(currentNum));
start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
for (int i = 0; i < 50 ; i ++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
updateTextView(lyricsAnalysis,i);
}
}
});
lyricsAnalysis.show();
lyricsAnalysis.getWindow().setLayout(600, 1000);
break;
}
return super.onOptionsItemSelected(item); }
public void updateTextView(Dialog dialog, int i) {
final TextView currentNum = (TextView) dialog.findViewById(R.id.currentNum);
currentNum.setText(Stri`enter code here`ng.valueOf(i));
//return;
}
Try this method. This may helps you. It's work for me.(But I am not use this in dialog)
public void updateTextView(String toThis) {
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(toThis);
//return;
}
try like this
int elapsedtime=0;
boolean isTimerRunning=false;
Timer timerr;
inside onCreate
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//declare your textview here;
timerr=new Timer();
startTimer();
}
/*
* timer for displaying message bubble
*/
protected static void startTimer() {
isTimerRunning = true;
elapsedtime = 0;
// recordingseek.setProgress(0);
timerr.scheduleAtFixedRate(new TimerTask() {
public void run() {
// increase every sec
elapsedtime++;
mmHandler.obtainMessage(1).sendToTarget();
System.out.println("recording time" + elapsedtime);
if(elapsedtime==50)
timerr.cancel();
}
}, 1000, 2000);
};
public static Handler mmHandler = new Handler() {
public void handleMessage(Message msg) {
textview.setText(elapsedtime);
}
};
}
};