安卓应用在尝试播放媒体时关闭。

huangapple 未分类评论44阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年4月6日 09:34:09
  • 转载请务必保留本文链接:https://java.coder-hub.com/61051733.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定