如何根据在Edittext中输入的文字查找并播放音频文件
How to find and play the audio file according to the text enterd in Edittext
当我输入动物名称并播放动物声音时,我制作的以下代码工作正常,但我如何才能使 200 个声音文件更简单。比如从 edittext 中获取字符串并从原始文件夹中搜索文件并播放。
如果输入的文本是 "dog" 它应该播放 "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();
}
}
}
应用给定的解决方案 here。在某处添加实用方法:
public static int getResourceIdentifierForRawFile(Context context, String fileName) {
final String packageName = context.getPackageName();
final Resources resources = context.getResources();
return resources.getIdentifier(fileName, "raw", packageName);
}
并用它将文件名转换成id值:
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();
当我输入动物名称并播放动物声音时,我制作的以下代码工作正常,但我如何才能使 200 个声音文件更简单。比如从 edittext 中获取字符串并从原始文件夹中搜索文件并播放。 如果输入的文本是 "dog" 它应该播放 "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();
}
}
}
应用给定的解决方案 here。在某处添加实用方法:
public static int getResourceIdentifierForRawFile(Context context, String fileName) {
final String packageName = context.getPackageName();
final Resources resources = context.getResources();
return resources.getIdentifier(fileName, "raw", packageName);
}
并用它将文件名转换成id值:
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();