【问题标题】:Null Pointer Exception when calling mediaPlayer.start() : Android调用 mediaPlayer.start() 时出现空指针异常:Android
【发布时间】:2021-08-28 12:59:16
【问题描述】:

基本上我想要的是允许用户从他们的设备中选择一个音频文件,一旦他们这样做,这个活动就会开始并且音乐/音频文件将被播放。为此,我在我的 Android 清单文件中使用了一个意图过滤器,它工作正常,没有错误。

问题是当我调用mediaPlayer.start() 时,我得到一个空指针异常。从我目前阅读的内容来看,发生这种情况是因为MediaPlayer 无法创建对象或其他东西......MediaPlayer.cretae() 返回 null。

以下是本次活动的全部代码:

public class IntentPlayerActivity extends AppCompatActivity {

    TextView song_name,artist_name;
    ImageView playPauseBtn;
    SeekBar seekBar;

    static Uri uri;
    static MediaPlayer mediaPlayer = new MediaPlayer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intent_player);

        initViews();
        Intent intent = getIntent();
        if (intent.getAction().equals(Intent.ACTION_VIEW)){

            Log.d("Intent Player_Activity:", " File Path: "+ intent.getData().getPath());

            playPauseBtn.setImageResource(R.drawable.ic_pause_circle_outline);
            uri = Uri.parse(intent.getData().getPath());
            Log.d("Intent Player_Activity:", " URI: "+uri.toString());

            if (mediaPlayer != null){
                mediaPlayer.stop();
                mediaPlayer.release();
                mediaPlayer = MediaPlayer.create(getApplicationContext(),uri);
                mediaPlayer.start();
            }else {
                mediaPlayer = MediaPlayer.create(getApplicationContext(),uri);
                mediaPlayer.start();
            }
        }
    }

    private void initViews() {
        song_name = findViewById(R.id.song_name);
        artist_name = findViewById(R.id.song_artist);
        playPauseBtn = findViewById(R.id.play_pause);
        seekBar = findViewById(R.id.seekBar);
    }
}   

我希望有人可以解释MediaPlayer.create() 的剂量以及可能导致它失败的原因,就我而言,我不相信音频文件是无效格式或找不到指定的媒体文件。我认为它是别的东西。

【问题讨论】:

    标签: android audio nullpointerexception android-mediaplayer intentfilter


    【解决方案1】:

    删除:

    uri = Uri.parse(intent.getData().getPath());
    

    改为将intent.getData() 传递给MediaPlayer.create()

    mediaPlayer = MediaPlayer.create(getApplicationContext(),intent.getData());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-01
      • 2019-06-14
      • 1970-01-01
      相关资源
      最近更新 更多