Android switching between normal speaker and ear speaker - android

I'm trying to play an audio file through the default speaker or through the little speaker (used during calls).
Now i'm trying to choose between these 2 options using the proximity sensor.
Here's my code:
am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
am.setMode(AudioManager.STREAM_MUSIC);
m=MediaPlayer.create(getApplicationContext(), R.raw.a_meno_che_non);
m.setAudioStreamType(AudioManager.STREAM_MUSIC);
am.setSpeakerphoneOn(true);
SensorEventListener proximitySensorEventListener = new SensorEventListener(){
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType()==Sensor.TYPE_PROXIMITY){
if((int)(event.values[0])==myProximitySensor.getMaximumRange()){
am.setSpeakerphoneOn(true);
}
else {
am.setSpeakerphoneOn(false);
}
}
}
};
this works, but not very well because when switching between the speakers it loses a part of audio (about 2 seconds).
How can I solve this?

Related

Android: Need app's Audio Volume Seekbar to change totally independed of the device volume

I need my in-app volume seekbar to change the volume of the audio in my app only. I need it to be totally separate from the main volume of the device. Everything I find changes the device volume when I change the slider in my app.
I want users to have the option of playing audio in my app at a low volume, but maybe still have their device turned up so phone calls and alarms and such could still be at their normal high volume.
How can I make a seekbar in my app only control audio in my app and not bother other device volumes? Here is the code I am using:
Called in onCreate method:
VolumeControls();
Outside of that:
private void VolumeControls() {
final TextView txtView = (TextView)findViewById(R.id.textView1);
SeekBar seekBar = (SeekBar)findViewById(R.id.sbVolume);
final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
seekBar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
seekBar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
txtView.setText(String.valueOf(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC)));
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar arg0){
}
public void onStartTrackingTouch(SeekBar arg0){
}
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2)
{
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
progress, 0);
txtView.setText(String.valueOf(progress));
}
});
}

Android mute/umute not working properly on asus device

I am using AudioManager to mute unmute on Asus memopad 10. I can mute the device but i can't unmute it back. If i use some other application which uses microphone it also doesn't work there. Then i have to restart the device than it start working.
Edti : Mute code
_audioManager.setMicrophoneMute(mute);
Suppose this is the scenario, where you set the microphone to mute using a boolean and then use a button on screen to unmute it.
Boolean mute = true;
final AudioManager myAudio;
myAudio=(AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
myAudio.setMicrophoneMute(mute);
Button unmute = (Button)findViewById(R.id.unm);
unmute.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myAudio.setMicrophoneMute(false);
}
});
Another scenario where you use the same button to mute or unmute :
public Boolean mute = true;
final AudioManager myAudio;
myAudio=(AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
Button unmute = (Button)findViewById(R.id.unm);
unmute.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myAudio.setMicrophoneMute(mute);
if(mute=true){
mute=false;
}
else{
mute=true;
}
}
});
Now everytime,the button

MediaPlayer gives different results if it has to wait longer before .start() is called

I'm trying to use a MediaPlayer instance to play several audio files individually, in response to various sensor events.
I've found that when I load up the clip to be played right before calling MediaPlayer.start(), the audio clip will play fine. However, the application takes a major performance hit. Ideally, each audio clip should be loaded into the MediaPlayer immediately after the last one was played, leaving the MediaPlayer ready to start playback the instant the SensorEvent comes in.
I would expect this to be simple, but now that I made the change the audio just doesn't play. PlayAudioClip() is definitely still being called as expected, but something is going wrong after that. No errors are thrown, so I don't think the MediaPlayer is changing state, but could something be interfering with in the time that it's waiting to play?
Here is a simplified version of my code:
public class MainActivity extends Activity implements SensorEventListener {
private Random numGenerator;
private SensorManager manager;
private Sensor accelerometer;
private MediaPlayer mediaPlayer;
private Uri[] audioClips;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initVariables();
prepareNextAudioClip(); //load first audioClip
}
#Override
public void onSensorChanged(SensorEvent event) {
if(conditionsRight()){
playAudioClip();
}
}
}
private void playAudioClip() {
mediaPlayer.start();
prepareNextAudioClip();
}
private void prepareNextAudioClip() {
try {
mediaPlayer.reset();
Uri audioClip = audioclips[(int) Math.floor(numGenerator.nextDouble()*audioClips.length)];
mediaPlayer.setDataSource(this, audioClip);
mediaPlayer.prepare();
} catch (Exception e) {
e.printStackTrace();
}
}
//Code below here isn't very important... handling setup and teardown
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
protected void onResume() {
super.onResume();
manager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_UI);
}
private void initVariables() {
audioClips = new Uri[]{
Uri.parse("android.resource://com.example.afraidofflying/" + R.raw.audio1),
Uri.parse("android.resource://com.example.afraidofflying/" + R.raw.audio2),
Uri.parse("android.resource://com.example.afraidofflying/" + R.raw.audio3)
};
numGenerator = new Random();
mediaPlayer = new MediaPlayer();
manager = (SensorManager)getSystemService(SENSOR_SERVICE);
accelerometer = manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if(null == accelerometer) finish();
}
protected void onPause() {
super.onPause();
manager.unregisterListener(this);
}
protected void onDestroy(){
mediaPlayer.release();
mediaPlayer = null;
}
}
PS: This has all been assuming I'll only use one instance of MediaPlayer but I'd also like input on if you think using multiple MediaPlayers and delegating each of them 1 audio clip would be advisable. My intuition is no because for my purposes I'd have to use 10-20 MediaPlayers, but it would be good to hear outside perspectives on it.
It's because you're resetting player right after starting playback.
private void playAudioClip() {
mediaPlayer.start(); //starting playback
prepareNextAudioClip(); //reset
}
if you want to play files in queue, than you can use one instance. But if you have to play several files simultaneusly, then you need to have several media player instances.
I think you have to look at subtle points regarding using Mediaplayer class
In your code you used:
initVariables();
prepareNextAudioClip(); //load first audioClip
initVariables() seems ok, Now lets see prepareNextAudioClip()
...
mediaPlayer.reset();
...
...
mediaPlayer.prepare();
The above code seems to corrupt Mediaplayer state machine. Please refer to http://developer.android.com/reference/android/media/MediaPlayer.html for details on using new, prepare,reset. It is better to write defensive MediaPlayer code using Errorlistener

Double logs while getting the volume of System ring using ContentObserver

I am trying to get System ring volume change using the content Observer. Using this volume integer number I would like trigger another java file.
I succeeded using the below code but the problem is I am getting two logs always. I am trying to differentiate the previousVolume and ChangedVolume. I am not why am I getting to logs inside change method? Good thing about this is that the values are not changing?
Here is the code I have tried:
public class VolumeChecker extends ContentObserver
{
int previousVolume;
Context context;
public VolumeChecker(Context c, Handler handler)
{
super(handler);
context=c;
AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
previousVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
}
#Override
public boolean deliverSelfNotifications()
{
return super.deliverSelfNotifications();
}
#Override
public void onChange(boolean selfChange)
{
super.onChange(selfChange);
AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
int currentVolume = audio.getStreamVolume(AudioManager.STREAM_RING);
Log.e("changed", "Volume"+currentVolume);
}
}
And registering the obersever -from service as:
Volume = new VolumeChecker(this,new handler());
getApplicationContext().getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI, true, Volume );
Does anybody know why it is logging twice inside onChange part?

Android proximity sensor when uncoverd

I work in project where i use proximity sensor my program should mute the phone when the proximity sensor is covered and restore it to normal when the sensor is uncovered. i managed to code for when the sensor is covered but i don't know the value for far when the sensor is uncovered i need a code to unmute when the sensor is uncovered.
#Override
public void onSensorChanged(SensorEvent event) {
audio.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if(event.sensor.getType()==Sensor.TYPE_PROXIMITY){
if(event.values[0]<5){ audio.setRingerMode(AudioManager.RINGER_MODE_youwant);}else{ audio.setRingerMode(AudioManager.RINGER_MODE_SILENT);}
}
}
Here is the code for mute/unmute
AudioManager mAudioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
int current_volume =mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
//If you want to player is mute ,then set_volume variable is zero.Otherwise you may supply some value.
int set_volume=0;
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,set_volume, 0);

Categories

Resources