I have recorded audio, and play it through the mediaplayer. Recording, playing works fine. I used a seekbar, while playing the recorded voice. I used the following coding to play the content stored in sdcard. It works fine.. mFileName is the audio file in sdcard.
The seek bar doesnt move, while playing. Any suggestions...
private void startPlaying()
{
MediaPlayer mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
mSeekBar.setMax(mPlayer.getDuration());
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
And I used
mSeekBar.setOnSeekBarChangeListener(new SeekBar.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){
mPlayer.seekTo(progress);
mSeekBar.setProgress(progress);
}
}
});
Thread currentThread = new Thread((Runnable) this);
currentThread.start();
public void run() {
// TODO Auto-generated method stub
try {
while(mPlayer != null){
int currentPosition = mPlayer.getCurrentPosition();
Message msg = new Message();
msg.what = currentPosition;
threadHandler.sendMessage(msg);
}
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Handler threadHandler = new Handler(){
public void handleMessage(Message msg){
mSeekBar.setProgress(msg.what);
}
};
The progressbar moves only when the user moves. It doent move atomatically.
The seekbar isn't going to magically update itself to show the MediaPlayer's current position. Here's a link that shows how to do this with a polling thread that checks the MediaPlayer's position every second or so and updates the seekbar accordingly:
http://united-coders.com/nico-heid/an-android-seekbar-for-your-mediaplayer
Related
how to stream a online radio without any buffering after the player is played. It should buffered for few sec for continue playing the radio,but it get stuck for few sec and playing.
my Aync task:
class Player extends AsyncTask {
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();
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();
}
}
public void mute1(View v){
speaker.setVisibility(View.VISIBLE);
mute.setVisibility(View.INVISIBLE);
mediaPlayer.setVolume(0,0);
media.setVolume(0,0);
seekbar.setClickable(false);
seekbar.setFocusable(false);
seekbar.setEnabled(false);
}
public void speaker1(View v){
speaker.setVisibility(View.INVISIBLE);
mute.setVisibility(View.VISIBLE);
mediaPlayer.setVolume(1,1);
media.setVolume(1,1);
seekbar.setClickable(true);
seekbar.setFocusable(true);
seekbar.setEnabled(true);
}
how to get my player prepare for the online radio without any streaming after player is started.
Please Help me..
my source is:
if (playPause) {
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 = false;
} else {
control.setBackgroundResource(R.drawable.pause);
if (intialStage) {
new Player()
.execute("http://streaming.shoutcast.com/MUKILFMRADIO");
} else {
if (!mediaPlayer.isPlaying())
mediaPlayer.start();
}
}
playPause = true;
}
};
I would suggest to use Exoplayer than media player.ExoPlayer is an application level media player for Android. It provides an alternative to Android’s MediaPlayer API for playing audio and video both locally and over the Internet. ExoPlayer supports features not currently supported by Android’s MediaPlayer API, including DASH and SmoothStreaming adaptive playbacks. Unlike the MediaPlayer API, ExoPlayer is easy to customize and extend, and can be updated through Play Store application updates. This links give you better idea about Exoplayer.
https://developer.android.com/guide/topics/media/exoplayer.html
https://github.com/google/ExoPlayer
In android, I have a mediaplayer on detail screen, which duplicates when I select another screen then play another detail, causing sound files to play on the same time. how do I fix this problem? Id like to play the most recent selected media only.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feeddetail);
tc_recDurat = (TextView)findViewById(R.id.recDetDurat);
tc_recDuratBack = (TextView)findViewById(R.id.recDetDuratBack);
TextView tc_recPath = (TextView)findViewById(R.id.recDetPath);
recPath = (String) intent.getSerializableExtra("INTENT_PATH");
tc_recPath.setText(recPath);
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(recPath);
} catch (IOException e1) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), e1.getLocalizedMessage(), Toast.LENGTH_LONG);
}
ImageButton mClickButton1 = (ImageButton)findViewById(R.id.btnPlay);
mClickButton1.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mediaPlayer !=null){
try {
mediaPlayer
mediaPlayer.prepare();
seekBar.setMax(mediaPlayer.getDuration());
mediaPlayer.start();
seekUpdate();
isPlaying = true;
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
ImageButton mClickButton2 = (ImageButton)findViewById(R.id.btnStop);
mClickButton2.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mediaPlayer.stop();
isPlaying = false;
}
});
I am not sure what your problem is, but i believe you are trying to say that as you change through different activities, the sounds files do not stop playing
In that case you can do the following
In the activity
You can override the onPause method and put mediaPlayer.stop() inside it
#Override
public void onPause() {
super.onPause();
mediaPlayer.stop();
}
In my application I am trying to implement SeekBar.. The SeekBar is working fine when playing the sound at first time. but When I click the button to play the sound again then I am an endless loop of errors regarding the MediaPlayer. The thing that I want is that when I while playing the sound if I click the the play button the sound should play again from the beginning and the SeekBar should also start from beginning. If I remove the the SeekBar then everything is working fine.. But SeekBar is must in my application.. I have implemented all these things in the BaseAdapter.. I have to do all the things in the BaseAdapter. So please help me in letting me the code that works with the BaseAdapter..
This is my code... Please have a look...
mediaPlayer.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(activity, "Loading Message", Toast.LENGTH_LONG).show();
mp.reset();
try {
mp.setDataSource("url for any mp3 audio file");
} 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();
}
mp.prepareAsync();
mp.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(final MediaPlayer mp) {
// TODO Auto-generated method stub
mp.start();
mediaPlayer.setBackgroundResource(R.drawable.m_pause);
seekBar.setProgress(0);
seekBar.setMax(100);
mUpdateTimeTask = new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();
int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
seekBar.setProgress(progress);
mHandler.post(this);
}
});
mUpdateTimeTask.start();
}
});
}
});
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mediaPlayer.setBackgroundResource(R.drawable.m_play);
mp.stop();
try {
mUpdateTimeTask.join();
mHandler.sendEmptyMessage(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mHandler.removeCallbacks(mUpdateTimeTask);
}
});
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onStopTrackingTouch(final SeekBar seekBar) {
// TODO Auto-generated method stub
//mHandler.removeCallbacks(mUpdateTimeTask);
if(mp.isPlaying())
{
int totalDuration = mp.getDuration();
int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);
mp.seekTo(currentPosition);
mUpdateTimeTask = new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();
int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
//timer.setText(""+utils.milliSecondsToTimer(currentDuration));
seekBar.setProgress(progress);
mHandler.post(this);
}
});
mUpdateTimeTask.start();
}
else
{
seekBar.setProgress(0);
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
if(mp.isPlaying())
{
mHandler.removeCallbacks(mUpdateTimeTask);
}
else
{
seekBar.setProgress(0);
}
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
}
});
mp.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
return false;
}
});
Thanks...
Create a method in your BaseAdapter which sets the current seekbarprogress to zero
void setSeekBarValuetoZero(){
seekBar.setProgress(0);
}
Please check the initially that seekbar is initialized.
You can call this function from yourMediaPlayer class before mp.reset();
Just start streaming audio...starts playing, buffer goes ahead, but suddenly stops. When song catches up to the buffer, music stops. Pressing next goes to the nest songs but same thing happens. any idea?
private void startPlay(String file, String name)
{
Log.i("Selected: ", file);
tv_selelctedFile.setText(name);
//progressControlSeekbar.setProgress(0);
int maxVolume = mediaPlayer.getDuration();
int curVolume = mediaPlayer.getCurrentPosition();
progressControlSeekbar.setMax(maxVolume);
progressControlSeekbar.setProgress(curVolume);
progressControlSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar)
{
isMoveingSeekBar = false;
}
public void onStartTrackingTouch(SeekBar seekBar)
{
isMoveingSeekBar = true;
}
public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser)
{
if(isMoveingSeekBar)
{
mediaPlayer.seekTo(progress);
Log.i("OnSeekBarChangeListener","onProgressChanged");
}
}
});
mediaPlayer.stop();
mediaPlayer.reset();
try {
mediaPlayer.setDataSource(file);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
progressControlSeekbar.setMax(mediaPlayer.getDuration());
playButton.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
isStarted = true;
}
What you can try doing is
use the listeners instead of directly calling
mediaPlayer.prepare();//use preapareAsync()
mediaPlayer.start(); // dont call it here.
call the OnPreparedListener() of the mediaplayer and in onPrepared() use the mediaplayer.start()
if that doesn't help , just implement all the listeners for Media player, like onComplete onError() and check which one is called when suddenly media player stops playing
Hope it helps.
I am playing a song from the sdcard.
Its plays fine. I tried to implement the seekbar such that when the user moves the seekbar the song gets forwarded or rewnided as per the seek bar position.
Here is the code
public class ViewAudio extends Activity implements OnSeekBarChangeListener,OnSeekCompleteListener,OnCompletionListener,OnPreparedListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.audio_player);
System.gc();
Intent i = getIntent();
Bundle extras = i.getExtras();
filename = extras.getString("audiofilename");
try {
mPlayer.setDataSource(filename);
} 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();
}
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mPlayer.setOnCompletionListener(this);
mPlayer.setOnPreparedListener(this);
mPlayer.setOnSeekCompleteListener((OnSeekCompleteListener) this);
mPlayer.start();
TextView tv=(TextView) findViewById(R.id.file);
tv.setText("Playing "+filename);
seekbar = (SeekBar)findViewById(R.id.seekBar1);
mPlay = (Button)findViewById(R.id.play);
mPause = (Button)findViewById(R.id.pause);
seekbar.setProgress(0);
seekbar.setOnSeekBarChangeListener(this);
total = mPlayer.getDuration();
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
Log.d("Progres changed",""+progress);
if(fromUser){
mPlayer.seekTo(progress);
seekbar.setProgress(progress);
}
}
}
Now where ever i click the seekbar the song is getting played from the beginning not from the position i clicked. And it is not moving based on the song.
Any one please help.
i have solved it.
Create a thread that will check the song position every second and move the seekbar based on the song position
mediaPos = mplayer.getCurrentPosition();
mediaMax = mplayer.getDuration();
seekbar.setMax(mediaMax); // Set the Maximum range of the
seekbar.setProgress(mediaPos);// set current progress to song's
handler.removeCallbacks(moveSeekBarThread);
handler.postDelayed(moveSeekBarThread, 100); //cal the thread after 100 milliseconds
}
/**
* The Move seek bar. Thread to move seekbar based on the current position
* of the song
*/
private Runnable moveSeekBarThread = new Runnable() {
public void run() {
if(mplayer.isPlaying()){
int mediaPos_new = mPlayer.getCurrentPosition();
int mediaMax_new = mPlayer.getDuration();
seekbar.setMax(mediaMax_new);
seekbar.setProgress(mediaPos_new);
handler.postDelayed(this, 100); //Looping the thread after 0.1 second
}
}
};