problem in volume management in media player in android code - android

I am working in an android tab which has tabs activities, I have made tab groups for every tabs, in one activity i have media player for playing audio song. everything is fine except
i cann't control the volume of media player and I am not seeing volume control dialog of android device. here is my code,
mp=new MediaPlayer();
mp.setWakeMode(getParent(), PowerManager.PARTIAL_WAKE_LOCK); //for powermanagement
try {
if(GlobalConfig.notInternet==true)
{
mp.setDataSource("/sdcard/abc/"+file);
}else{
mp.setDataSource(url2);
}
mp.prepare();
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
mp.start();
please help me. thanks in advance

The following code should be used to managing media sound...
AudioManager mAudioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
//It gives max volume of ur device
int max_volume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
//It gives current volume of device
int current_volume=mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
//Here you can set volume
int progress=your set value;
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,progress, 0);

Related

FFmpegMediaPlayer Stops When Network is Turned Off and Back On

I am currently working with FFmpegMediaPlayer in order to make a basic music player given a url. I got the basic functionality to work. On error, I show an error message, else I play the songs.
The problem I am facing is, once the player starts, and I turn off my wifi and phone data, it stops the sound. Once I turn my wifi or phone data back one, I would like the player to continue but it simply stops. I have to stop and play again for it to continue.
Is there a way to have the FFmpegMediaPlayer continue streaming?
This is what I have to initialize the player:
mMediaPlayer = new FFmpegMediaPlayer();
mMediaPlayer.setOnErrorListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnSeekCompleteListener(this);
try {
Uri uri = Uri.parse(radio_url);
mMediaPlayer.setDataSource(mMainActivity, uri);
mMediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Then I have a function to handle when Play/Stop button is clicked:
#Override
public void onPlayButtonClicked(Button button) {
if (radioInitialized) {
mAnalytics.onStopButtonClicked();
mMainLayout.loading(false);
mMediaPlayer.pause();
button.setBackground(mMainActivity.getResources().getDrawable(R.drawable.play_button));
radioInitialized = false;
} else {
mAnalytics.onPlayButtonClicked();
mMainLayout.loading(true);
initRadio();
button.setBackground(mMainActivity.getResources().getDrawable(R.drawable.stop_button));
radioInitialized = true;
}
}
Again, the basic functionality works, but I would like for it to continue streaming after wifi is turned back on.
Found a solution.
My main goal was to create a media player like a radio.
I tried MediaPlayer and it works but it tends to stop frequently.
I then tried vitamio and FFmpegMediaPlayer. Vitamio was confusing and FFmpegMediaPlayer doesn't support on streaming error.
I currently got it working with Google's Exo Player. There is a very nice tutorial here: https://codelabs.developers.google.com/codelabs/exoplayer-intro/index.html?index=..%2F..%2Findex#0

Raise volume progressively in Android app

I've got an app where Ii want to sound the alarm ringtone and raise the volume each second.
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
player = MediaPlayer.create(getApplicationContext(), RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM));
After initializing AudioManager and MediaPlayer, I've got a method which is executed each second when some circumstances occur. The method is the next one:
private void sound() {
if (!player.isPlaying()) {
try {
player.setLooping(true);
player.setVolume(5,5);
} catch (Exception e) {
e.printStackTrace();
}
player.start();
} else {
audioManager.adjustStreamVolume(AudioManager.STREAM_NOTIFICATION,AudioManager.ADJUST_RAISE,0);
}
}
As you can see, the first time the method is executed the sound begins, that works OK. But when is already started and I want to raise the volume, the adjustStreamVolume makes nothing.
Any help or advice?

Playing sound through STREAM_ALARM doesn't start from beginning in Marshmallow

I'm playing a sound through STREAM_ALARM:
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(context, notificationSoundUri);
mp.setAudioStreamType(AudioManager.STREAM_ALARM);
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mp.prepare();
It worked ok until I tried on Android 6. On Android 6 sound doesn't play from beginning, so if I play short sounds, no sound is heard. I tried using seekTo(0) and initializing MediaPlayer in other ways.
It only happens in Android 6 when using STREAM_ALARM (other streams work well).
Any help?
EDIT: I realized that sound actually starts playing from start, but at very low volume, and after about 2 seconds volume increases... do you know how to deactivate this behavior?
It sounds like an equalization problem (maybe this audio stream comes with an audioSessionId which is already handled by the system equalizer?)
I will try the following trick before the MediaPlayer initialization:
1) Change the STREAM_ALARM volume
AudioManager mAudioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
int maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, maxVolume, 0 /*flags*/);
2) Set volume after prepare()
//...
mp.prepare();
mp.setVolume(1.0f, 1.0f);
3) Change the audioSessionId
//...
mp.setAudioStreamType(AudioManager.STREAM_ALARM);
mp.setAudioSessionId(CUSTOM_ID); //manually assign an ID here
//...
UPDATE
4) Try to use the SoundPool API instead of MediaPlayer and see if the problem persists (I also suspect that this is a device-dependent issue).
5) Try to call start() ==> pause() ==> start() on MediaPlayer
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
mp.pause();
mp.start();
}
6) Try to trick the initial "low volume" period using the following logic:
before play, set volume to 0
play
after 2 seconds of playback, seek to position 0 (this may consume the silent period)
set the volume to max
play again
In this way, you may be able to do a normal playback, with an initial delay of few seconds.
Let us know your progress, I'll update this answer accordingly with more information and suggestions.

Is it possible to reduce the period between audio tracks being played with MediaPlayer?

I have a number of audio tracks that I need to play in sequence. I'm using MediaPlayer's OnCompletionListener as follows:
public void OnCompletion(MediaPlayer mp)
{
_completed++;
mp.Reset();
if (_completed < _tracks.Length)
{
try
{
AssetFileDescriptor afd = _context.Resources.OpenRawResourceFd(_tracks[_completed]);
if (afd != null)
{
mp.SetDataSource(afd.FileDescriptor, afd.StartOffset, afd.Length);
afd.Close();
mp.Prepare();
mp.Start();
}
}
catch (Exception ex)
{
throw;
}
}
}
This works, but there is a noticeable delay between tracks. I'd like to reduce that period to as close to zero as possible. Is this possible?
MediaPlayer "chaining" was added with API level 16 (Jellybean). The method you'd be interested in is setNextMediaPlayer(MediaPlayer next):
Set the MediaPlayer to start when this MediaPlayer finishes playback (i.e. reaches the end of the stream). The media framework will attempt to transition from this player to the next as seamlessly as possible. The next player can be set at any time before completion. The next player must be prepared by the app, and the application should not call start() on it.
Not with the standard android player though there were many requests to add gapless playback - https://code.google.com/p/android/issues/detail?id=3461
You can try to create and prepare a second instance of MediaPlayer and switch them quickly in the OnCompletion callback.

Sounds stopping too soon in MediaPlayer :: Android

Ok well I have been fighting with this for a while now and have soundboard apps that I havn't ran into this problem in. I am developing a widget that allows for a sound to be played when a button is pressed on the widget.
I am assuming I am just not using the setOnPreparedListener properly but basically what is happening is that some of my sounds play correctly and more likely than not the sounds will cut off the last part noticeable by word or sound effect missing. Below is my code please let me know if you have any idea what's wrong with the code or post a working revision.
Thanx in advance.
public int onStartCommand(Intent intent, int flags, int startId) {
/** Get our place holder for quotes & sounds. */
int s = UpdateService.getQuoteNumber();
/** Check if a sound is playing if so... stop and reset it. */
if (mp != null && mp.isPlaying()){mp.stop();mp.reset();}
/** Create a new mediaplayer and set looping. */
mp = MediaPlayer.create(this, SoundsClicked.randomSound[s]);
mp.setLooping(false);
/** Try to prepare the sound/mediaplayer, if not report error & type. */
try {mp.prepare();}
catch (IllegalStateException e) {e.printStackTrace();Log.e(Integer.toString(s), "IllegalStateException");}
catch (IOException e) {e.printStackTrace();Log.e(Integer.toString(s), "IOException");}
/** Check if the sound is prepared, if so play it. */
mp.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mp.start();
while (mp.isPlaying()) {};
}
});
return flags;}
This is called from a service (obviously from the onStartCommand) but figured I would throw that out there for those not familiar with some of the methods.
If you're using Android 2.2, there are apparently some problems with the MediaPlayer cutting off the last X% of at least some audio files. I'm running in to that problem with the app I'm currently working on. I haven't found if there is a solution or not.

Categories

Resources