How to syncronize system volume with mediaplayer app - android

I've just developed a simple media player that sounds a song and it has a seekbar that regulate the song volume.
That's my code:
public class MainActivity extends AppCompatActivity {
Button playBtn;
SeekBar positionBar;
SeekBar volumeBar;
TextView elapsedTimeLabel;
TextView remainingTimeLabel;
MediaPlayer mp;
int totalTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playBtn = (Button) findViewById(R.id.playBtn);
elapsedTimeLabel = (TextView) findViewById(R.id.elapsedTimeLabel);
remainingTimeLabel = (TextView) findViewById(R.id.remainingTimeLabel);
// Media Player
mp = MediaPlayer.create(this, R.raw.song);
mp.setLooping(true);
mp.seekTo(0);
mp.setVolume(0.5f, 0.5f);
totalTime = mp.getDuration();
// Position Bar
positionBar = (SeekBar) findViewById(R.id.positionBar);
positionBar.setMax(totalTime);
positionBar.setOnSeekBarChangeListener(
new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
mp.seekTo(progress);
positionBar.setProgress(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
);
// Volume Bar
volumeBar = (SeekBar) findViewById(R.id.volumeBar);
volumeBar.setOnSeekBarChangeListener(
new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
float volumeNum = progress / 100f;
mp.setVolume(volumeNum, volumeNum);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
);
// Thread (Update positionBar & timeLabel)
new Thread(new Runnable() {
#Override
public void run() {
while (mp != null) {
try {
Message msg = new Message();
msg.what = mp.getCurrentPosition();
handler.sendMessage(msg);
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
}
}).start();
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
int currentPosition = msg.what;
// Update positionBar.
positionBar.setProgress(currentPosition);
// Update Labels.
String elapsedTime = createTimeLabel(currentPosition);
elapsedTimeLabel.setText(elapsedTime);
String remainingTime = createTimeLabel(totalTime-currentPosition);
remainingTimeLabel.setText("- " + remainingTime);
}
};
public String createTimeLabel(int time) {
String timeLabel = "";
int min = time / 1000 / 60;
int sec = time / 1000 % 60;
timeLabel = min + ":";
if (sec < 10) timeLabel += "0";
timeLabel += sec;
return timeLabel;
}
public void playBtnClick(View view) {
if (!mp.isPlaying()) {
// Stopping
mp.start();
playBtn.setBackgroundResource(R.drawable.ic_stop);
} else {
// Playing
mp.pause();
playBtn.setBackgroundResource(R.drawable.ic_play);
}
} }
Now, when I regulate the volume with the media player seekbar, the phone system volume didn't change and the other way around.
How can I syncronize the volume seekbar with the phone system volume so as to adjust the volume with both?

Using the Audio Manager to Raise and Down Volume.
AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
//Using volume control UI visibility
//To increase media player volume
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
//To decrease media player volume
audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
//Without volume control UI
//To increase media player volume
audioManager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND);
//To decrease media player volume
audioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);

Related

Set volume of a video of a VideoView + SeekBar as control bar

I have to set the volume of a video that is contained in a VideoView. I have to use a SeekBar(I already know how to work with SeekBars, I just would like to know how to set the volume of the video).
I also have to use another SeekBar as controll bar.
This is my code:
positionBar = (SeekBar) this.findViewById(R.id.seekBar2);
volumeBar = (SeekBar) this.findViewById(R.id.seekBar);
//getting the max volume and the current volume to set the volume bar
audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
maxVolume = audioManager.getStreamMaxVolume(AudioManager.USE_DEFAULT_STREAM_TYPE);
currentVolume = audioManager.getStreamVolume(AudioManager.USE_DEFAULT_STREAM_TYPE);
volumeBar.setMax(maxVolume);
volumeBar.setProgress(currentVolume);
//putting the video to execute in the video view
videoPlayer.setVideoPath("android.resource://" + getPackageName() + "/" + R.raw.video);
//volume bar listener
volumeBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
//********************************************************************
//position bar listener
positionBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
//********************************************************************
//timer to update the position bar during the video execution
//and the volume
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
currentVolume = audioManager.getStreamVolume(AudioManager.USE_DEFAULT_STREAM_TYPE);
volumeBar.setProgress(currentVolume);
}
}, 0 , 500);
//********************************************************************
Check Below Code, To set the volume of the video programatically.
SeekBar volumeBar;
int volumeLevel;
AudioManager audioManager;
ImageView volumnBtn;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
.....
.....
volumeBar = (SeekBar) findViewById(R.id.volumeBar);
audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
volumeBar.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumeLevel = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
volumnBtn = (ImageView) findViewById(R.id.volumnBtn);
if (volumeLevel == 0) {
volumnBtn.setImageDrawable(getResources().getDrawable(R.drawable.volumnMute));
} else {
volumnBtn.setImageDrawable(getResources().getDrawable(R.drawable.volumnHigh));
}
iv_volumn_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
volumeLevel = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
volumeBar.setProgress(volumeLevel);
if (volumeBar.getVisibility() == View.GONE) {
volumeBar.setVisibility(View.VISIBLE);
} else {
volumeBar.setVisibility(View.GONE);
}
}
});
volumeBar.setProgress(volumeLevel);
volumeBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
volumeLevel = i;
if (volumeLevel == 0) {
volumnBtn.setImageDrawable(getResources().getDrawable(R.drawable.volumnMute));
} else {
volumnBtn.setImageDrawable(getResources().getDrawable(R.drawable.volumnHigh));
}
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volumeLevel, 0);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
volumeBar.setVisibility(View.GONE);
if (volumeLevel == 0) {
volumnBtn.setImageDrawable(getResources().getDrawable(R.drawable.volumnMute));
} else {
volumnBtn.setImageDrawable(getResources().getDrawable(R.drawable.volumnHigh));
}
}
});
}
use SeekBar.getProgress() to get value of your seekbar,and then use the value to set volume,in onProgressChanged method.

View Holders Data messing up while scrolling in RecyclerView

Hi Community,
I'm developing whats-app like application.In that I am facing a
problem in recycle view while scrolling the items.The problem is even
specific to audio files itself.These files were playing irrelevant to
item data position.Please help me to resolve this issue.
MyAdapterClass:
#Override
public void onBindViewHolder(SwappingHolder holder, int position) {
MessageDetails messageData = messagesList.get(position);
if (messageData != null) {
switch (messageData.getMessageType()) {
case MessageDetails.MESSAGE_TEXT_TYPE:
TextTypeViewHolder textViewHolder = (TextTypeViewHolder) holder;
textViewHolder.updateView(messageData);
break;
case MessageDetails.MESSAGE_IMAGE_TYPE:
ImageTypeViewHolder imageViewHolder = (ImageTypeViewHolder) holder;
imageViewHolder.updateImageFile(messageData);
break;
case MessageDetails.MESSAGE_AUDIO_TYPE:
AudioTypeViewHolder audioHolder = (AudioTypeViewHolder) holder;
audioHolder.initializeAudioPlayer(messageData);
break;
case MessageDetails.MESSAGE_VIDEO_TYPE:
VideoTypeViewHolder videoHolder = (VideoTypeViewHolder) holder;
videoHolder.updateVideoMessage(messageData);
break;
case MessageDetails.MESSAGE_LOCATION_TYPE:
MapTypeHolder mapHolder = (MapTypeHolder) holder;
mapHolder.loadMapThumbView(messageData);
break;
case MessageDetails.MESSAGE_CONTACT_TYPE:
ContactsTypeHolder contactsHolder = (ContactsTypeHolder) holder;
contactsHolder.setContactData(messageData);
break;
case MessageDetails.MESSAGE_FILE_TYPE:
FileTypeHolder fileTypeHolder = (FileTypeHolder)holder;
fileTypeHolder.updateFileData(messageData);
}
}
}
MyHolderClass:
public class AudioTypeViewHolder extends SwappingHolder implements View.OnClickListener, View.OnLongClickListener {
SeekBar seekBar;
TextView timer, tv_time;
ImageView btn_play, iv_smile;
CardView cardView;
RelativeLayout parentView;
CustomizedAudioPlayer player;
MessageDetails messageDetails;
MediaPlayer mediaPlayer;
public AudioTypeViewHolder(View itemView) {
super(itemView, multiSelector);
this.timer = (TextView) itemView.findViewById(R.id.timer);
this.seekBar = (SeekBar) itemView.findViewById(R.id.audio_seekBar);
this.btn_play = (ImageView) itemView.findViewById(R.id.btnPlay);
this.tv_time = (TextView) itemView.findViewById(R.id.timeright);
this.cardView = (CardView) itemView.findViewById(R.id.card_view);
this.parentView = (RelativeLayout) itemView.findViewById(R.id.parent_view);
this.iv_smile =(ImageView) itemView.findViewById(R.id.smile1);
this.mediaPlayer = new MediaPlayer();
btn_play.setOnClickListener(this);
player = new CustomizedAudioPlayer(mediaPlayer, seekBar, btn_play, timer);
itemView.setOnLongClickListener(this);
itemView.setLongClickable(true);
btn_play.setOnLongClickListener(this);
btn_play.setLongClickable(true);
}
void initializeAudioPlayer(MessageDetails messageDetails) {
int colorId, gravity;
this.messageDetails = messageDetails;
if(messageDetails.getAudioPlayer() == null)
messageDetails.setAudioPlayer(player);
if (messageDetails.getSender().equals("to")) {
colorId = mContext.getResources().getColor(R.color.color_recevied_item);
gravity = Gravity.LEFT;
iv_smile.setVisibility(View.GONE);
} else {
colorId = mContext.getResources().getColor(R.color.color_sent_item);
gravity = Gravity.RIGHT;
iv_smile.setVisibility(View.VISIBLE);
iv_smile.setBackgroundResource(updateMessageStatus(messageDetails.getMstatus()));
}
player.initializePlayer(messageDetails.getMessage());
tv_time.setText(messageDetails.getTime());
cardView.setCardBackgroundColor(colorId);
parentView.setGravity(gravity);
}
#Override
public void onClick(View view) {
int id = view.getId();
if (id == R.id.btnPlay) {
if (!mediaPlayer.isPlaying()) {
// check my player is playing
//if not, stop if any other player is playing
for (MessageDetails messageDetails : messagesList) {
CustomizedAudioPlayer customPlayer = messageDetails.getAudioPlayer();
if(customPlayer != null)
customPlayer.stopTheMediaPlay();
}
//start my player
btn_play.setImageResource(R.drawable.img_pause);
player.startThePlayer();
notifyDataSetChanged();
} else {
btn_play.setImageResource(R.drawable.img_play);
player.stopTheMediaPlay();
}
}
}
#Override
public boolean onLongClick(View view) {
onItemLongPressed(this, messageDetails);
return true;
}
}
My Custom Audio Player
public class CustomizedAudioPlayer implements SeekBar.OnSeekBarChangeListener,MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener {
private Handler myHandler = new Handler();
SeekBar seekbar;
MediaPlayer mediaPlayer;
boolean isPaused;
ImageView playBtn;
TextView timer;
StringBuilder mFormatBuilder;
Formatter mFormatter;
int totalDuration, currentDuration;
String path, chatId;
public CustomizedAudioPlayer(MediaPlayer mediaPlayer, SeekBar seekbar, ImageView view, TextView timer){
this.seekbar = seekbar;
this.playBtn = view;
this.timer = timer;
this.mediaPlayer = mediaPlayer;
mFormatBuilder = new StringBuilder();
mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
this.seekbar.setProgress(0);
this.seekbar.setMax(100);
this.seekbar.setOnSeekBarChangeListener(this);
}
public void initializePlayer(String filePath){
try{
if(path == null){
this.path = filePath;
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setDataSource(path);
mediaPlayer.prepare();
timer.setText(stringForTime( mediaPlayer.getDuration()));
}
}catch (Exception e){
}
}
public void startThePlayer(){
totalDuration = mediaPlayer.getDuration();
mediaPlayer.seekTo(currentDuration);
myHandler.postDelayed(updateProgress,100);
mediaPlayer.start();
}
public void stopTheMediaPlay(){
if(mediaPlayer.isPlaying()){
playBtn.setImageResource(R.drawable.img_play);
currentDuration = mediaPlayer.getCurrentPosition();
timer.setText(stringForTime( mediaPlayer.getDuration()));
myHandler.removeCallbacks(updateProgress);
mediaPlayer.pause();
}
}
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
playBtn.setImageResource(R.drawable.img_play);
seekbar.setProgress(0);
timer.setText(stringForTime( mediaPlayer.getDuration()));
myHandler.removeCallbacks(updateProgress);
}
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
myHandler.removeCallbacks(updateProgress);
playBtn.setImageResource(R.drawable.img_play);
mediaPlayer.pause();
isPaused = true;
}
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
currentDuration = progressToTimer(seekBar.getProgress(), totalDuration);
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
if(fromUser){
mediaPlayer.seekTo(currentDuration);
}
} else if (mediaPlayer == null) {
seekBar.setProgress(0);
}
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
currentDuration = progressToTimer(seekBar.getProgress(), totalDuration);
if (mediaPlayer.isPlaying() && mediaPlayer != null || (isPaused && mediaPlayer != null)) {
isPaused = false;
mediaPlayer.seekTo(currentDuration);
myHandler.postDelayed(updateProgress,100);
mediaPlayer.start();
playBtn.setImageResource(R.drawable.img_pause);
}
}
#Override
public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
return false;
}
private Runnable updateProgress = new Runnable() {
public void run() {
totalDuration = mediaPlayer.getDuration();
currentDuration = mediaPlayer.getCurrentPosition();
int progress = getProgressPercentage();
float progressPer = ((float)progress/100);
float newPosition = (totalDuration) * progressPer;
seekbar.setProgress(progress);
timer.setText(stringForTime( (int) newPosition));
myHandler.postDelayed(this, 100);
}
};
private String stringForTime(int timeMs) {
int totalSeconds = timeMs / 1000;
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
mFormatBuilder.setLength(0);
if (hours > 0) {
return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
} else {
return mFormatter.format("%02d:%02d", minutes, seconds).toString();
}
}
public int getProgressPercentage(){
long currentSeconds = (currentDuration / 1000);
long totalSeconds = (totalDuration / 1000);
Double percentage =(((double)currentSeconds)/totalSeconds)*100;
return percentage.intValue();
}
public int progressToTimer(int progress, int totalDuration) {
totalDuration = (totalDuration / 1000);
int currentDuration = (int) ((((double)progress) / 100) * totalDuration);
// return current duration in milliseconds
return currentDuration * 1000;
}
}
I even tried by placing
setIsRecyclable(false);
Using this, the positions of items are stable, but the item not updating while playing audio file(i.e. seekbar, file time not updating)
You can closely find my problem in following screenshot

How to adjust the volume of two media players simultaneously?

I am running two media players simultaneously to play two different sounds, one is audio recording and second one is music. I am controlling the volume of both through two seekbars. The problem is, volume of one media player is controlled at once. When one media player is released, volume of other media player can be adjusted. I want to adjust SIMULTANEOUSLY
Here's my implementation.
public void setMediaPLayers() {
mediaPlayer = new MediaPlayer(); //TO PLAY VOICE RECORDING
mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
try {
mediaPlayer.setDataSource(AudioSavePathInDevice); //VOICE RECORDING FILE PATH
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer2 = MediaPlayer.create(getActivity(), R.raw.sunnysideup); //FOR MUSIC FILE
mediaPlayer2.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer2.start();
}
In seekbars, i am using audio manager to adjust volumes. In music seekbar, volume is adjusted through,
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i, 0); // i = seekbar progress
Code for changing the volume of recording seekbar is,
audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, i, 0); // i = seekbar progress
Here's the solution to play 2 media players simultaneously and control their volume through seekbars.
Create Variables
MediaPlayer mpOne = null;
MediaPlayer mpTwo = null;
SeekBar seekBarOne, seekBarTwo;
//Path to mp3 file stored in device
String FILE_PATH_ONE = Environment.getExternalStorageDirectory().getPath() + "/music_one.mp3";
String FILE_PATH_TWO = Environment.getExternalStorageDirectory().getPath() + "/music_two.mp3";
Function to intialize and start media players:
public void setMediaPlayers() {
mpOne = new MediaPlayer();
mpTwo = new MediaPlayer();
try {
mpOne.setDataSource(FILE_PATH_ONE);
mpTwo.setDataSource(FILE_PATH_TWO);
mpOne.prepare();
mpTwo.prepare();
mpOne.start();
mpTwo.start();
} catch (IOException e) {
e.printStackTrace();
}
}
Create SeekBarChangeListener to get the current progress.
SeekBar.OnSeekBarChangeListener seekBarOneListener = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
//Lets assume, seekbar's maximum progress is 10.
//i is the progress of seekbar between 0 to 10.
float volume = i * 0.10f;
//Set the volume if media player is not null
if (null != mpOne)
//volume is the float number between 0.0 and 1.0
mpOne.setVolume(volume, volume);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
};
SeekBar.OnSeekBarChangeListener seekBarTwoListener = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
//Lets assume, seekbar's maximum progress is 10.
//i is the progress of seekbar between 0 to 10.
float volume = i * 0.10f;
//Set the volume if media player is not null
if (null != mpTwo)
//volume is the float number between 0.0 and 1.0
mpTwo.setVolume(volume, volume);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
};
In activity or fragment
seekBarOne = (SeekBar) v.findViewById(R.id.seekBar1);
seekBarTwo = (SeekBar) v.findViewById(R.id.seekBar2);
seekBarOne.setOnSeekBarChangeListener(seekBarOneListener);
seekBarTwo.setOnSeekBarChangeListener(seekBarTwoListener);
//Start media players
setMediaPlayers();
//Completion listeners for releasing media players on completion.
mpOne.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mpOne.reset();
mpOne.release();
mpOne = null;
}
});
mpTwo.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mpTwo.reset();
mpTwo.release();
mpTwo = null;
}
});

Android Media Player with seekbar always update and reset

everybody.
First of all, I'm a newbie. I created an activity to play a specific mp3 from raw folder. It works fine and playing it well. I implemented the Media Player as you will see in my code below. But the problem is when I change the orientation of my smartphone , the player continues playing the sound, but a new activity is opened/ updated with the same elements reseted and if I click on PLAY button, the mp3 starts playing, but the old activity stills running on back, playing the mp3.... so, there are 2 same songs playing now...
I don't want to update the activity or open a new one. I just want to continue playing the song where it was playing before I change the smartphone orientation.
Here is my code:
MP3PlayerActivity.java (main)
public class Mp3PlayerActivity extends Activity implements OnPreparedListener {
/** Called when the activity is first created. */
private Button btnPlay;
private Button btnPause;
private int current = 0;
private boolean running = true;
private int duration = 0;
private MediaPlayer mPlayer;
private SeekBar mSeekBarPlayer;
private TextView mMediaTime;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
mPlayer = MediaPlayer.create(getApplicationContext(), R.raw.goodthings);
btnPlay = (Button) findViewById(R.id.button1);
btnPause = (Button) findViewById(R.id.button2);
mMediaTime = (TextView)findViewById(R.id.mediaTime);
mSeekBarPlayer = (SeekBar)findViewById(R.id.progress_bar);
mPlayer.setOnPreparedListener(this);
mSeekBarPlayer.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) {
if(fromUser){
mPlayer.seekTo(progress);
updateTime();
}
}
});
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mPlayer.start();
mSeekBarPlayer.postDelayed(onEverySecond, 1000);
}
public void onCompletion( MediaPlayer mPlayer)
{
mPlayer.release();
}
});
btnPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mPlayer.pause();
}
public void onCompletion( MediaPlayer mPlayer)
{
mPlayer.release();
}
});
}
private Runnable onEverySecond = new Runnable() {
#Override
public void run(){
if(true == running){
if(mSeekBarPlayer != null) {
mSeekBarPlayer.setProgress(mPlayer.getCurrentPosition());
}
if(mPlayer.isPlaying()) {
mSeekBarPlayer.postDelayed(onEverySecond, 1000);
updateTime();
}
}
}
};
private void updateTime(){
do {
current = mPlayer.getCurrentPosition();
System.out.println("duration - " + duration + " current- "
+ current);
int dSeconds = (int) (duration / 1000) % 60 ;
int dMinutes = (int) ((duration / (1000*60)) % 60);
int dHours = (int) ((duration / (1000*60*60)) % 24);
int cSeconds = (int) (current / 1000) % 60 ;
int cMinutes = (int) ((current / (1000*60)) % 60);
int cHours = (int) ((current / (1000*60*60)) % 24);
if(dHours == 0){
mMediaTime.setText(String.format("%02d:%02d / %02d:%02d", cMinutes, cSeconds, dMinutes, dSeconds));
}else{
mMediaTime.setText(String.format("%02d:%02d:%02d / %02d:%02d:%02d", cHours, cMinutes, cSeconds, dHours, dMinutes, dSeconds));
}
try{
Log.d("Value: ", String.valueOf((int) (current * 100 / duration)));
if(mSeekBarPlayer.getProgress() >= 100){
break;
}
}catch (Exception e) {}
}while (mSeekBarPlayer.getProgress() <= 100);
}
#Override
public void onPrepared(MediaPlayer arg0) {
// TODO Auto-generated method stub
duration = mPlayer.getDuration();
mSeekBarPlayer.setMax(duration);
mSeekBarPlayer.postDelayed(onEverySecond, 1000);
}
}
when you rotate your device, onCreate() is called again, so all the stuff you do in onCreate() is done all over again - which means recreating your MediaPlayer and re-setting all of the variables.
What you need to do is only create those things if this is the first time onCreate() is being called.
Have a look here for more info on that.:
http://developer.android.com/guide/topics/resources/runtime-changes.html

Android MediaPlayer Audio SeekBar

This sort of question seems to have come up a here a lot, but they are all a slightly different case to mine and have just confused me. I am trying to get my SeekBar to synchronise with a single and specified mp3. With the code below, the audio plays and if you move the SeekBar the audio DOES seek, however the SeekBar does not move on its own to update with the music. Could someone please see if they can find the problem that is stopping the SeekBar from updating?
FIXED NOW but don't know why it fixed.
This is my FIXED Java code. Changes in bold:
MediaPlayer mediaPlayer;
Button buttonPlayPause;
ImageView Image;
SeekBar seekBar;
Handler handler;
private int stateMediaPlayer;
private final int stateMP_NotStarter = 0;
private final int stateMP_Playing = 1;
private final int stateMP_Pausing = 2;
private int mediaPos;
private int mediaMax;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playerwere);
Image = (ImageView) findViewById(R.id.pdfview);
Image.setImageResource(R.drawable.wereim);
seekBar = (SeekBar) findViewById(R.id.seekBar);
buttonPlayPause = (Button) findViewById(R.id.playpause);
buttonPlayPause.setOnClickListener(buttonPlayPauseOnClickListener);
seekBar.setOnSeekBarChangeListener(seekBarOnSeekChangeListener);
initMediaPlayer();
mediaPos = mediaPlayer.getCurrentPosition();
mediaMax = mediaPlayer.getDuration();
seekBar.setMax(mediaMax); // Set the Maximum range of the
// seekBar.setProgress(mediaPos);// set
// current progress to song's
seekBar.setProgress(mediaPos);// set current progress to song's
handler.removeCallbacks(moveSeekBarThread);
handler.postDelayed(moveSeekBarThread, 100);
}
private Runnable moveSeekBarThread = new Runnable() {
public void run() {
if (mediaPlayer.isPlaying()) {
int mediaPos_new = mediaPlayer.getCurrentPosition();
int mediaMax_new = mediaPlayer.getDuration();
seekBar.setMax(mediaMax_new);
seekBar.setProgress(mediaPos_new);
handler.postDelayed(this, 100); // Looping the thread after 0.1
// seconds
} **else {
int mediaPos_new = mediaPlayer.getCurrentPosition();
int mediaMax_new = mediaPlayer.getDuration();
seekBar.setMax(mediaMax_new);
seekBar.setProgress(mediaPos_new);
handler.postDelayed(this, 100); // Looping the thread after 0.1
// seconds
}**
}
};
private void initMediaPlayer() {
handler = new Handler();
mediaPlayer = new MediaPlayer();
mediaPlayer = MediaPlayer.create(were.this, R.raw.were);
stateMediaPlayer = stateMP_NotStarter;
}
Button.OnClickListener buttonPlayPauseOnClickListener = new Button.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (stateMediaPlayer) {
case stateMP_NotStarter:
mediaPlayer.start();
buttonPlayPause
.setBackgroundResource(android.R.drawable.ic_media_pause);
stateMediaPlayer = stateMP_Playing;
break;
case stateMP_Playing:
mediaPlayer.pause();
buttonPlayPause
.setBackgroundResource(android.R.drawable.ic_media_play);
stateMediaPlayer = stateMP_Pausing;
break;
case stateMP_Pausing:
mediaPlayer.start();
buttonPlayPause
.setBackgroundResource(android.R.drawable.ic_media_pause);
stateMediaPlayer = stateMP_Playing;
break;
}
}
};
SeekBar.OnSeekBarChangeListener seekBarOnSeekChangeListener = 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) {
mediaPlayer.seekTo(progress);
seekBar.setProgress(progress);
}
}
};
}

Categories

Resources