如何从Environment.DIRECTORY_DOWNLOADS播放mp3文件

时间:2016-10-25 10:29:43

标签: java android android-studio audio media-player

我从Url下载了mp3文件,并通过以下代码将其保存在Environment.DIRECTORY_DOWNLOADS中:

request.setDestinationInExternalFilesDir(MainActivity.this, Environment.DIRECTORY_DOWNLOADS,"d1.mp3");

我检查过该文件可以正常下载。现在我想播放这个d1.mp3文件,但是当我按下播放按钮时它不会开始播放音乐!当我使用" setDataSource"时看起来我有问题。如果你检查我的代码并让我在哪里犯了错误,我将不胜感激。

private void initMediaPlayer()
{
    String PATH_TO_FILE = Environment.DIRECTORY_DOWNLOADS + "/d1.mp3";
    mp = new  MediaPlayer();

    try {
        mp.setDataSource(PATH_TO_FILE);
        mp.prepare();
        Toast.makeText(this, PATH_TO_FILE, Toast.LENGTH_LONG).show();
        stateMediaPlayer = stateMP_NotStarter;
        textState.setText("- IDLE -");
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
        stateMediaPlayer = stateMP_Error;
        textState.setText("- ERROR!!! -");
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
        stateMediaPlayer = stateMP_Error;
        textState.setText("- ERROR!!! -");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
        stateMediaPlayer = stateMP_Error;
        textState.setText("- ERROR!!! -");
    }

}

public void play(View view) {
    initMediaPlayer();
    mp.start();           
}

2 个答案:

答案 0 :(得分:0)

您应该使用getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)(对于应用下载)或Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)来获取下载文件的完整路径。

答案 1 :(得分:0)

我知道它来晚了,但是我也遇到了同样的问题,我通过在您的代码中添加一行来解决了它 设置数据源后

mp.setDataSource(PATH_TO_FILE);

添加PrepareAsync

mp.prepareAsync();

这为我解决了这个问题