Skip to content

Instantly share code, notes, and snippets.

@dynoChris
Last active June 23, 2024 04:50
Show Gist options
  • Save dynoChris/24ab88a30b71e8aee245ce52ffe79b79 to your computer and use it in GitHub Desktop.
Save dynoChris/24ab88a30b71e8aee245ce52ffe79b79 to your computer and use it in GitHub Desktop.
How to work with MediaPlayer in Android
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private MediaPlayer mPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initPlayer();
}
private Uri mCurrentRingtoneUri;
private void initPlayer() {
mPlayer = new MediaPlayer();
mCurrentRingtoneUri = RingtoneManager.getActualDefaultRingtoneUri(getApplicationContext(), RingtoneManager.TYPE_RINGTONE);
//mCurrentRingtoneUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.dreamer_sky); //raw folder
try {
mPlayer.setDataSource(this, mCurrentRingtoneUri);
mPlayer.setLooping(true);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment