Hi am trying to stream online radio while opening my app when buffering first time it runs fine while i close the app and then start again the app it plays from where the player last closed and then stopped after it ends and i have to startup manually to stream the url for current level of radio
my coding:
public class MainActivity extends AppCompatActivity {
DrawerLayout drawer;
ImageView list_activity_check;
ImageView share,speaker,mute, control;
DrawerListAdapter drawerListAdapter;
ListView listview_nav;
private SmallBang mSmallBang;
String [] Items={"Program Lists","Rate app"} ;
int [] images={R.drawable.pro_logo,
R.drawable.rate_icon} ;
String[] titles = {
"Ippadikku Idhayam",
"Akilam 360",
"Cine Pattarai",
"Palsuvai Thoranam",
"Pesum Noolagam",
"Lollu Cafe",
"Kavi Saagaram",
"Aa muthal Akk",
"Thiraicholai",
"Kathamba Saaral",
"Paarkatha Pakkangal",
"Pagadi Panna Porom",
};
public static final String[] fromtime = new String[]{"10:30 AM","12:30 PM","14:30 PM","16:30 PM","18:30 PM","20:30 PM","22:30 PM","00:30 AM","02:30 AM","04:30 AM","06:30 AM","08:30 AM"};
public static final String[] totime = new String[]{"12:30 PM","14:30 PM","16:30 PM","18:30 PM","20:30 PM","22:30 PM","00:30 AM","02:30 AM","04:30 AM","06:30 AM","08:30 AM","10:30 AM"};
Integer[] images0 = {
R.drawable.ipadikku_idhayam,
R.drawable.akilam_360,
R.drawable.cine_pattarai,
R.drawable.palsuvai_thoranam,
R.drawable.pesum_noolagam,
R.drawable.lollu_cafe,
R.drawable.kavi_saagaram,
R.drawable.aa_muthal_akk,
R.drawable.thiraicholai,
R.drawable.kathamba_saaral,
R.drawable.paarkatha_pakkangal,
R.drawable.pagadi_panna_porom,
};
//************* Current Show ***************//
ListView list,lvshow;
List<Program> rowItems;
int iImageId;
String sTitle,sFrom,sTo ;
SQLiteDatabase db;
ImageView music;
int media1;
int intValue1;
AdapAdapter Adapadapter;
ArrayList<String> iTitle = null;
ArrayList<String> sQuantity = null;
ArrayList<String> sQuantity1 = null;
ArrayList<String> sImageID = null;
//***************************************//
SeekBar seekbar;
AudioManager audioManager;
MediaPlayer media, mediaPlayer;
boolean playPause = false;
boolean intialStage = true;
int intvalue ;
ImageView timer;
private static final int NOTIFICATION_ID = 1;
String URL = "http://streaming.shoutcast.com/MUKILFMRADIO";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addNotification();
mSmallBang = SmallBang.attach2Window(this);
list_activity_check = (ImageView) findViewById(R.id.list_view);
share = (ImageView) findViewById(R.id.share);
speaker = (ImageView) findViewById(R.id.speaker);
mute = (ImageView) findViewById(R.id.mute);
control = (ImageView) findViewById(R.id.play);
timer = (ImageView) findViewById(R.id.timer);
//************ Current show ************//
db = this.openOrCreateDatabase("MukilApp",Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS proname(ID INTEGER PRIMARY KEY AUTOINCREMENT,ImageID INTEGER,Title TEXT,FromTiming INTEGER,ToTiming INTEGER);");
rowItems = new ArrayList<Program>();
for (int i = 0; i < titles.length; i++) {
Program item = new Program(images0[i], titles[i],fromtime[i],totime[i]);
rowItems.add(item);
}
db.execSQL("DELETE FROM proname;");
lvshow = (ListView) findViewById(R.id.lvshow);
// listView.setVisibility(View.INVISIBLE);
final ProgramAdapter adapter = new ProgramAdapter(this,rowItems, false);
for (int i = 0; i < adapter.getCount(); i++) {
Program rowItem = (Program) adapter.getItem(i);
iImageId = rowItem.getImageId();
sTitle = rowItem.getTitle();
sFrom = rowItem.getFromtime();
sTo = rowItem.getTotime();
db.execSQL("INSERT INTO proname (ImageID,Title,FromTiming,ToTiming) VALUES(" + iImageId + ",'" + sTitle + "','" + sFrom + "','" + sTo + "');");
}
final Cursor cView = db.rawQuery("SELECT * FROM proname WHERE FromTiming <= time('now', 'localtime')\n" + "" +
"AND ToTiming >= time('now', 'localtime')\n", null);
if (cView.getCount() > 0) {
sImageID = new ArrayList<String>();
iTitle = new ArrayList<String>();
sQuantity = new ArrayList<String>();
sQuantity1 = new ArrayList<String>();
while (cView.moveToNext()) {
sImageID.add(cView.getString(1));
iTitle.add(cView.getString(2));
sQuantity.add(cView.getString(3));
sQuantity1.add(cView.getString(4));
Adapadapter = new AdapAdapter(this, sImageID, iTitle, sQuantity, sQuantity1);
lvshow.setAdapter(Adapadapter);
}
}
//*************************************//
timer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSmallBang.bang(v);
mSmallBang.setmListener(new SmallBangListener() {
#Override
public void onAnimationStart() {
}
#Override
public void onAnimationEnd() {
Intent slideactivity = new Intent(MainActivity.this, Timer_Activity.class);
Bundle bndlanimation =
ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animate1, R.anim.animate2).toBundle();
// startActivity(slideactivity, bndlanimation);
startActivityForResult(slideactivity, 1001,bndlanimation);
// finish();
}
});
}
});
media = MediaPlayer.create(this,R.raw.mukil_master_jingle);
media.start();
media.setLooping(true);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
if (intialStage) {
new Player()
.execute(URL);
}
intvalue = mediaPlayer.getAudioSessionId();
control.setBackgroundResource(R.drawable.pause);
control.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (playPause == false) {
control.setBackgroundResource(R.drawable.play);
mediaPlayer.stop();
new Player().cancel(true);
media.stop();
media.reset();
mediaPlayer.reset();
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
mediaPlayer.reset();
media.stop();
playPause = true;
} else {
control.setBackgroundResource(R.drawable.pause);
if (intialStage) {
new Player()
.execute(URL);
} else {
if (!mediaPlayer.isPlaying())
mediaPlayer.start();
}
playPause = false;
}
}
});
speaker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speaker.setVisibility(View.INVISIBLE);
mute.setVisibility(View.VISIBLE);
media.setVolume(0, 0);
mediaPlayer.setVolume(0, 0);
speaker.setImageResource(R.drawable.speaker);
mSmallBang.bang(v);
mSmallBang.setmListener(new SmallBangListener() {
#Override
public void onAnimationStart() {
}
#Override
public void onAnimationEnd() {
}
});
}
});
mute.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
speaker.setVisibility(View.VISIBLE);
mute.setVisibility(View.INVISIBLE);
media.setVolume(1, 1);
mediaPlayer.setVolume(1, 1);
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayShowTitleEnabled(false); // hide built-in Title
}
try {
seekbar = (SeekBar) findViewById(R.id.seekbar1);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
seekbar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
seekbar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
}
#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
progress, 0);
}
});
} catch (Exception e) {
e.printStackTrace();
}
listview_nav = (ListView) findViewById(R.id.listview_nav);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
drawerListAdapter = new DrawerListAdapter(MainActivity.this, Items, images);
listview_nav.setAdapter(drawerListAdapter);
listview_nav.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position == 0){
Intent in = new Intent(MainActivity.this,ShowList_Activity.class);
startActivity(in);
}else if(position == 1){
}
}
});
list_activity_check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list_activity_check.setImageResource(R.drawable.playlist);
mSmallBang.bang(v);
mSmallBang.setmListener(new SmallBangListener() {
#Override
public void onAnimationStart() {
}
#Override
public void onAnimationEnd() {
Intent slideactivity = new Intent(MainActivity.this, EqualizerActivity.class);
slideactivity.putExtra("sessionvalue", intvalue);
Bundle bndlanimation =
ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animate1, R.anim.animate2).toBundle();
startActivity(slideactivity, bndlanimation);
}
});
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
share.setImageResource(R.drawable.share_icon);
mSmallBang.bang(v);
mSmallBang.setmListener(new SmallBangListener() {
#Override
public void onAnimationStart() {
}
#Override
public void onAnimationEnd() {
}
});
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"https://play.google.com/store/apps/details?id=com.digitamatix.mukilfm");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "https://play.google.com/store/apps/details?id=com.digitamatix.mukilfm" + " Mukil FM shareApp");
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
});
PhoneStateListener phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
//INCOMING call
//do all necessary action to pause the audio
if(mediaPlayer!=null){//check mp
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
}
}
if(media!=null){//check mp
if(media.isPlaying()){
media.pause();
}
}
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
//Not IN CALL
//do anything if the phone-state is idle
if(mediaPlayer == null){//check mp
if(!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
}
if(media==null){//check mp
if(!media.isPlaying()){
media.start();
}
}
} else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
//A call is dialing, active or on hold
//do all necessary action to pause the audio
//do something here
if(mediaPlayer!=null){//check mp
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
}
}
if(media!=null){//check mp
if(media.isPlaying()){
media.pause();
}
}
}
super.onCallStateChanged(state, incomingNumber);
}
};//end PhoneStateListener
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
private void addNotification() {
NotificationCompat.Builder builder =
(NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.mukil)
.setContentTitle("MUKIL FM")
.setContentText("Smartah Kelunga Ungal MukilFm");
// Add as notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
class Player extends AsyncTask<String, Void, Boolean> {
private ProgressDialog progress;
#Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
Boolean prepared;
try {
mediaPlayer.setDataSource(params[0]);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
intialStage = true;
playPause = false;
control.setBackgroundResource(R.drawable.play);
mediaPlayer.stop();
mediaPlayer.reset();
}
});
mediaPlayer.prepare();
mediaPlayer.prepareAsync();
prepared = true;
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
Log.d("IllegarArgument", e.getMessage());
prepared = false;
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
}
return prepared;
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (progress.isShowing()) {
progress.cancel();
}
Log.d("Prepared", "//" + result);
mediaPlayer.start();
media.stop();
intialStage = false;
}
public Player() {
progress = new ProgressDialog(MainActivity.this);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
this.progress.setMessage("Buffering...");
media.start();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1001) {
String result=data.getStringExtra("result");
if(result.equalsIgnoreCase("STOP")){
onStop();
finish();
}else if(result.equalsIgnoreCase("Do Nothing")){
Toast.makeText(this, "Timer is not set", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onStop() {
super.onStop();
if(media != null){
// media.stop(); //Stops playback after playback has been stopped or paused
media.release(); //Releases resources associated with this MediaPlayer object
media = null;
}
if(mediaPlayer!= null){
// mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer= null;
}
}
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
// set title
alertDialogBuilder.setTitle("Exit");
// set dialog message
alertDialogBuilder
.setMessage("Do you really want to exit?")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
MainActivity.this.finish();
mediaPlayer.release();
media.release();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
// super.onBackPressed();
}
}
please help me in fixing this issues..
Thank you in advance..
In your onStop() of your activity stop and release the media player.
Place the below code in your onStop():
#Override
public void onStop() {
super.onStop();
if(media != null){
media.stop(); //Stops playback after playback has been stopped or paused
media.release(); //Releases resources associated with this MediaPlayer object
media = null;
}
if(mediaPlayer!= null){
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer= null;
}
}
This is the proper way to stop media player.
Hope it helps:)
The Path where the file is located "/storage/sdcard/MediaRecorderSample/Recordingg2"
The errors i am getting
E/MediaPlayer: stop called in state 1,E/MediaPlayer: error (-38, 0),D/MediaPlayer: Couldn't open file on client side, trying server side
Here is my code
public class Player extends AppCompatActivity implements View.OnClickListener {
static MediaPlayer mp;
SeekBar sb;
ArrayList mysongs;
int pos;
Uri u;
Thread th;
String filepath;
File file;
Button btprev,btfb,btplay,btff,btnext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
mp = new MediaPlayer();
filepath = android.os.Environment.getExternalStorageDirectory().getPath();
file = new File(filepath,"MediaRecorderSample");
btplay=(Button) findViewById(R.id.btplay);
btff=(Button) findViewById(R.id.btff);
btnext=(Button) findViewById(R.id.btnxt);
btprev=(Button) findViewById(R.id.btprev);
btfb=(Button) findViewById(R.id.btfb);
btplay.setOnClickListener(this);
btff.setOnClickListener(this);
btnext.setOnClickListener(this);
btfb.setOnClickListener(this);
btprev.setOnClickListener(this);
sb= (SeekBar) findViewById(R.id.seekBar);
th = new Thread(){
#Override
public void run() {
int totalduration= mp.getDuration();
int currentposition=0;
sb.setMax(totalduration);
while(currentposition < totalduration)
{
try {
sleep(500);
currentposition = mp.getCurrentPosition();
sb.setProgress(currentposition);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//super.run();
}
};
// if(mp!=null)
// {
// mp.stop();
// mp.reset();
// mp.release();
// }
Intent i = getIntent();
Bundle b= i.getExtras();
pos = b.getInt("pos");
mysongs= b.getStringArrayList("mysongs");
Log.d("Mystring", String.valueOf(mysongs));
Log.d("path1",file.getAbsolutePath()+ "/" + mysongs.get(pos));
u = Uri.parse(file.getAbsolutePath()+ "/" + mysongs.get(pos)+".wav");
//mp.create(getApplicationContext(),u);
try {
if (mp != null) {
mp.stop();
}
mp.setDataSource(getApplicationContext(),u);
//mp.prepare();
mp.start();
th.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// mp = MediaPlayer.create(getApplicationContext(),u);
// try {
// mp.setDataSource(getApplicationContext(),u);
// mp.start();
// } catch (IOException e) {
// e.printStackTrace();
// }
//mp.start();
}
#Override
public void onClick(View v) {
int id = v.getId();
switch (id)
{
case R.id.btplay:
if(mp.isPlaying())
{
btplay.setText(">");
mp.pause();
}
else {
btplay.setText("||");
mp.start();
}
break;
case R.id.btff:
mp.seekTo(mp.getCurrentPosition()+ 5000);
break;
case R.id.btfb:
mp.seekTo(mp.getCurrentPosition()-5000);
break;
case R.id.btnxt:
mp.stop();
mp.reset();
mp.release();
pos =(pos+1)%mysongs.size();
u = Uri.parse(file.getAbsolutePath()+ "/"+mysongs.get(pos).toString());
// mp = MediaPlayer.create(getApplicationContext(),u);
try {
mp.setDataSource(getApplicationContext(),u);
mp.start();
} catch (IOException e) {
e.printStackTrace();
}
break;
case R.id.btprev:
mp.stop();
mp.reset();
mp.release();
pos =(pos-1<0)? mysongs.size()-1: pos-1;
u= Uri.parse(file.getAbsolutePath()+ "/"+mysongs.get(pos).toString());
// mp = MediaPlayer.create(getApplicationContext(),u);
try {
mp.setDataSource(getApplicationContext(),u);
mp.start();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
`
My ProgressBar does not reset after audio is done. It reset after some audio's but not others not sure why. Also would like to make pause icon change to play when audio is done if anyone can help out with that to, that will be great!
Heres code:
public class player1 extends Activity implements Runnable {
private MediaPlayer mp;
private ProgressBar progressBar;
private ImageButton pauseicon;
private final int NUM_SOUND_FILES = 3; //*****REPLACE THIS WITH THE ACTUAL NUMBER OF SOUND FILES YOU HAVE*****
private int mfile[] = new int[NUM_SOUND_FILES];
private Random rnd = new Random();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_1);
pauseicon = (ImageButton) findViewById(R.id.pauseicon);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
getActionBar().setDisplayHomeAsUpEnabled(true);
mfile[0] = R.raw.sound01; //****REPLACE THESE WITH THE PROPER NAMES OF YOUR SOUND FILES
mfile[1] = R.raw.sound02; //PLACE THE SOUND FILES IN THE /res/raw/ FOLDER IN YOUR PROJECT*****
mfile[2] = R.raw.sound03;
// Listeners
/**
* Play button click event
* plays a song and changes button to pause image
* pauses a song and changes button to play image
* */
try{
mp = MediaPlayer.create(player1.this, mfile[rnd.nextInt(NUM_SOUND_FILES)]);
mp.seekTo(0);
mp.start(); ;
progressBar.setVisibility(ProgressBar.VISIBLE);
progressBar.setProgress(0);
progressBar.setMax(mp.getDuration());
new Thread(this).start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
pauseicon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.pauseicon)
if(mp.isPlaying()){
mp.pause();
ImageButton pauseicon =(ImageButton) findViewById(R.id.pauseicon);
pauseicon.setImageResource(R.drawable.playicon);
} else {
mp.start();
ImageButton pauseicon =(ImageButton) findViewById(R.id.pauseicon);
pauseicon.setImageResource(R.drawable.pauseicon);
}}});
}
public void run() {
int currentPosition= 0;
int total = mp.getDuration();
while (mp!=null && currentPosition<total) {
try {
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
progressBar.setProgress(currentPosition);
}
}
public boolean onOptionsItemSelected(MenuItem item){
Intent myIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivityForResult(myIntent, 0);
return true;
}
}
First issue:
In the thread "run" method, in the while condition you are saying:
(currentPosition<total)
this way "currentPosition" value will never reach "total" value and your progressbar won't go, you should use "less than or equal":
(currentPosition<=total)
so code will be:
public void run() {
int currentPosition= 0;
int total = mp.getDuration();
while (mp!=null && mp.isPlaying() && currentPosition<=total) {
try {
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
progressBar.setProgress(currentPosition);
}
}
Second issue:
You can change the ImageButton using "mp.setOnCompletionListener(this)" like this:
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
pauseicon.setImageResource(R.drawable.playicon);
}
});
Set it while initializing the mediaplayer, before mp.start()
I have a problem of that how to setup seekbar to work correctly when I setProgress upon click. Progress is jumping to the beginning/middle/end depends on where I click on it. How is it possible to solve?
That my attemps:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
getWindow().setFormat(PixelFormat.TRANSLUCENT);
videoPath = getIntent().getExtras().getString("videoPath");
videoView = (VideoView) findViewById(R.id.vvPlayer);
seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.setOnSeekBarChangeListener(this);
....
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
seekBar.setMax(mp.getDuration());
System.out.println("curpos" + mp.getCurrentPosition());
new Thread(new Runnable() {
public void run() {
try {
while (mPlayer != null && mPlayer.getCurrentPosition() < mPlayer.getDuration()) {
seekBar.setProgress(mPlayer.getCurrentPosition());
Message msg = new Message();
int millis = mPlayer.getCurrentPosition();
msg.obj = millis / 1000;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("interrupt exeption" + e);
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("my Exception" + e);
}
}
}).start();
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
Log.e("onProgressChanged: ", Integer.toString(progress));
mPlayer.seekTo(progress);
}
}
Full Code:
public class VideoPlayerActivity extends Activity implements Callback, OnSeekBarChangeListener, OnTouchListener, OnErrorListener, OnCompletionListener, OnPreparedListener {
MediaPlayer mPlayer;
AssetFileDescriptor afd;
VideoView videoView;
SurfaceHolder holder;
MediaController mController;
String videoPath;
SeekBar seekBar;
ImageButton mPlay, mStop, mPause;
TextView mCurDuration, mDuration;
int position = 0;
Handler handler = new Handler();
Runnable r;
boolean controlsVisibility = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
getWindow().setFormat(PixelFormat.TRANSLUCENT);
mDuration = (TextView) findViewById(R.id.tvDuration);
mCurDuration = (TextView) findViewById(R.id.tvCurDuration);
videoPath = getIntent().getExtras().getString("videoPath");
videoView = (VideoView) findViewById(R.id.vvPlayer);
seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.setOnSeekBarChangeListener(this);
seekBar.setFocusable(false);
videoView.setOnTouchListener(this);
mPlay = (ImageButton) findViewById(R.id.play);
mPause = (ImageButton) findViewById(R.id.pause);
mStop = (ImageButton) findViewById(R.id.stop);
mController = new MediaController(this);
videoView.setMediaController(mController);
holder = videoView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mPlay.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Log.e("Play:", " is Pressed!");
if (mPlayer == null)
playVideo();
mPlayer.start();
}
});
mPause.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Log.e("Pause:", " is Pressed!");
if (mPlayer != null) {
handler.removeCallbacks(r);
controlsVisibility=true;
AutoHideControls();
Log.e("mPlayer status: ", "Not Null");
if (mPlayer.isPlaying())
Log.e("mPlayer status: ", "Not Null");
mPlayer.pause();
}
}
});
mStop.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Log.e("Stop:", " is Pressed!");
if (mPlayer != null) {
handler.removeCallbacks(r);
controlsVisibility=true;
AutoHideControls();
seekBar.setProgress(0);
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
}
});
}
private void playVideo() {
try {
if (afd != null && mPlayer != null) {
mPlayer.start();
return;
}
Log.e("VideoPath:", videoPath);
if (videoPath != "") {
afd = getAssets().openFd(videoPath);
// "videos/start.mp4"
mPlayer = new MediaPlayer();
mPlayer.setOnErrorListener(this);
mPlayer.setOnCompletionListener(this);
mPlayer.setOnPreparedListener(this);
mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mPlayer.setScreenOnWhilePlaying(true);
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setDisplay(holder);
mPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mPlayer.prepare();
mPlayer.start();
handler.removeCallbacks(r);
controlsVisibility=true;
AutoHideControls();
}
} 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 surfaceCreated(SurfaceHolder holder) {
runOnUiThread(new Runnable() {
public void run() {
playVideo();
}
});
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.e("Debug:", "onError---> what:" + what + " extra:" + extra);
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
return true;
}
#Override
public void onCompletion(MediaPlayer mp) {
mPlayer.release();
finish();
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
}
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (controlsVisibility) {
controlsVisibility = false;
mPlay.setVisibility(View.GONE);
mPause.setVisibility(View.GONE);
mStop.setVisibility(View.GONE);
seekBar.setVisibility(View.GONE);
handler.removeCallbacks(r);
} else {
controlsVisibility = true;
mPlay.setVisibility(View.VISIBLE);
mPause.setVisibility(View.VISIBLE);
mStop.setVisibility(View.VISIBLE);
seekBar.setVisibility(View.VISIBLE);
AutoHideControls();
}
return false;
}
public void AutoHideControls() {
r = new Runnable() {
public void run() {
controlsVisibility = false;
mPlay.setVisibility(View.GONE);
mPause.setVisibility(View.GONE);
mStop.setVisibility(View.GONE);
seekBar.setVisibility(View.GONE);
}
};
handler.removeCallbacks(r);
handler.postDelayed(r, 4000);
}
#Override
public void onPrepared(MediaPlayer mp) {
seekBar.setMax(mp.getDuration());
new Thread(new Runnable() {
public void run() {
int currentPosition = 0;
int total = mPlayer.getDuration();
seekBar.setMax(total);
while (mPlayer != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mPlayer.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekBar.setProgress(currentPosition);
}
}
}).start();
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
Log.e("onProgressChanged: ", Integer.toString(progress));
mPlayer.seekTo(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
The same but throughtout AsyncTask (but the same result - still jumping):
#Override
public void onPrepared(MediaPlayer mp) {
seekBar.setMax(mp.getDuration());
new Async().execute();
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
Log.e("onProgressChanged: ", Integer.toString(progress));
mPlayer.seekTo(progress);
seekBar.setProgress(progress);
Log.e("SeekedProgressTime: ", Integer.toString(mPlayer.getCurrentPosition()));
Log.e("SeekedProgressTime: ", Integer.toString(seekBar.getProgress()));
}
}
class Async extends AsyncTask<Void, Integer, Void> {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
int currentPosition = 0;
int total = mPlayer.getDuration();
seekBar.setMax(total);
while (mPlayer != null && currentPosition < total) {
Log.e("Current mPlayer time in Thread: ", Integer.toString(mPlayer.getCurrentPosition()));
Log.e("Current seekBar time in Thread: ", Integer.toString(seekBar.getProgress()));
try {
Thread.sleep(1000);
currentPosition = mPlayer.getCurrentPosition();
} catch (InterruptedException e) {
} catch (Exception e) {
}
seekBar.setProgress(currentPosition);
}
return null;
}
}
Maybe, I did something wrong inside the AsyncTask, I cannot understand what is the problem with this seekBar. Check what real position it takes when you click somewhere on the seekbar, everything correct but in one moment its position value overrides somehow.
I am trying to update two TextViews txtName and textEndName. When i debug sometimes it updates the text but rest of the time it does not works. Sometime it works but not not exactly what it is suppose to.What is the problem in the below given code ?
txtName = (TextView) findViewById(R.id.txtstarttag);
textEndName = (TextView) findViewById(R.id.txtendtag);
startSec = (TextView) findViewById(R.id.txtstartsecnd);
endSec = (TextView) findViewById(R.id.txtendsecnd);
btnplay = (ImageButton) findViewById(R.id.btnplay);
btnback = (Button) findViewById(R.id.btnback);
btnback.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((MyMixes) getParent()).goBack();
}
});
btnplay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
btnClick();
}
});
splitArray();
Thread t = new Thread()
{
public void run()
{
while (isDownloading)
{
if (Data.filenames != null && Data.filenames.size() >= (getIntent() .getExtras().getInt("index") + 1) && Data.filenames.get(getIntent().getExtras() .getInt("index")) != null)
{
try
{
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(Data.filenames.get(getIntent().getExtras().getInt("index")));
mediaPlayer.prepare();
mediaPlayer.start();
Timer t = new Timer();
handler.postDelayed(onEverySecond, 1000);
mediaPlayer.setOnCompletionListener(new OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.seekTo(0);
}
});
boolean isPlaying = mediaPlayer.isPlaying();
if(!isPlaying){
mediaPlayer.pause();
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
isDownloading = false;
}
}
}
}
};
t.start();
}
private Runnable onEverySecond=new Runnable()
{
public void run()
{
if (mediaPlayer.isPlaying())
{
for (int i = index; i < intervals.length; i++)
{
if (i != index && mediaPlayer.getCurrentPosition() > intervals[i])
{
index = i;
handler.dispatchMessage(handler.obtainMessage());
handler.postDelayed(onEverySecond, 1000);
break;
}
}
}
}
};
Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg) {
txtName.setText(arrName.get(index));
textEndName.setText(arrName.get(index+1));
super.handleMessage(msg);
}
};
public void splitArray()
{
strSplit = kggg.split("\n");// string array
intervals = new long[strSplit.length];
Time timer;
for (int j = 0; j < strSplit.length; j++)
{
split = strSplit[j];// string
split1 = split.split("-");// string array
arrName.add(split1[0]);
String timeq = split1[1];
String[] timed = timeq.split(":");
if(timed.length == 3)
{
timer = new Time(Integer.parseInt(timed[0].trim()), Integer.parseInt(timed[1].trim()), Integer.parseInt(timed[2].trim()));
intervals[j] = timer.getTime();
}
else if(timed.length == 2)
{
timer = new Time(0, Integer.parseInt(timed[0].trim()), Integer.parseInt(timed[1].trim()));
intervals[j] = timer.getTime();
}
else if(timed.length == 1)
{
timer = new Time(0, 0, Integer.parseInt(timed[0].trim()));
intervals[j] = timer.getTime();
}
}
for (int j = intervals.length-1; j >= 0 ; j--)
{
intervals[j] = intervals[j] - intervals[0];
}
}
public void btnClick()
{
k++;
k = k % 2;
startSong(k);
}
private void startSong(int i) {
if (i == 1) {
System.out.println("11111" + i);
btnplay.setImageResource(R.drawable.pause);
try {
System.out.println("start try chech------");
mediaPlayer.start();
} catch (Exception e) {
mediaPlayer.pause();
}
}
if (i == 0) {
btnplay.setImageResource(R.drawable.play);
mediaPlayer.pause();
System.out.println("00000" + i);
}
}
You shouldn't be doing this:
handler.dispatchMessage(handler.obtainMessage());
Try this instead:
handler.sendMessage(handler.obtainMessage());
EDIT: Added other things I noticed
I also see that in your Thread you have a loop while (isDownloading) and you set isDownloading to false in the finally block. This loop while never run more than once.
Also, you do
btnplay.setImageResource(R.drawable.play);
inside a thead. This isn't good. You need to do everything related to UI on the main (UI) thread.