I'm trying to play .ogg files I have placed in the raw folder by click listener on an imageview.
This method is inside the onCreate of an Activity that extends AppCompatactivity.
Can anyone help me identify what causes the app to crash when I click on the ImageView? And how to do it properly?
ImageView soundButton = (ImageView) this.findViewById(R.id.soundbtn);
soundButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String s = "a"+num+".ogg";
Log.i("mytag", "inside" + s);
Resources res = getApplicationContext().getResources();
int soundID = res.getIdentifier(s, "raw", getApplicationContext().getPackageName());
MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), soundID);
mediaPlayer.start(); // no need to call prepare(); create() does that for you
}
});
Edit:
It is working if I try the normal method:
MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationcontext(), R.raw.a1);
mediaPlayer.start(); // no need to call prepare(); create() does that for you
But I want to play different file based on the num variable.
I used this Android get R.raw from variable for reference.