无法播放sdcard Android的音频文件

时间:2015-04-20 07:41:15

标签: android nullpointerexception android-mediaplayer

MediaPlayer mPlayer;

String path = /storage/emulated/0/Audio/1429167704744.wav;
mPlayer = new MediaPlayer();
mPlayer = MediaPlayer.create(getActivity(), Uri.parse(path));
mPlayer.start();

日志

04-20 13:04:09.667: E/AndroidRuntime(28202): Process: com.abs_ind.audio, PID: 28202 04-20 13:04:09.667: E/AndroidRuntime(28202): java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference 
04-20 13:04:09.667: E/AndroidRuntime(28202):at com.bb_ind.test.Browse_Fragment.show_dialog(Browse_Fragment.java:71)

当我启动Mediaplayer时,我得到了NullPointerException。我确定文件路径是正确的,文件没有损坏。提前谢谢。

2 个答案:

答案 0 :(得分:1)

尽量不要直接指定路径,使用Environment的帮助程序来获取文件路径。在清单文件中声明权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

然后尝试使用以下代码播放音频文件。

    final String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)
            + File.separator + "1429167704744.wav";

    MediaPlayer mediaPlayer = MediaPlayer.create(this, Uri.parse(path));
    try {
        mediaPlayer.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }
    mediaPlayer.start();

答案 1 :(得分:0)

您可以尝试使用此代码:

MediaPlayer mp = new MediaPlayer(); mp.setDataSource("/mnt/sdcard/yourdirectory/youraudiofile.wav"); mp.prepare(); mp.start();

您是否在清单中添加了以下权限行?

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>