Search code examples
javaandroidaudioandroid-mediaplayer

Playing a sound on android


I have come across another error along my first app journey :) I want to play a sound when the app loads. Which is a .wav file. It lasts 2 seconds long yet it does not play when I run the app on my old Samsung S4. There is no errors within the IDE or anything I can see, I have checked if 'mp' has a value and it does. Looking around on posts most people have the problem that 'mp' is = null. Whereas mine has a value just no sound comes out of the phone... Again, any help is appreciated!

public class OpeningScreen extends Activity {
    @Override
    // create the screen state
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // connect the xml layout file
        setContentView(R.layout.activity_opening_screen);

        final MediaPlayer mp = new MediaPlayer();
        mp.create(this, R.raw.welcome_message);

        mp.start();

        // create the on touch listener
        ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.opening_layout);

        layout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // change the screen to a new state
                Intent intent = new Intent(OpeningScreen.this, GameScreen.class);

                // start the new activity
                startActivity(intent);

                // stop welcome sound (if still playing)
                mp.stop();
                return true;
            }
        });
    }
}

Solution

  • public static MediaPlayer create(Context context, int resid) is a static method to create a MediaPlayer for a given resource id. It means that by calling create you are creating a new instance of media player with no reference usage.

    Try to change

    final MediaPlayer mp = new MediaPlayer();
    mp.create(this, R.raw.welcome_message);
    

    to

    final MediaPlayer mp = MediaPlayer.create(this, R.raw. welcome_message);
    

    And the player should work.