I am trying to play an audio file
if (audioFile != null && audioFile.exists()) {
mediaPlayer = new MediaPlayer();
try {
Uri audioUri = Uri.fromFile(new File(audioFile.getAbsolutePath()));
mediaPlayer.setDataSource(getApplicationContext(),audioUri);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
Log.e("MediaPlayer Error", "Error while setting data source: " + e.getMessage());
} catch (IllegalArgumentException e) {
Log.e("MediaPlayer Error", "Error while preparing MediaPlayer: " + e.getMessage());
} catch (IllegalStateException e) {
Log.e("MediaPlayer Error", "Error while starting MediaPlayer: " + e.getMessage());
}
} else {
Toast.makeText(MainActivity.this, "No audio file to play", Toast.LENGTH_SHORT).show();
}
Yet I get
E/MediaPlayerNative: Unable to create media player
E/MediaPlayer Error: Error while setting data source: setDataSourceFD failed.: status=0x80000000
I thought about permission errors, so I added <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
to the manifest and
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
to the code of protected void onCreate(Bundle savedInstanceState)
and
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this, "Ja", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Nein", Toast.LENGTH_SHORT).show();
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
outside.
I always get Nein
and no window is showing up to ask for permissions, it goes straight to Nein
.
The solutions here did not work so far.
I am using this in build gradle:
defaultConfig {
applicationId "com.my.program"
minSdk 27
targetSdk 33
versionCode 1
versionName "1.0"
}