java Android 播放外部 MP3:错误——在状态 1 中调用 MediaPlayer start
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16511213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android playing external MP3: error -- MediaPlayer start called in state 1
提问by
I'm having trouble playing an external MP3 file on Android. I'm using the following code:
我在 Android 上播放外部 MP3 文件时遇到问题。我正在使用以下代码:
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
).
url
是外部文件所在的字符串。我确实有对 SD 卡 ( 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?
可能是什么问题?
回答by
Found the answer: before calling player.start()
, you have to run setDataSource()
and prepare()
, according to the State Diagram of the MediaPlayer reference.
找到答案:在调用 之前player.start()
,您必须根据MediaPlayer 参考的状态图运行setDataSource()
和。prepare()
Like this:
像这样:
// Use same path as before
player.setDataSource(Environment.getExternalStorageDirectory().getPath() + "/forvo_temp.mp3");
player.prepare();
回答by YueYue
You need to set AndroidManifest.xml
permission as:
您需要将AndroidManifest.xml
权限设置为:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>