I'm having trouble playing an external MP3 file on Android. I'm using the following code:
MediaPlayer player = new MediaPlayer();
try {
BufferedInputStream bis = new BufferedInputStream(new java.net.URL(url).openStream());
FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/forvo_temp.mp3");
BufferedOutputStream bos = new BufferedOutputStream(fos,1024);
byte [] data = new byte[1024];
int x=0;
while((x=bis.read(data,0,1024))>=0){
bos.write(data,0,x);
}
player.reset();
player.start();
} catch (Exception e) {
e.printStackTrace();
}
url
is the string where the external file is. I do have write permission for the SD card (WRITE_EXTERNAL_STORAGE
).
On the debug, I see:
E MediaPlayer start called in state 1
E MediaPlayer error (-38, 0)
E MediaPlayer Error (-38,0)
What might the problem be?
Found the answer: before calling player.start()
, you have to run setDataSource()
and prepare()
, according to the State Diagram of the MediaPlayer reference.
Like this:
// Use same path as before
player.setDataSource(Environment.getExternalStorageDirectory().getPath() + "/forvo_temp.mp3");
player.prepare();