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;
}
});
Related
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);
I set custom dingdong bell sound but it ring one time . how to set two or three times ringing sound.
Here java Code,
mMediaPlayer = new MediaPlayer();
mMediaPlayer =
MediaPlayer.create(MyRideDetailTrackRide.this, R.raw.dingdong);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
// mMediaPlayer.setLooping(true);
mMediaPlayer.start();
int howManyTimesPlayed = 0;
mediaPlayer.setOnCompletionListener(new OnCompletionListener(){
int maxRePlayCount = 3; // set this value to replay x time
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
if(howManyTimesPlayed < maxRePlayCount) {
howManyTimesPlayed++;
mediaPlayer.seekTo(0);
mediaPlayer.start();
}
}});
I want Mute Sound of video and use Videoview for playing video
_player.setVideoURI("/sdcard/Movie/byern.mp4");
_player.start();
Now,How can Resolve it?
You can custom VideoView like that
public class VideoPlayer extends VideoView implements OnPreparedListener, OnCompletionListener, OnErrorListener {
private MediaPlayer mediaPlayer;
public Player(Context context, AttributeSet attributes) {
super(context, attributes);
//init player
this.setOnPreparedListener(this);
this.setOnCompletionListener(this);
this.setOnErrorListener(this);
}
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
this.mediaPlayer = mediaPlayer;
}
#Override
public boolean onError(MediaPlayer mediaPlayer, int what, int extra) { }
#Override
public void onCompletion(MediaPlayer mediaPlayer) { ... }
public void mute() {
this.setVolume(0);
}
public void unmute() {
this.setVolume(100);
}
private void setVolume(int amount) {
final int max = 100;//change 100 to zeo
final double numerator = max - amount > 0 ? Math.log(max - amount) : 0;
final float volume = (float) (1 - (numerator / Math.log(max)));
this.mediaPlayer.setVolume(volume, volume);
}
}
You need to call MediaPlayer.OnPreparedListener and MediaPlayer.OnCompletionListener of you want to use VideoView .Then you can make setVolume method public so that volume can be controlled outside of the scope of the class.Below 3 will solve these..
Disabling sound in a video
Mute a playing video by VideoView in Android Application
Muting a video in a VideoView
I'm using a SeekBar to display the progress of an audio file and for seeking to a certain time. For updating I use a Runnable which calls getCurrentPosition() on a MediaPlayer every second or so. Every time that happens there is a small amount of lag in the audio. Since I call it often, I get very noticeable stuttering while playing something. If it's relevant, I'm using setAudioStreamType(AudioManager.STREAM_MUSIC) and the file format is mp4 whith AAC audio (no video) and I'm using Android 2.3.4. Is there a way to get good audio with getCurrentPosition(), or do I have to implement my own progress calculations?
The Runnable:
private Runnable mUpdateTask = new Runnable(){
#Override
public void run() {
mSeekBar.setProgress((int) (mPlayer.getCurrentPosition() * 100 / mArrayAdapter.getRecording(mPlayingId).mDuration));
mHandler.postDelayed(mUpdateTask, 999);
}
};
I had the same problem or something similar.
When I've used mMediapPlayer.getCurrentPosition() in a TimerTask to update the SeekBar, I heard sound problems like echo but actually the problem wasn't there..
The issue is that I've also used SeekBar OnSeekBarChangeListener for manual seek but what happened is that update the seekBar from the TimerTask also triggered the listener, which did mp.seekTo(progress) and this, caused the mp to return back to that position again..
I've fixed it by using the fromUser argument as suggested here to do seek only if the seekBar changed manually.
Here is my sample code:
The TimerTask:
public void initializeTimerTask() {
mTimerTask = new TimerTask() {
public void run() {
int progress = mp.getCurrentPosition()/1000;
runOnUiThread(new Runnable() {
#Override
public void run() {
mSeekBar.setProgress(progress);
tvDuration.setText(DateUtils.formatElapsedTime(progress));
}
});
}
};
}
Listener:
mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(mp != null && fromUser){
mp.seekTo(progress * 1000);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
you can do something like this:
private Runnable mUpdateTask = new Runnable(){
#Override
public void run()
{
mSeekBar.setProgress(mMediapPlayer.getCurrentPosition());
mHandler.postDelayed(mUpdateTask, 999);
}
};
you can also apply seek bar progress change listener as follow:
mSeekBar.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)
{
int secProgress = seekBar.getSecondaryProgress();
if (secProgress> progress)
{
mMediapPlayer.seekTo(progress);
}
else
{
seekBar.setProgress(mSeekBar.getProgress());
}
}
}
});
mMediapPlayer.setOnBufferingUpdateListener(new OnBufferingUpdateListener()
{
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent)
{
mSeekBar.setSecondaryProgress((mSeekBar.getMax()/100)*percent);
}
});
I use this method to caluclate progress'
public static int getProgressPercentage(long currentDuration,
long totalDuration) {
Double percentage = (double) 0;
long currentSeconds = (int) (currentDuration / 1000);
long totalSeconds = (int) (totalDuration / 1000);
// calculating percentage
percentage = (((double) currentSeconds) / totalSeconds) * 100;
// return percentage
return percentage.intValue();
}
Note: mPlayer.getCurrentPosition() is not accurate. There are some bugs reported. I had problem that current position was higher than totalDuration.
When I develop an Android application, I want to adjust to the volume of Music with a seekbar. How can this be done?
In addition, when I adjust the volume of Music, I don't want to display a Toast.
please check this code......
SeekBar ring = null;
AudioManager mgr = null;
mgr = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
ring = (SeekBar) findViewById(R.id.seekBar1);
initBar(ring, AudioManager.STREAM_RING);
please call the function initbar using your seekbar view instance and stream it will set the music volume as you increase or decrease the seekbar...
private void initBar(SeekBar bar, final int stream) {
bar.setMax(mgr.getStreamMaxVolume(stream));
bar.setProgress(mgr.getStreamVolume(stream));
bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar bar, int progress,
boolean fromUser) {
mgr.setStreamVolume(stream, progress,
AudioManager.FLAG_PLAY_SOUND);
}
public void onStartTrackingTouch(SeekBar bar) {
// no-op
}
public void onStopTrackingTouch(SeekBar bar) {
// no-op
}
});
}