I face a problem when trying to play an audio file located inside the expansion file in the phone’s internal memory
private void playSelectedSong(String songName) {
String obbPath = Environment.getExternalStorageDirectory() + "/Android/obb/com.mesbahi.free.player/main.1.com.mesbahi.free.player.obb";
try {
ZipFile obbZipFile = new ZipFile(obbPath);
Enumeration<? extends ZipEntry> entries = obbZipFile.entries();
boolean fileFound = false;
while(entries.hasMoreElements()){
ZipEntry entry = entries.nextElement();
if(entry.getName().startsWith(songName)){
InputStream inputStream = obbZipFile.getInputStream(entry);
File tempFile = File.createTempFile(songName, "."+getFileExtension(entry), getCacheDir());
FileOutputStream outputStream = new FileOutputStream(tempFile);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.close();
inputStream.close();
Uri uri = Uri.fromFile(tempFile);
MediaItem mediaItem = MediaItem.fromUri(uri);
player.setMediaItem(mediaItem);
player.prepare();
player.play();
player.setRepeatMode(Player.REPEAT_MODE_ONE);
fileFound = true;
break;
}
}
if (!fileFound) {
Intent fileNotFoundIntent = new Intent("com.mesbahi.free.player.FILE_NOT_FOUND");
LocalBroadcastManager.getInstance(this).sendBroadcast(fileNotFoundIntent);
}
} catch (IOException e) {
e.printStackTrace();
}
Intent updateButtonIntent = new Intent("com.mesbahi.free.player.UPDATE_BUTTON_STATE");
updateButtonIntent.putExtra("isPlaying", true);
LocalBroadcastManager.getInstance(this).sendBroadcast(updateButtonIntent);
}
private String getFileExtension(ZipEntry entry){
String name = entry.getName();
int lastIndexOf = name.lastIndexOf(".");
if (lastIndexOf == -1) {
return "";
}
return name.substring(lastIndexOf);
}
The code works correctly on Android versions 13 or lower
The bug only appears in Android version 14, and this appears in the logcat :
FileNotFoundException: /storage/emulated/0/Android/obb/com.mesbahi.free.player/main.1.com.mesbahi.free.player.obb (Permission denied)