Question

I am trying to create android app which will play two short sounds continuously. I have to adjust volume on the go and it should be stereo sound. I mean the left volume may become louder while the right volume may become quieter. How can I achieve that? I have created an AsyncTask as below and I am going to run two of them at the same time. Is it a right approach?

private class PlaySoundTask extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onCancelled() {
        super.onCancelled();
    }

    @Override
    protected void onPreExecute() {

    SoundPool sndPool = new SoundPool(16, AudioManager.STREAM_MUSIC, 100);
    sndPool.load(R.raw.soundOne, 1);

    }

    @Override
    protected Void doInBackground(String... params) {
        while (m_stop_sound) {


            sndPlay.play(R.raw.soundOne, 1, 0, 0);


        }
        return null;
    }
}
Was it helpful?

Solution

No, this approach is not correct for a simple reason. Depending on the version you're running, two AsyncTasks may not be able to run concurrently:

https://groups.google.com/forum/?fromgroups#!topic/android-developers/8M0RTFfO7-M

You can use AsyncTask.executeOnExecutor(...) to override this behavior but still, you will be targeting systems starting from API 11, which is approximately 60% of the available devices:

http://developer.android.com/about/dashboards/index.html

Moreover, AsyncTask is not designed for long running operations since they can easily be killed by the system to retrieve memory. And may cause memory leaks if it holds references to an activity which is no longer used.

Use your own Threads and possibly use an Handler to notify the UI Thread. Also take a look here:

Android AsyncTask for Long Running Operations

where RoboSpice is suggested as an out-of-the-box safe-alternative to AsyncTask.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top