首页 > 解决方案 > 如何在 android studio 中为音乐播放器添加在线歌曲下载?

问题描述

我是 Android 工作室的新开发人员。我想要一个创建音乐播放器。但是,这个音乐播放器在线歌曲下载然后将播放 ve 并从存储中读取歌曲。我在这方面有点缺乏经验。我不知道如何使用代码从互联网下载歌曲到我的项目。我应该使用哪种方法、代码、库或 API?我想使用 kotlin 语言。谁能帮我解决这个问题

标签: androidkotlindownloadaudio-streaming

解决方案


此代码有效:

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();

结果无法保证。你可以试试


推荐阅读