Skip to content Skip to sidebar Skip to footer

Problems With MediaPlayer, Raw Resources, Stop And Start

I'm new to Android development and I have a question/problem. I'm playing around with the MediaPlayer class to reproduce some sounds/music. I am playing raw resources (res/raw) an

Solution 1:

this is how MediaPlayer.create method works to open a raw file:

    public static MediaPlayer create(Context context, int resid) {
         try {
             AssetFileDescriptor afd = context.getResources().openRawResourceFd(resid);
             if (afd == null) return null;

             MediaPlayer mp = new MediaPlayer();
             mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
             afd.close();
             mp.prepare();
            return mp;
        } catch (IOException ex) {
            Log.d(TAG, "create failed:", ex);
            // fall through
        } catch (IllegalArgumentException ex) {
            Log.d(TAG, "create failed:", ex);
           // fall through
        } catch (SecurityException ex) {
            Log.d(TAG, "create failed:", ex);
            // fall through
        }
         return null;
    }

Solution 2:

Or, you could access the resource in this way:

mediaPlayer.setDataSource(context, Uri.parse("android.resource://com.package.name/raw/song"));

where com.package.name is the name of your application package


Solution 3:

You can use

mp.pause();
mp.seekTo(0);

to stop music player.


Solution 4:

Finally, the way it works for me:

public class MainStart extends Activity {

    ImageButton buttonImage;
    MediaPlayer mp;
    Boolean playing = false;

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

        buttonImage = (ImageButton)findViewById(R.id.ButtonID);


        buttonImage.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if(playing){
                    mp.stop();
                    playing = false;
                }else{
                    mp = MediaPlayer.create(getApplicationContext(), R.raw.sound_u_want);
                    mp.start();
                    playing = true;
                }
            }
        });
    }
}

Solution 5:

MR. Rectangle, this message maybe too late for it, but I proudly write these codes to your idea: I have mp for mediaplayer and sescal9 is a button.

....
if(btnClicked.getId() == sescal9_ornek_muzik.getId())
        {
            mp.start();
            mp.seekTo(380);
            mp2.start();
            mp2.seekTo(360);
            mp3.start();
            mp3.seekTo(340);
            ...
            }

Post a Comment for "Problems With MediaPlayer, Raw Resources, Stop And Start"