Android Audio Question
I have several audio files in the res/raw folder. When I run the following code I was assuming开发者_开发知识库 that just the "sound1" file would be played, instead all of the files in the folder get played one after another, not just "sound1".
MediaPlayer mp = MediaPlayer.create(this, R.raw.sound1);
try {
mp.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
What am I missing? Thanks for any help!
You can try this way.
static MediaPlayer mpBackground = new MediaPlayer();
mpBackground = MediaPlayer.create(this, R.raw.music);
mpBackground.start();
Use SoundPool instead if they are short sound clips... I ran into alot of issues using the Mediaplayer for playing short sounds. I store my sounds in the assets folder instead of res/raw... but you can get the same results. Here is some code.
private int BUZZ = sound_load("sounds/buzz.mp3");
private SoundPool _sounds = new SoundPool(8, AudioManager.STREAM_MUSIC, 0);
private int sound_load(String fname) {
AssetManager am = getAssets();
try {
AssetFileDescriptor fd = am.openFd(fname);
int sid = _sounds.load(fd.getFileDescriptor(), fd.getStartOffset(),
fd.getLength(), 1);
return sid;
} catch (IOException e) {
}
return 0;
}
private void sound_play(int sid) {
_sounds.play(sid, (float) 1.0, (float) 1.0, 0, 0, (float) 1.0);
}
Then to play a sound I just call it like this:
sound_play(BUZZ);
精彩评论