android - 如何在 android studio 中为音乐播放器添加在线歌曲下载?
问题描述
我是 Android 工作室的新开发人员。我想要一个创建音乐播放器。但是,这个音乐播放器在线歌曲下载然后将播放 ve 并从存储中读取歌曲。我在这方面有点缺乏经验。我不知道如何使用代码从互联网下载歌曲到我的项目。我应该使用哪种方法、代码、库或 API?我想使用 kotlin 语言。谁能帮我解决这个问题
解决方案
此代码有效:
private static void downloadFile(String url, File outputFile) {
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
} catch(FileNotFoundException e) {
return;
} catch (IOException e) {
return;
}
}
确保您已Manifest.permissions.READ_EXTERNAL_STORAGE
在 Manifest 中声明。
然后
File files = new File(Environment.getExternalStorageDirectory().toString());
String file = downloadFile("yourweb.com/music.mp3", files);
String directory = Environment.getExternalStorageDirectory()+"/music.mp3";
MediaPlayer mediaPlayer = MediaPlayer.create(MainActivity.this, directory);
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
结果无法保证。你可以试试
推荐阅读
- jqplot - jqPlot - 绘制面积图和条形图/折线图时颜色的重叠
- sql-server - 如何创建只能访问运行存储过程的登录名?
- amazon-web-services - 在 GCP 中,与使用共享 vpc 相比,具有 vpc 对等的中心辐射模型更好
- r - 我正在尝试计算出现的数量并传播到多个列,并希望随着时间的推移将数字聚合
- java - 如何修改抽象数据类型 (ADT) 堆栈?
- python - 如何在python 3的while循环中嵌套if语句
- c - 构建二叉树时如何获取树节点的父节点?
- c# - ASP.NET Core 中的 Microsoft 身份验证 - MFA
- json - 如何访问嵌套在另一个 json 响应的 ['error'] 属性中的 json 属性?
- arduino - 如何获得 +IPD 响应的值