Search code examples
androidsoundpool

Streaming audio file to soundpool load() Android


I want to use SoundPool class to create Playback speed effects. To play sound fastly or slowly (1x,0.5x,2x etc). But the problem is soundpool handles only small files. When i give a large file. It doesn't play anything. I was wondering if it would be possible to load stream of music (some bytes of my large audio file) and play it via soundpool. any idea.??

Here is my code for soundPool to play song

AudioManager mgr = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = streamVolumeCurrent / streamVolumeMax;  
soundID = soundPool.load(Environment.getExternalStorageDirectory()+"/cm.mp3", 1);
soundPool.play(soundID, volume, volume, 1, 0, 1.0f);

I found JetPlayer and AudioTrack classes, but i m not finding any good tutorials to handle this.


Solution

  • You will need to check file is loaded successfully before playing it using SoundPool.setOnLoadCompleteListener

    public void loadSound (String strSound, int stream) {
         boolean loaded = false;
         mSoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
                @Override
                public void onLoadComplete(SoundPool soundPool, int sampleId,
                        int status) {
                    loaded = true;
                }
            });
        try {
              stream= mSoundPool.load(aMan.openFd(strSound), 1);
            } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       // Is the sound loaded already?
       if (loaded) {
         mSoundPool.play(stream, streamVolume, streamVolume, 1, LOOP_1_TIME, 1f);
        }
    }
    

    where aMan is

    AssetFileDescriptor aMan =  getAssets();