Rajasekaran T
Rajasekaran T

Reputation: 23

How to release Soundpool in android

While I am scanning racks using barcode, I implemented a singleton class of soundpool, while continue scans, automatically app closed. The error is "Could not read input channel file descriptors from parcel".

 public void successfulAlert() {
    Logger.d("", "SuccessAlert Start" + Calendar.getInstance().getTimeInMillis());
    final int audioID = mSPool.load(Application.getInstance(), R.raw.scan, 1);
    mSPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
        
        @Override
        public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
            Logger.d("", "SuccessAlert Completed " + Calendar.getInstance().getTimeInMillis());
            float volume = (float) mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            mSPool.play(audioID, volume, volume, 1, 0, 1f);
          ///  cleanupSound();
        }
    });
    Logger.d(TAG, "Possitive Scan Beep ");
}

This code is for success alert. I tried to cleanup the soundpool release, but the sound is not heard. Can anyone suggest me, how to release soundpool after playing a sound.

 public void cleanupSound() {
    if (mSPool != null) {
        mSPool.release();
       // mSPool=null;
       // mAudioManager.unloadSoundEffects();
       // mInstance=null;
    }
}

Upvotes: 1

Views: 1303

Answers (1)

William Ellis
William Ellis

Reputation: 106

The Question is two fold: 1) Why is my sound not playing? 2) How do I correctly release a SoundPool?

For 1 - SoundPool play is asynchronous. You are doing: "play then release" but you need to do "play then wait-until-play-has-completed then release".

For 2 - Due to 1, you ought not to release a SoundPool until play has completed. Unfortunately, there is no way to ask the SoundPool to callback when it has finished playing. I've seen two solutions to this:

  • If you know how long it will take to play the sample (X ms), schedule your release, for X ms in the future, perhaps using postDelayed from Handler.
  • Decide that the truly important concern is that the SoundPool is released when your application is finished. So, monitor all exit points from your application, and ensure that, at each, the SoundPool is released. If someone closes the application while you are playing sound, you might abruptly cut that effect, but this is probably the correct behaviour as your application is exiting!

Note: To be a truly well behaved Android citizen, your application should only play sound if it has first acquired, and continues to hold, the Audio Focus. More info on that here: https://developer.android.com/guide/topics/media-apps/volume-and-earphones.html

Upvotes: 1

Related Questions