我正在尝试获取一个 mp3 文件并将其保存在手机内存而不是 SD 卡上,然后立即使用媒体播放器播放。当我以前用它在 SD 卡上做同样的事情时,这段代码运行良好,所以在我保存和读取 mp3 的位置似乎可能有一些错误。
这是我的代码:
try {
MediaPlayer player = new MediaPlayer();
URI uri = null;
try {
uri = new URI(
"http://translate.google.com/translate_tts?tl="
+ oLanguage + "&q=" + text);
} catch (URISyntaxException e) {
e.printStackTrace();
}
String FileName = "Audio2.mp3";
URL u = new URL(uri.toASCIIString());
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
// FileOutputStream f = new FileOutputStream(new File(
// Environment.getExternalStorageDirectory()
// + "/download/" + FileName));
FileOutputStream f = openFileOutput(FileName, MODE_PRIVATE);
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
// player.setDataSource(Environment.getExternalStorageDirectory()
// + "/download/" + FileName);
player.setDataSource("/data/data/com.comm/files/" + FileName);
player.prepare();
player.start()
日志猫:
07-30 12:23:47.319: W/MediaPlayer(22426): info/warning (1, 26)
07-30 12:23:47.319: E/MediaPlayer(22426): error (1, -4)
07-30 12:23:47.319: W/System.err(22426): java.io.IOException: Prepare failed.: status=0x1
07-30 12:23:47.329: W/System.err(22426): at android.media.MediaPlayer.prepare(Native Method)
07-30 12:23:47.329: W/System.err(22426): at com.comm.Connect.Text(Connect.java:396)
07-30 12:23:47.329: W/System.err(22426): at com.comm.Connect$7.onClick(Connect.java:233)
07-30 12:23:47.329: W/System.err(22426): at android.view.View.performClick(View.java:2485)
07-30 12:23:47.329: W/System.err(22426): at android.view.View$PerformClick.run(View.java:9080)
07-30 12:23:47.329: W/System.err(22426): at android.os.Handler.handleCallback(Handler.java:587)
07-30 12:23:47.329: W/System.err(22426): at android.os.Handler.dispatchMessage(Handler.java:92)
07-30 12:23:47.329: W/System.err(22426): at android.os.Looper.loop(Looper.java:130)
07-30 12:23:47.329: W/System.err(22426): at android.app.ActivityThread.main(ActivityThread.java:3687)
07-30 12:23:47.329: W/System.err(22426): at java.lang.reflect.Method.invokeNative(Native Method)
07-30 12:23:47.329: W/System.err(22426): at java.lang.reflect.Method.invoke(Method.java:507)
07-30 12:23:47.329: W/System.err(22426): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
07-30 12:23:47.329: W/System.err(22426): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
07-30 12:23:47.329: W/System.err(22426): at dalvik.system.NativeStart.main(Native Method)
最后,我是否需要指定任何权限以允许我保存到手机内存中?