How to set Videoview Volume Programmatically? - android

I have 4 Videoview which is created dynamically. I want to set a custom volume for only one video which is coming from the server, the remaining three videos will be mute.
I want to set a custom volume for particular videos I tried below code it's not working
vid1.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
{
public void onPrepared(MediaPlayer mp)
{
//mp.setVolume(100f, 100f);
//mp.setLooping(true);
vid1.enableSound(20,mp); //here i will set music sound dynamically
vid1.start();
playingvideo1 = true;
}
});
//startTimeForContent = dateFormatForContent.format(new Date());
vid1.setOnErrorListener(mOnErrorListener2);
playBackfunction1();
}
public void enableSound(int sound, MediaPlayer mp){
Float f = Float.valueOf(sound);
Log.e("checkingsounds","&&&&& "+f);
mp.setVolume(f,f);
mp.setLooping(true);
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, sound, AudioManager.FLAG_PLAY_SOUND);
}
When I give volume 0 it is working...but when change 10,20,30 video is playing full sound....
I already research below:
sound volume not working on Android
Using SeekBar to Control Volume in android?
How to increase and decrease volume in android

After researching some hours I got a solution
You need to set Volume 0 to 15
vid1.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
{
public void onPrepared(MediaPlayer mp)
{
//mp.setVolume(100f, 100f);
//mp.setLooping(true);
vid1.enableSound(10,mp); //set Volume 0 to 15.
vid1.start();
playingvideo1 = true;
}
});
//startTimeForContent = dateFormatForContent.format(new Date());
vid1.setOnErrorListener(mOnErrorListener2);
playBackfunction1();
}
public void enableSound(int sound, MediaPlayer mp){
Float f = Float.valueOf(sound);
Log.e("checkingsounds","&&&&& "+f);
mp.setVolume(f,f);
mp.setLooping(true);
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC); //Max Volume 15
audioManager.getStreamVolume(AudioManager.STREAM_MUSIC); //this will return current volume.
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, sound, AudioManager.FLAG_PLAY_SOUND); //here you can set custom volume.
}

Related

Android Mediaplayer setVolume not work when I press volume button on moblie

I use MediaPlayer setVolume function to control the audio track volume, that is ok. but when I set Volume 0, then press the volume button, the volume is not 0. Why? please help me.
The volume you are changing is the volume of that mediaplayer instance not the device. To change device volume you need to create the AudioManager Object and use it to change device volume. Example :
AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
Button upButton = (Button) findViewById(R.id.upButton);
upButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//To increase media player volume
audioManager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND);
}
});
Button downButton = (Button) findViewById(R.id.downButton);
downButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//To decrease media player volume
audioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);
}
});
You can look at this complete answer to override volume button from your device.

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.

Android sounds not playing after successive button clicks

I have a math game with multiple choice questions. I have a bell sound for a right answer and an oink sound for a wrong answer. There is a timed play mode which encourages the player to enter answers rapidly. The sounds play fine if answer buttons are pressed slowly. But if in quick succession, a sound fails to play.
The two sounds are each a fraction of a second long.
In the method that handles correct answers I have ting.start();, and in the method for wrong answers I have oink.start();
One thing I tried was to forcibly stop both sounds and then start only the one I want (see below) but then the sounds don't play at all! Any suggestions?
private void handleWrongAnswer(int chosenID)
{
// Toast.makeText(getApplicationContext(), "Oops, try again.", Toast.LENGTH_SHORT).show();
Button checked_button = (Button) findViewById(chosenID);
checked_button.setEnabled(false);
checked_button.setClickable(false);
checked_button.setBackgroundColor(Color.rgb(255,100,100));
score = score - 1.0/3.0;
score_field.setText(String.format("%.2f", score));
ting.stop();
oink.stop();
oink.start();
}
Well I suppose that you are using Mediaplayer to play that sounds. If you want to play small audio clips and repeat them in small place of time you should use soundPool.
You should implement it this way:
private SoundPool soundPool;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Load the sound
soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId,
int status) {
loaded = true;
}
});
soundID = soundPool.load(this, R.raw.sound1, 1);
}
And then when you want to use it:
// Getting the user sound settings
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
float actualVolume = (float) audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = actualVolume / maxVolume;
// Is the sound loaded already?
if (loaded) {
soundPool.play(soundID, volume, volume, 1, 0, 1f);
}
Anyway you have a nice tutorial about this here.

Switching between earpiece and speakerphone on button press

I am trying to play audio from both the speakerphone and earpiece by having a button toggle between the two. The problem is that I am trying to default the audio to play from the earpiece, but nothing comes out. Then when I press the button to toggle to speakerphone, still no audio plays. I am playing from a local raw file.
I have android.permission.MODIFY_AUDIO_SETTINGS in the Manifest as well.
Here is my code:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
context = getActivity().getBaseContext();
am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
am.setMode(AudioManager.MODE_IN_CALL);
am.setSpeakerphoneOn(false);
am.setBluetoothScoOn(true);
speakerON = false;
}
#Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.buttonSpeaker:
if(!speakerON)//speaker off
{
speakerON = true;
am.setMode(AudioManager.MODE_NORMAL);
am.setSpeakerphoneOn(true);
am.setBluetoothScoOn(false);
speaker.setCompoundDrawablesWithIntrinsicBounds(android.R.drawable.ic_lock_silent_mode_off, 0, 0, 0);
}
else
{
speakerON = false;
am.setMode(AudioManager.MODE_IN_CALL);
am.setSpeakerphoneOn(false);
am.setBluetoothScoOn(true);
speaker.setCompoundDrawablesWithIntrinsicBounds(android.R.drawable.ic_lock_silent_mode, 0, 0, 0);
}
break;
}
}
Here is how I am setting up the MediaPlayer:
mediaPlayer = MediaPlayer.create(getActivity().getBaseContext(), R.raw.test_message);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
mediaPlayer.start();
It turns out that I had set the mode wrong.
Here is the updated media player:
mediaPlayer = MediaPlayer.create(getActivity().getBaseContext(), R.raw.test_message);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.start();
And then I set the mode for the audio manager to :
context = getActivity().getBaseContext();
am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
am.setMode(AudioManager.MODE_IN_CALL);
am.setSpeakerphoneOn(false);
And then it worked. So make sure that the media player and audio manager are in the same mode.

Android : setVolume and setAudioStreamType(AudioManager.STREAM_VOICE_CALL);

I am playing an audio file with an internal speaker using this code
audioManager = (AudioManager)Context.getSystemService(Context.AUDIO_SERVICE);
audioManager.setSpeakerphoneOn(false);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
How can I set the volume?
Use adjustStreamVolume() on AudioManager.
Though, preferably, you let the user set the volume the normal way, via the volume control buttons. You can indicate what stream that is to control in your activity via setVolumeControlStream().
am2 is an instance of AudioManager system service.
am2 = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
// makes the media volume adjustment
public static int setVolume(int inputVol, Context sender) {
int outVol;
if (inputVol < 0)
inputVol = 0;
if (inputVol > am2.getStreamMaxVolume(AudioManager.STREAM_MUSIC))
inputVol = am2.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
am2.setStreamVolume(AudioManager.STREAM_MUSIC, inputVol,
AudioManager.FLAG_SHOW_UI);
outVol = am2.getStreamVolume(AudioManager.STREAM_MUSIC);
return outVol;
}

Categories

Resources