英文:
Android app closes when trying to play media
问题
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 a different file based on the num
variable.
I used this Android get R.raw from variable for reference.
英文:
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.
专注分享java语言的经验与见解,让所有开发者获益!
评论