Text
MediaPlayer mediaPlayer = new MediaPlayer();
File sdCard = Environment.getExternalStorageDirectory();
File song = new File(sdCard.getAbsolutePath() + "/Music/Song.mp3");
try{
mediaPlayer.setDataSource(song.getAbsolutePath());
mediaPlayer.prepare();
mediaPlayer.setOnCompletionListener(...onCompletion...);
}
catch ...
//Reproducir una cancion de la carpeta raw
mediaPlayer = MediaPlayer.create(context, R.raw.song_name);
//Funciones de control
mediaPlayer.start();
mediaPlayer.pause();
mediaPlayer.stop();
mediaPlayer.release();
if (ContextCompat.checkSelfPermission(Music.this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(Music.this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(Music.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_CONSTANT_EXTERNAL_STORAGE);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
onRequestPermissionsResult
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_CONSTANT_EXTERNAL_STORAGE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
if(ContextCompat.checkSelfPermission(Music.this,Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Intent intent1 = new Intent(Intent.ACTION_PICK, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent1, 1);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
try {
/* Aquí tenemos que resetear el media player
y a continuación cargamos la canción */
{...}
mediaPlayer.setDataSource(this,data.getData());
/* Con la canción ya cargada, tenemos que reproducir la canción */
{...}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}