我调试并看到path = /storage/emulated/0/Music/test_cbr.mp3
并测试
mp.setDataSource(path);
和
mp.setDataSource(getApplicationContext(),Uri.parse(path));
但两种方式都会在setDataSource中给出illegalStateException么?
try
{
MediaPlayer mp = new MediaPlayer();
// Uri fileUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, 1834);
// mp.setDataSource(context, fileUri);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.release();
mp.reset();
mp.setDataSource(getApplicationContext(),Uri.parse(path));
// mp.reset();
// mp.setDataSource(context, uri);
mp.prepare();
mp.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
编辑和回答
现在一切正常。我向媒体播放器拼错了mp。现在我纠正它。感谢您的帮助朋友。
答案 0 :(得分:1)
只需尝试我的代码
MediaPlayer mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mp.setDataSource(getApplicationContext(), Uri.parse("path"));
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
答案 1 :(得分:1)
在您的活动类中创建媒体播放器的全局对象:
MediaPlayer mediaPlayer;//global object
String path = "/storage/emulated/0/Music/test_cbr.mp3";
在活动类的oncreate方法中编写以下代码:
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(path);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new OnPreparedListener()
{
@Override
public void onPrepared(MediaPlayer mp)
{
// TODO Auto-generated method stub
mediaPlayer.start();
}
});
我希望这个解决方案可以帮到你。