选择要与MediaPlayer一起播放的音乐文件

时间:2013-06-11 10:49:37

标签: android media-player android-4.2-jelly-bean

我是Android编程的新手,现在我的应用程序出了问题。我打算使用feature对MediaPlayer应用程序进行编码:使用intent从存储中选择一个文件,然后开始播放该文件。我使用“MediaPlayer.create(context,uri)”方法,但目前我收到了错误

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //openFile();
    Button openFile = (Button) this.findViewById(R.id.ButtonOpen);
    openFile.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent chooseFile;
            Intent intent;
            chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
            chooseFile.setType("file/*");
            intent = Intent.createChooser(chooseFile, "Choose a file");
            startActivityForResult(intent, ACTIVITY_CHOOSE_FILE);

            Uri uri = intent.getData();
            initViews(uri);
        }
    }); 

}

private void initViews(Uri uri) {
    mButtonPlayStop = (Button) findViewById(R.id.ButtonPlayStop);
    mButtonPlayStop.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            buttonClick();
        }
    });

    mMediaPlayer = MediaPlayer.create(this, uri);
}


private void starPlayProgressUpdater() {
    mSeekBar.setProgress(mMediaPlayer.getCurrentPosition());

    if (mMediaPlayer.isPlaying()) {
        Runnable notification = new Runnable() {

            @Override
            public void run() {
                starPlayProgressUpdater();
            }
        };
        mHandler.postDelayed(notification, 1000);
    } else {
        mMediaPlayer.pause();
        mButtonPlayStop.setText(getString(R.string.play_str));
        mSeekBar.setProgress(0);
    }
}

private void buttonClick() {
    if (mButtonPlayStop.getText() == getString(R.string.play_str)) {
        mButtonPlayStop.setText(getString(R.string.pause_str));
        try {
            mMediaPlayer.start();
            starPlayProgressUpdater();              
        } catch (IllegalStateException e) {
            mMediaPlayer.pause();
        }
    } else {
        mButtonPlayStop.setText(getString(R.string.play_str));
        mMediaPlayer.pause();
    }
}

它在“mMediaPlayer = MediaPlayer.create(this,uri);”中抛出NullPointerException。它与uri有问题。有人能帮助我吗?


感谢Ilango j,我修改了我的代码,然后现在我可以选择并播放音乐文件了。但我的预测是选择文件,然后只有在点击播放/暂停按钮(带进度条)后播放,但我得到了新的NullPointerException与我的buttonClick

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mContext = (Context) getApplicationContext();

    Button openFile = (Button) this.findViewById(R.id.ButtonOpen);
    openFile.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {       
            initView();
        }
    }); 

}

private void initView() {
    mButtonPlayStop = (Button) findViewById(R.id.ButtonPlayStop);
    mButtonPlayStop.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            buttonClick();
        }
    });

    Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(intent, 10);

}
    @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == RESULT_OK && requestCode == 10) {
        Uri uri = data.getData();

        mMediaPlayer = MediaPlayer.create(mContext, uri);

        mSeekBar = (SeekBar) findViewById(R.id.SeekBar01);
        mSeekBar.setMax(mMediaPlayer.getDuration());
        mSeekBar.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                seekChange(v);
                return false;
            }
        });         
    }
}   

private void starPlayProgressUpdater() {
    mSeekBar.setProgress(mMediaPlayer.getCurrentPosition());

    if (mMediaPlayer.isPlaying()) {
        Runnable notification = new Runnable() {

            @Override
            public void run() {
                starPlayProgressUpdater();
            }
        };
        mHandler.postDelayed(notification, 1000);
    } else {
        mMediaPlayer.pause();
        mButtonPlayStop.setText(getString(R.string.play_str));
        mSeekBar.setProgress(0);
    }
}

private void seekChange(View v) {
    if (mMediaPlayer.isPlaying()) {
        SeekBar sb = (SeekBar) v;
        mMediaPlayer.seekTo(sb.getProgress());
    }
}

private void buttonClick() {
    if (mButtonPlayStop.getText().equals(getString(R.string.play_str))) {
        mButtonPlayStop.setText(getString(R.string.pause_str));
        try {
            mMediaPlayer.start();
            starPlayProgressUpdater();              
        } catch (IllegalStateException e) {
            mMediaPlayer.pause();
        }
    } else {
        mButtonPlayStop.setText(getString(R.string.play_str));
        mMediaPlayer.pause();
    }
}

你能提出建议吗?

3 个答案:

答案 0 :(得分:7)

首先从SD卡开始播放媒体文件的活动。替换以下代码

Button openFile = (Button) this.findViewById(R.id.ButtonOpen);
    openFile.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
           Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 10);
        }
    }); 

然后在 onActivityResult

中添加以下代码
     @Override
     protected void onActivityResult(int requestCode, int resultCode, Intent data) {

          if(resultCode == RESULT_OK && requestCode == 10){
                Uri uriSound=data.getData();
                play(this, uriSound); 
          }
      }

并调用以下方法创建媒体播放器并播放选定的音频文件。

   private void play(Context context, Uri uri) {

        try {
            MediaPlayer mp = new MediaPlayer();
            mp.setDataSource(context, uri);         
            mp.start();
          } catch (IllegalArgumentException e) {
          // TODO Auto-generated catch block
             e.printStackTrace();
          } catch (SecurityException e) {
          // TODO Auto-generated catch block
             e.printStackTrace();
          } catch (IllegalStateException e) {
          // TODO Auto-generated catch block
             e.printStackTrace();
          } catch (IOException e) {
          // TODO Auto-generated catch block
             e.printStackTrace();
          }
    }

答案 1 :(得分:0)

查看MediaPlayer创建的源代码,如下所示:

public static MediaPlayer create(Context context, Uri uri, SurfaceHolder holder) {

        try {
            MediaPlayer mp = new MediaPlayer();
            mp.setDataSource(context, uri);
            if (holder != null) {
                mp.setDisplay(holder);
            }
            mp.prepare();
            return mp;
        } catch (IOException ex) {
            Log.d(TAG, "create failed:", ex);
            // fall through
        } catch (IllegalArgumentException ex) {
            Log.d(TAG, "create failed:", ex);
            // fall through
        } catch (SecurityException ex) {
            Log.d(TAG, "create failed:", ex);
            // fall through
        }

        return null;
    }

因此,在您的情况下,错误可能是您在参数中传递的URI错误或格式错误,因此create方法返回null。创建mediaPlayer对象时检查URI是否正确。

我也看到了这句话:

if (mButtonPlayStop.getText() == getString(R.string.play_str))

请勿使用==来比较字符串的内容。请改用.equals()

if (mButtonPlayStop.getText().equals(getString(R.string.play_str)))

答案 2 :(得分:0)

如果有人像我一样对这个问题有困难,我对上面的答案做了一些修正,这段代码应该有效:

private  final int SELECT_PICTURE = 1;

public void pickMusic() {
    Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(i,SELECT_MUSIC);
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_MUSIC){
            Uri selectedMusicUri = data.getData();
            if (selectedMusicUri != null){
                String pathFromUri = getRealPathFromURI(this, selectedMusicUri);
                MediaPlayer mp = new MediaPlayer();
                try {
                    mp.setDataSource(this, Uri.parse(pathFromUri));
                    mp.prepare();
                    mp.start();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


private String getRealPathFromURI(Context context, Uri contentUri) {
    String[] projection = { MediaStore.Audio.Media.DATA };
    CursorLoader loader = new CursorLoader(context, contentUri, projection, null, null, null);
    Cursor cursor = loader.loadInBackground();
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}