Dave
Dave

Reputation: 324

Start audio as soon as the app is loaded Android App

I'm creating a game, and I have a few audio clips in the game. I'm using audio pool and I'm only using 2 audio clips. They are both mp3 format, 1 is 700kb and the other is 800 bytes.

I'm trying to play the 700kb audio clip when the game is first loaded. It's a background sound that will loop forever as long as the app is open. However everything I've tried fails. The only way I was able to get it to work is to start a thread on startup and have the thread sleep for like 15 seconds. After that it calls the start audio and it plays, but if the thread is destroyed it will kill the sound with it.

I'm assuming the audio is buffering maybe and that's why it doesn't play at start? Also do you have to make all audio calls from a thread?

Upvotes: 1

Views: 562

Answers (1)

Lumis
Lumis

Reputation: 21639

I have just used this code in an Activity onCreate() method it is working fine:

public class LaunchActivity extends Activity {
       private MediaPlayer mp;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.whatever);

        setVolumeControlStream(AudioManager.STREAM_MUSIC); 
        mp = MediaPlayer.create(this, R.raw.a);
        mp.start();

    }

If there is no stop instructions for this instance it will continue to play for all activities in the application, and if you exit your application it will still play and when you come back a new instance will start to play over the old at the same time! The media player is its own process so I think there is no need for another thread.

Are you sure something is not wrong with your MP3 file and makes the system struggle?

Upvotes: 1

Related Questions