Skip to content
Search

Android.media.MediaPlayer

lastmod 2018-08-17created 2016-05-193 edits

For simple music playback on Android, there are two options.

For short sound effects you can use android.media.SoundPool, and for long background music you can use android.media.MediaPlayer.

Put music files in the res/raw directory.

StreamingMediaPlayer

android.media.MediaPlayer does not yet support streaming from external URLs so this class provides a pseudo-streaming function by downloading the content incrementally & playing as soon as we get enough audio in our temporary storage: http://code.google.com/p/mynpr/source/browse/trunk/mynpr/src/com/webeclubbin/mynpr/StreamingMediaPlayer.java?spec=svn9&r=9

Files downloaded with MediaPlayer do not play

The following can be found here.

// you store your tempfile in the application cache directory and the problem is that the MediaPlayer doesn't have access rights to application directories.
// Instead you should passing a FileDescriptor to your MediaPlayer with setDataSource(FileDescriptor fd).
// Something like this:
// ...
FileInputStream fis = new FileInputStream(bufferedFile);
FileDescriptor fd = fis.getFD();
mediaPlayer.setDataSource(fd);

Based on this, you can write the following.

try {
 MediaPlayer mediaPlayer = new MediaPlayer();
 FileInputStream fis = new FileInputStream(pathinlocal+FileName);
 FileDescriptor fd = fis.getFD();
 mediaPlayer.setDataSource(fd);
 mediaPlayer.prepare();
 mediaPlayer.start();
} catch (IOException e) {
 // handle exception
 //((EditText) ((Activity) mMain).findViewById(R.id.txtStatus)).setText(e.getMessage());
}

How to return the Android Camera (camcorder) profile

On devices such as the Nexus S, recording with the front camera may not work properly. In that case, set the quality to LOW or set the camera ID.

/** 캠코더의 캠코더 프로파일을 반환한다. */
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
private static CamcorderProfile getCamcorderProfile(int cameraId) {
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
        return CamcorderProfile.get(cameraId, CamcorderProfile.QUALITY_HIGH);
    } else if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
        return CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
    }
    return null;
}

Favorite site

References


  1. Android-mediaplayer_vs_soundpool.zip ↩