Android:OnClick从/ res / raw文件中随机播放.mp3

时间:2013-09-21 22:48:23

标签: java android android-mediaplayer filenotfoundexception

我是Android应用程序开发的新手,我正在尝试从/ res / raw文件夹中随机播放.mp3。

FIXED 到目前为止,我有这个,但我遇到了FileNotFoundException。

FIXED 仅在第一次点击时播放随机声音,之后声音相同,除非重新打开该应用。

NEW ISSUE 现在播放随机声音,但是当我多次单击该按钮时,声音会同时开始播放,并且仍然会在日志中显示“start()mUri is null”消息。

更新代码

MediaPlayer player;
int soundIndex;
AssetFileDescriptor descriptor;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

}


/**
 * gets a random index from an array of sounds
 * 
 * @return
 */
public int getRandomSoundIndex(){

    int soundIndex;
    int[] sound = SOUNDZ;

    Random random = new Random();
    soundIndex = random.nextInt(sound.length);

    return sound[soundIndex];
}

/**
 * Plays that random sound on button click
 * @param button
 */
public void playRandomSound(View button){

    //where button is physically located
    button = (Button) findViewById(R.id.button1);

    //get random sound index
    soundIndex = getRandomSoundIndex();

    //make media player
    player = MediaPlayer.create(this, soundIndex);

    //play sound
    player.start();

}

这是日志:


09-21 17:42:32.528:D / MediaPlayer(4282):start()mUri为空

1 个答案:

答案 0 :(得分:0)

这里有一些问题。

首先,在toString()上调用Field将为您提供对象实例的字符串表示形式,例如"public static final int com.lena.button.R$raw.laptopkeyboard1",这不是很有用。据推测,您需要getInt()

其次,原始资源不是资产,因此您不使用openFd()。相反,请使用静态create()方法创建MediaPlayer个实例,并在int上传递getInt() Field

第三,反思很慢。请不要多做一次。使用R.raw.class.getFields() 一次,缓存结果。或者,更好的是,考虑根本不使用反射,而是使用您自己的文字Java int[]

static int[] SOUNDZ={R.raw.boom, R.raw.chaka, R.raw.laka};

(当然,用你自己的声音资源代替)