2
\$\begingroup\$

When two audio's are played at the same time... the sound is cancelling out. How do I fix this weird phenomenon?

I have some code where there is audio on button click and audio in ten second intervals (in a background service). I have the following code to stop the button audio when the ten second interval plays, and it works fine:

public static void myPop(Context context){
    AudioManager manager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
    if(!manager.isMusicActive()) {       //Only if there isn't any other audio playing
        MediaPlayer pop = MediaPlayer.create(context, R.raw.pop);
        pop.start();
    }
    else{
        Log.v(TAG, "Audio is already playing");
    }
}

This works fine, and it stops one audio from playing (pop) to let the other audio play (the one from the background service). Now, I am getting the issue when they both play at the same time. For example, when I tap the button at the exact same time as when the audio from the background service is about to start. When they are both played at the same time, the audio just gets cut off.

Is there any way to give a preference to the background service audio? Somehow say that: If two audio pieces start at the exact same time, I want to let the background service audio to play.

To think of this visually:

enter image description here

I want to say that if I have the choice between apples and oranges, pick apples. AKA If I have two audio players playing at the same time, pick one (the apple).


Image source

\$\endgroup\$
  • \$\begingroup\$ How complex is audio in your game? If you have simple audio needs Ahmet's answer using SoundPool should suit you best, if not, and you have many different audio emitting entities that need mixing, why not use an API like OpenAL or something built into your libraries like SDL's mixer or Cocos' Audio API (which is very friendly and forgiving while still being fairly effective). \$\endgroup\$ – user5665 Apr 3 '16 at 12:58
1
\$\begingroup\$

Each MediaPlayer can play only one audio at the same time (Remember, can you play multiple musics in your music player app?).

But if you want to play multiple sounds you should use SoundPool instead. There you can play sounds with higher priority too.

An example for SoundPool: link

Check this for playing it in background: link

|improve this answer|||||
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.