I'm trying to play audio files with the built in mediaplayer in Android Studio. I'm using the code below to call an intent and open a third party file manager to get a files Uri and from that the file path whoich I store somewhere. Anyway, if I use a file manager like ES File Explorer I get a path that looks like "/sdcard/some directory/test.mp3" however, if I use the built in file explorer I get a path like "/documents/audio:1159" for the same file. I understand that the latter is an "asset" but when I try to feed this into mediaplayer I get an exception. What am I doing wrong?
The code below shows the intent method I'm using to get the filepath and the code below that shows how I use that file path to get a Uri and feed this into mediaplayer. Just to be clear file paths like "/sdcard/some directory/test.mp3" work fine. File paths like "/documents/audio:1159" don't.
final View.OnClickListener mGlobal_OnClickListener = new View.OnClickListener() {
public void onClick(final View v) {
int resID2 = v.getId();
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("audio/*");
try {
startActivityForResult(intent,resID2); }
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Please install a file manager",Toast.LENGTH_LONG).show();
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent result) {
if (resultCode == RESULT_OK)
{
Uri data = result.getData();
String thePath = data.getPath();
// Do something with the file path
}
}
Code used to start mediaplayer based on the file path retrieved from above
Uri myUri = Uri.parse(filePath);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(getApplicationContext(), myUri);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {}
I guess you cannot use Uri like
/documents/audio:1159
when uses Intent MediaPlayer
EDITTED: Try this code for getting filepath from assets folder
AssetManager am = getAssets();
InputStream inputStream = am.open(file:///android_asset/myfoldername/myfilename);
File file = createFileFromInputStream(inputStream);
private File createFileFromInputStream(InputStream inputStream) {
try{
File f = new File(my_file_name);
OutputStream outputStream = new FileOutputStream(f);
byte buffer[] = new byte[1024];
int length = 0;
while((length=inputStream.read(buffer)) > 0) {
outputStream.write(buffer,0,length);
}
outputStream.close();
inputStream.close();
return f;
}catch (IOException e) {
//Logging exception
}
return null;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.