Search code examples
androidaudioandroid-intentsoundpool

Sound not ringing on load of The Intent


I am calling this class from another class using intent and i want to play this song "song.ogg" on load of the class .. please Help me How To??

public class DetlsActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detls_layout);

        getActionBar().setDisplayHomeAsUpEnabled(true);

        SoundPool soundPool;
        int soundID;
        soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
        soundID = soundPool.load(this,R.raw.song, 1);
        AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        //soundPool.play(soundID,1f,1f,1,0,1f);
        Toast.makeText(this,"Ringing Song",Toast.LENGTH_LONG).show();
        try {
        AssetFileDescriptor assetFileDescriptor = this.getAssets().openFd("song.ogg");
        soundPool.load(assetFileDescriptor,1);
            Toast.makeText(this,"Played",Toast.LENGTH_LONG).show();
        }
        catch (Exception e) {
            Log.d("LOGCAT","Exception Song");
        }

Solution

  •     SoundPool soundPool;
        int soundID;
        soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
        Toast.makeText(this,"Ringing Song",Toast.LENGTH_LONG).show();
        try {
            soundID = soundPool.load(this,R.raw.song, 1);
            int waitLimit = 1000;
            int waitCounter = 0;
            int throttle = 10;
            while(soundPool.play(soundID, 1.f, 1.f, 1, 0, 1.f) == 0 && waitCounter < waitLimit)
              {waitCounter++; SystemClock.sleep(throttle);}
            Toast.makeText(this,"Played "+soundID,Toast.LENGTH_LONG).show();
    
        }
        catch (Exception e) {
            Log.d("LOGCAT","Exception Song");
            Toast.makeText(this,"Exception "+e,Toast.LENGTH_LONG).show();
        }
    

    Replace your code with above code. Current code give warning soundpool sample 1 not ready so check this using while condition.

    Here, your resource is in raw folder that's why we use soundID = soundPool.load(this,R.raw.song, 1);. If your resource is in assets folder at that time you can use soundID = soundPool.load(getAssets().openFd("song.ogg"),1);