我想制作示例在android中播放音频文件,我想播放手机内存中的音乐。请建议如何给出路径。
我正在写这篇文章,但面临 java.io.IOException:prepare failed 错误
final MediaPlayer mp = new MediaPlayer();
try{
mp.setDataSource(Environment.getRootDirectory()+"/1.mp3");
mp.prepare();
}
catch(Exception e)
{
e.printStackTrace();
}
最佳答案
你可以尝试这样的事情。
// Add permission to your menifest to Read File from your storage
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
然后在您调用加载 mp3 文件的 JAVA 类/Activity 中。
MediaPlayer mPlayer;
// Your Media Player will be called with Audio file here..
private void loadAudio(){
String fileName = "YourAudio.mp3";
String completePath = Environment.getExternalStorageDirectory() + "/" + fileName;
File file = new File(completePath);
Uri myUri1 = Uri.fromFile(file);
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mPlayer.setDataSource(getApplicationContext(), myUri1);
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
}
mPlayer.start();
}
希望这对您有帮助。
关于android - 如何在Android中播放手机内存中的音频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30100083/