The below code I made works fine when I type the animal-name and it plays the animal sound but how can I make it simpler for 200 sound files. like getting the string from edittext and searching the file from raw folder and play. If entered text is "dog" it should play "dog.mp3"
editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
{
String name = editText.getText().toString();
if(name.contentEquals("cow")){
mp = MediaPlayer.create(Selection1Page1.this, R.raw.cow);
mp.start();
}
if(name.contentEquals("bat")){
mp = MediaPlayer.create(Selection1Page1.this, R.raw.bat);
mp.start();
}
if(name.contentEquals("cat")){
mp = MediaPlayer.create(Selection1Page1.this, R.raw.cat);
mp.start();
}
}
}
Apply the solution given here. Add a utility method somewhere:
public static int getResourceIdentifierForRawFile(Context context, String fileName) {
final String packageName = context.getPackageName();
final Resources resources = context.getResources();
return resources.getIdentifier(fileName, "raw", packageName);
}
And use it to convert the name of a file into an id value:
final String fileName = editText.getText().toString();
final int fileResId = getResourceIdentifierForRawFile(this, fileName);
//"this" assumes you are inside a class that inherits from Context, i.e. an Activity
MediaPlayer.create(this, fileResId).start();