Search code examples
androidfile-descriptor

Not able to play the raw file in Android?


I tried the below code to play the mp3 file but it plays all the ringtones. Can anyone help me why the ringtone is being played?

            MediaPlayer mMediaPlayer1 = new MediaPlayer();
            AssetFileDescriptor fd = context.getResources().openRawResourceFd(R.raw.dialtone);
            FileInputStream in = new FileInputStream(fd.getFileDescriptor());



            mMediaPlayer1.setDataSource(in.getFD());

            mMediaPlayer1.setLooping(true);
            mMediaPlayer1.prepare();
            mMediaPlayer1.start();`

Solution

  • Try this:

    public static void startSound(Context context, int soundResId) {
        if (mMediaPlayer != null) {
            mMediaPlayer.reset();
            mMediaPlayer = null;
        }
        mMediaPlayer = MediaPlayer.create(context, soundResId);
        mMediaPlayer.start();
    }
    

    then

    startSound(this, R.raw.dialtone);