I have been stuck on this for over an hour now. In my main menu screen, I have a mute button. I want it to call a method in my background service, which mutes all of the MediaPlayer audio.
Here I am calling mute:
public void mute(View view){
mutebutton = (ImageButton) findViewById(R.id.mutebutton);
currentVolume = manager.getStreamVolume(AudioManager.STREAM_MUSIC);
if (currentVolume == 0) {
TwentySeconds.unMute();
Toast.makeText(Main_Menu.this, "UNMUTED", Toast.LENGTH_SHORT).show();
} else {
TwentySeconds.mute();
Toast.makeText(Main_Menu.this, "MUTED", Toast.LENGTH_SHORT).show();
}
Here are the methods in the service:
public static void mute(){
ten.setVolume(0, 0);
three.setVolume(0, 0);
}
public static void unMute(){
ten.setVolume(1, 1);
three.setVolume(1, 1);
}
Here are the actual media players, which play at intervals:
static `MediaPlayer` ten;
static `MediaPlayer` three;
The problem is, I am getting a null pointer exception here:
currentVolume = manager.getStreamVolume(AudioManager.STREAM_MUSIC);
By the way, manager is instantiated like so:
AudioManager manager;
and later on:
manager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
I would really appreciate any feedback (positive or negative)! Thank you so much for all of your help, let me know if you need any more code.
{Rich}
Your "manager" should instantiated like this:
AudioManager manager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
If this is still a nullpoint, add
Context context = this;
before your instantiation. Try it, wish I can help you.
Related
I am creating an Android app which has a seekbar and it controls the media volume of android device. Now, I have to update the seekbar also if there is any change in media volume of the device either by using volume button or by changing default volume seekbar of the device.
So my question is: Is there any way to listen for volume change in android so that I can update my app specific seekbar when there is a change in volume of the device?
I have found a way of doing it. But, it gets triggered whenever there is any change in Setting.
public class SettingsContentObserver extends ContentObserver {
private AudioManager audioManager;
public SettingsContentObserver(Context context, Handler handler) {
super(handler);
audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
}
#Override
public boolean deliverSelfNotifications() {
return false;
}
#Override
public void onChange(boolean selfChange) {
int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
Log.d(TAG, "Volume now " + currentVolume);
}
}
Is there any better way of doing it? Please suggest.
Thanks in advance
I have come across another error along my first app journey :) I want to play a sound when the app loads. Which is a .wav file. It lasts 2 seconds long yet it does not play when I run the app on my old Samsung S4. There is no errors within the IDE or anything I can see, I have checked if 'mp' has a value and it does. Looking around on posts most people have the problem that 'mp' is = null. Whereas mine has a value just no sound comes out of the phone... Again, any help is appreciated!
public class OpeningScreen extends Activity {
#Override
// create the screen state
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// connect the xml layout file
setContentView(R.layout.activity_opening_screen);
final MediaPlayer mp = new MediaPlayer();
mp.create(this, R.raw.welcome_message);
mp.start();
// create the on touch listener
ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.opening_layout);
layout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// change the screen to a new state
Intent intent = new Intent(OpeningScreen.this, GameScreen.class);
// start the new activity
startActivity(intent);
// stop welcome sound (if still playing)
mp.stop();
return true;
}
});
}
}
public static MediaPlayer create(Context context, int resid) is a static method to create a MediaPlayer for a given resource id.
It means that by calling create you are creating a new instance of media player with no reference usage.
Try to change
final MediaPlayer mp = new MediaPlayer();
mp.create(this, R.raw.welcome_message);
to
final MediaPlayer mp = MediaPlayer.create(this, R.raw. welcome_message);
And the player should work.
It's better to register for OnPreapredListener via MediaPlayer.setOnPreaparedListener and after preparation you start your media playback.
http://developer.android.com/guide/topics/media/mediaplayer.html
Why do you use final?
You can play a mp3 with
MediaPlayer mp = MediaPlayer.create(OpeningScreen.this, R.raw.welcome_message);
mp.start();
Also stopping mediaplayer is better if you stop in onDestroy.
public void onDestroy() {
mp.stop();
super.onDestroy();
}
I created an onClick methord PlaySound in which an if statement checks weather the sound is playing or not , if it is playing it stops it or else it starts it.The problem i face is that the if statement is always false and never true.
CODE
public void PlaySound(View view) {
final MediaPlayer clickSound = MediaPlayer.create(this, R.raw.abcd);
if(clickSound.isPlaying()) {
clickSound.stop();
}
else{
clickSound.setLooping(true);
clickSound.start();
}
}
Remove
final MediaPlayer clickSound = MediaPlayer.create(this, R.raw.abcd);
from play method and create it outside of the method.
Edit for your convenince follow the steps:
You can take a global variable of MediaPlayer
public MediaPlayer clickSound ;
and then create in onCreate method:
clickSound = MediaPlayer.create(this, R.raw.abcd);
and thus your play method will be:
public void PlaySound(View view) {
if(clickSound.isPlaying()) {
clickSound.stop();
}
else{
clickSound.setLooping(true);
clickSound.start();
}
}
I'm really new at java and android and I'm trying to play some sound after a button is pressed. I searched a lot and tried this:
//package and imports
public class Simulador extends Activity {
int contador;
Button somar;
SoundPool som;
boolean loaded;
int comeu, comprou;
protected void onCreate(Bundle primeiroBundle) {
super.onCreate(primeiroBundle);
setContentView(R.layout.activity_primeira_atividade);
contador = 0;
somar = (Button) findViewById(R.id.som);
som = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
//I removed the whole part from the other button,
//since it's basically the same. So that's why I need to set maxStreams to 2.
comeu = som.load(this, R.raw.comeu, 1);
som.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
public void onLoadComplete(SoundPool som, int sampleId, int status){
loaded = true;
}
});
somar.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (loaded) {
som.play(comprou, 1, 1, 1, 0, 1f);
}
contador += 5;
}
}
});
}
protected void onPause() {
super.onPause();
som.release();
som = null;
}
}
My code is working as it should, but I got the follwing warning:
SoundPool(int, int, int)' is deprecated
So I came here to see how to solve and got this:
This constructor was deprecated in API level 21. use SoundPool.Builder instead to create and configure a SoundPool instance
So I went here but couldn't addapt my code to this new constructor, even reading the reference. Does anyone know how to solve this?
I know this question is a couple years old and You've probably already solved this, but hopefully this answer can help others.
For those whom are concerned about backwards compatibility in android versions and want to have the best of both worlds, here is a possible implementation that I've done.
In the onCreate() function where you instantiate your SoundPool object, write a logic check for the android version and use the respective constructor.
// For ADK versions 21 (Lollipop) or greater
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
sounds = new SoundPool.Builder().build();
// Else use older syntax (deprecated with ADK 21)
} else {
sounds = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
}
Note: this will technically still throw a warning in your IDE for using the deprecated method, but if you are concerned about APKs bellow 21, this may be the best option for you.
After you have instantiated it, simply load your sound files, and play the sound (call the bellow playSound() method in the onClick() listener on your button):
soundId = sounds.load(context, R.raw.sound, 1);
public void playSound() {
sounds.play(soundId, 1, 1, 1, 0, 1);
}
I have an application with a mute button. I have been stuck on this for 4 and a half hours now, so I am plain desperate. I am trying to have the volume mute when user clicks mute and unmute when user clicks it again. This works fine, except the audio isn't playing. For some reason, Stream_Music is 0?
public void mute(View view) {
mutebutton = (ImageButton) findViewById(R.id.mutebutton);
if ((variableForMute.x % 2) != 0) { //If it's odd UNMUTE
Log.v(TAG, "Use this volume to unmute " +userVolumeOnStart.userVolume +"");
Toast.makeText(Main_Menu.this, "UNMUTED", Toast.LENGTH_SHORT).show();
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, userVolumeOnStart.userVolume, 0);
variableForMute.x++;
} else { //If its even MUTE
userVolumeOnStart.userVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
Log.v(TAG, "Right Before Mute " +userVolumeOnStart.userVolume +"");
mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
Toast.makeText(Main_Menu.this, "MUTED", Toast.LENGTH_SHORT).show();
variableForMute.x++;
}
}
Here is the beginning where I declare the variables and objects:
ImageButton leftcenter;
ImageButton mutebutton;
final String TAG = "userVolume";
private AudioManager mAudioManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main__menu);
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
leftcenter = (ImageButton) findViewById(R.id.startGame);
}
The thing is, as log outputs, I am getting the following:
I should have the volume change to what my volume was before I started my app. I want to be able to have the user unmute the app to the same volume that the user was originally on. But for some reason it is always 0!? Why is this happening? My phone volume is at full?!
Please help,
I have spent way too much time on this-I appreciate all feedback:
positive, negative, neutral, whatever.
I found the issue. I have changed STRAM_MUSIC to STREAM_RING, and the variable userVolumeOnStart.userVolume changes successfully!
btn_mute.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if(isChecked) {
btn_mute.setBackgroundResource(R.drawable.mute_bt);
audio.setStreamMute(AudioManager.STREAM_MUSIC, true);
} else {
btn_mute.setBackgroundResource(R.drawable.volume_bt);
audio.setStreamMute(AudioManager.STREAM_MUSIC, false);
}
}
});