Android Mediaplayer空指针异常(Java)

huangapple go评论94阅读模式
英文:

Android Mediaplayer Null point Exception (Java)

问题

尝试使用给定的 URI 创建 MediaPlayer 会导致 NullpointerException

Uri uri = Uri.parse(path);

// 使用给定歌曲的 URI 创建 MediaPlayer
if (mediaPlayer != null) {
    mediaPlayer.stop();
    mediaPlayer.release();
}
mediaPlayer = MediaPlayer.create(this, uri);

try {
    // 设置 MediaPlayer 监听器
    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            seekBar.setMax(mp.getDuration());
            mediaPlayer.start();
            changeSeekbar();
        }
    });
} catch (Exception e) {
    Log.e("ERROR", e.toString());
}

给定的 Logcat

2020-04-07 22:21:05.289 12237-12237/com.example.musicappresearch2 E/Path: /storage/emulated/0/Music/Alone - Viren.mp3
2020-04-07 22:21:05.289 12237-12237/com.example.musicappresearch2 E/ERROR: java.lang.NullPointerException: 尝试调用空对象引用的 'void android.media.MediaPlayer.setOnPreparedListener(android.media.MediaPlayer$OnPreparedListener)' 方法


您能告诉我我做错了什么吗谢谢
英文:

I am trying to create Mediaplayer session with given uri. but it causes NullpointerException.

    Uri uri = Uri.parse(path);

    // Creating MediaPlayer with given song's URI
    if (mediaPlayer != null) {
        mediaPlayer.stop();
        mediaPlayer.release();
    }
    mediaPlayer = MediaPlayer.create(this, uri);

    try {
        // Setting the MediaPlayer Listener
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                seekBar.setMax(mp.getDuration());
                mediaPlayer.start();
                changeSeekbar();
            }
        });
    } catch (Exception e) {
        Log.e("ERROR", e.toString());
    }

Given Logcat:

2020-04-07 22:21:05.289 12237-12237/com.example.musicappresearch2 E/Path: /storage/emulated/0/Music/Alone - Viren.mp3
2020-04-07 22:21:05.289 12237-12237/com.example.musicappresearch2 E/ERROR: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.setOnPreparedListener(android.media.MediaPlayer$OnPreparedListener)' on a null object reference

Could you Tell me What i am doing wrong ? Thanks.

答案1

得分: 1

有两种方法可以编写这段代码,都在设备上经过测试。

首先,请确保正确处理 android.permission.READ_EXTERNAL_STORAGE 权限,并且确实拥有正确的 Uri。
如果上下文(context)或 Uri 无效,MediaPlayer.create(this, uri); 将会失败。

MediaPlayer.create(this, uri); 本身已经准备好了播放器,因此在这种情况下不需要使用 .prepareAsync()。您的代码可以直接运行。

另一种方法:

    mediaPlayer = new MediaPlayer(); // 因此,我们不使用 .create,手动实例化
    try {
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setDataSource(this, uri);
        mediaPlayer.setOnPreparedListener(mp -> {
            mediaPlayer.start();
        });

        /* 如果您不想阻塞 UI 线程,可以使用异步方式
         请注意,这应该在设置监听器之后调用
         因为它可能会在监听器设置之前准备好 */
        mediaPlayer.prepareAsync(); 
    } catch (Exception e) {
        Log.e("ERROR", e.toString());
    }
英文:

There are two ways to write this code, both tested on the device

First of all, make sure you handle android.permission.READ_EXTERNAL_STORAGE correctly and you really have correct Uri.
MediaPlayer.create(this, uri); will fail if either context or uri are invalid.

MediaPlayer.create(this, uri); which itself already prepares player so you don't need .prepareAsync() in this situation. and your code is good to go.

another way:


    mediaPlayer = new MediaPlayer(); // hence, we don't use .create, manually instantiate
    try {
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setDataSource(this, uri);
        mediaPlayer.setOnPreparedListener(mp -> {
            mediaPlayer.start();
        });

        /* use async, if you don't want to block UI thread
         keep in mind, this should be called after setting listener  
       because it might prepare even until the listener has been set */
        mediaPlayer.prepareAsync(); 
    } catch (Exception e) {
        Log.e("ERROR", e.toString());
    }

答案2

得分: 0

请尝试这样做:

Uri uri = Uri.parse(path);

mediaPlayer = new MediaPlayer();
try {
   // mediaPlayer.setDataSource(String.valueOf(uri));
   mediaPlayer.setDataSource(MainActivity.this, uri);
} catch (IOException e) {
    e.printStackTrace();
}
try {
    mediaPlayer.prepare();
} catch (IOException e) {
    e.printStackTrace();
}
mediaPlayer.start();
英文:

Try this :

            Uri uri = Uri.parse(path);

        mediaPlayer = new MediaPlayer();
        try {
           // mediaPlayer.setDataSource(String.valueOf(uri));
           mediaPlayer.setDataSource(MainActivity.this,uri);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            mediaPlayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mediaPlayer.start();

huangapple
  • 本文由 发表于 2020年4月8日 02:24:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/61086827.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定