My code tries to play an MP3 file from res/raw.
Code:
FileDescriptor fd = appContext.getResources().openRawResourceFd(R.raw.ringtone)
.getFileDescriptor();
player = new MediaPlayer();
try
{
player.setAudioStreamType(AudioManager.STREAM_RING);
player.setDataSource(fd);
player.prepare();
}
catch (IllegalArgumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
player = null;
return;
}
catch (IllegalStateException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
player = null;
return;
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
player = null;
return;
}
player.setLooping(true);
player.start();
The log shows:
02-21 15:18:18.360: ERROR/PlayerDriver(51): Command PLAYER_SET_DATA_SOURCE completed with an error or info PVMFErrNotSupported 02-21 15:18:18.380: ERROR/MediaPlayer(693): error (1, -4) 02-21 15:18:18.390: WARN/PlayerDriver(51): PVMFInfoErrorHandlingComplete
After player.prepare() is called.
I really don't have a hint. I won't use MediaPlayer.create() because I need player.setAudioStreamType(AudioManager.STREAM_RING );
Would appreciate any help on 开发者_C百科this...
From the MediaPlayer
API docs:
When a
MediaPlayer
object is just created using new or afterreset()
is called, it is in the Idle state; and afterrelease()
is called, it is in the End state. Between these two states is the life cycle of theMediaPlayer
object.It is a programming error to invoke methods such as
getCurrentPosition()
,...
,setAudioStreamType(int)
in the Idle state.
You should study the MediaPlayer
lifecycle diagram and provided examples and rewrite your code with respect to them. In this case, you see you need to call setDataSource()
before setAudioStreamType()
.
Side note: In Android, you really need to follow the lifecycle events for everything you do, or you'll get bitten. You can write incorrect code and you'll never know until runtime, or worse you might write code you think works and you'll only discover in weird circumstances that it doesn't... e.g. the screen orientation changes and the callback method is not the same in this case, or other similar situations (Home button...etc).
I had similar trouble trying to set the Audio Stream Type and I found this guide helpful: API gaps: an Android MediaPlayer example
精彩评论