开发者

Android MediaPlayer Sound res Problem

开发者 https://www.devze.com 2023-03-19 16:19 出处:网络
I have 40+ sound files in my application. In one of my activities I want to play only one sound file base on the id that come with the Bundle b (id range: 1 - 50). I tried this:

I have 40+ sound files in my application. In one of my activities I want to play only one sound file base on the id that come with the Bundle b (id range: 1 - 50). I tried this:

In onCreate():

    Bundle b = getIntent().getExtras();
    id = (int) b.getInt("id");
    tv.setText("id : "+id); // Just to make sure that I received a correct id
    setResourseId(id);
    mPlayer.start();

the setResourceId():

public void setResourseId(int id) {
    switch(id) {
    case 1:     mPlayer = MediaPlayer.create(this, R.raw.sound1);
    case 2:     mPlayer = MediaPlayer.create(this, R.raw.sound2);
    case 3:     mPlayer = MediaPlayer.create(this, R.raw.sound3);
    case 4:     mPlayer = MediaPlayer.create(this, R.raw.sound4);
    case 5:     mPlayer = MediaPlayer.create(this, R.raw.sound5);
                               .
                               .
                               .
                               .
                               .
    default:    mPlayer = MediaPlayer.create(开发者_Python百科this, R.raw.sound0);
    }
}

However, it always play the sound0 file (the default one) ! It seems strange, since the TextView tv always prints the correct id

-

Any solution for that ?


When you use switch, you need to break after each case, otherwise the next lines will be executed as well, in your case, all lines were executed each time and the last assignment to mPlayer was MediaPlayer.create(this, R.raw.sound2); each time. A short fix - add break after each case:

switch(id) {
    case 1:
        mPlayer = MediaPlayer.create(this, R.raw.sound1);
        break;
    case 2:
        mPlayer = MediaPlayer.create(this, R.raw.sound2);
        break;
    ....
}

As a side note - I would consider using an array of ids and avoiding this long switch case.

0

精彩评论

暂无评论...
验证码 换一张
取 消