how to play a sound in android
I am creating a scramble word game application which plays two sounds depending on the success or failure. On the success of the guess, the game plays one sound file. On the failure of the guess, the game plays another sound file. I 've written the following code
public void checkWord()
{
MediaPlayer mp;
if(abcd.equals(etGuessedWord.getText().toString()))
{
WordLibrary.setMyInt(WordLibrary.getMyInt() + 10);
tvScore.setText(String.valueOf(WordLibrary.getMyInt()));
new AlertDialog.Builder(JumbledWords.this).setMessage("Awesome!!!")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
wordIdx = (wordIdx + 1) % getSize();
sWord = getScrambledWord(word_list[wordIdx]);
tvScrambledWord.setText(sWord);
abcd = word_list[wordIdx];
++word_array_length;
etGuessedWord.setText("");
if(word_array_length >= word_list.length)
{
new AlertDialog.Builder(JumbledWords.this).setMessage("Level Complete!!! ")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
start = 0;
finish();
}
}).create().show();
}
}
}).create().show();
**mp = MediaPlayer.create(this, R.raw.clap);**
mp.start();
}
else
{
new AlertDialog.Builder(JumbledWords.this).setMessage("Wrong. Try Again")
.setPositiveBut开发者_StackOverflow社区ton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
etGuessedWord.setText("");
}
}).create().show();
**mp = MediaPlayer.create(this, R.raw.oop);**
mp.start();
}
}
The code mp = MediaPlayer.create(this,R.raw.oop) gives exception. I have done my my best to avoid exception such as IOException. The application halts in between and gives a "Force Close". What is wrong with the code? Is there any other way of programming to load the sound? Please help me.
The problem is the context you are using to create the object, "this" is an activity context and under certain conditions, does not contain references to raw objects. I had the same problem which I solved by using the application context instead of the activity context.
Try changing your create code to the following:
Context appContext = getApplicationContext();
mp = MediaPlayer.create(appContext, resid);
I'm usually using SoundPool
for playing sounds, it's more comfortable for me. You can check this link: Sound Pool
Good luck!
Make sure the sound file you're trying to play has the proper extension (e.g. clap.wav
).
精彩评论