2

我有这个非常基本的应用程序,它有 1 个按钮和 X 个语音文件。语音文件位于 raw/ 下的 res/ 文件夹中。

点击按钮后,我希望应用程序播放随机语音文件。这是我到目前为止所拥有的:

Button playNasr = (Button) findViewById(R.id.button1);
    playNasr.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {
            rand = randomGenerator.nextInt(6) + 1;
            // here's where I'm at a loss, I want to be able to concatenate
            // the random number to the "voice00" string to form
            // "voice001/2/3/etc..." in correspondence to how my voice files
            // are named.
            mp = MediaPlayer.create(Main.this, R.raw.voice00) + rand;
            mp.start();
        }
    });

任何帮助表示赞赏,在此先感谢

4

1 回答 1

2

你应该尝试这样的事情:

String voiceStr = "voice00";
MediaPlayer mp = new MediaPlayer();
Resources res = getResources();
String pkgName = getPackageName();

playNasr.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        rand = randomGenerator.nextInt(6) + 1;
        // "voice00x"
        String id = voiceStr + rand;
        // Get raw resource ID
        int identifier = res.getIdentifier(id, "raw", pkgName);
        AssetFileDescriptor afd = res.openRawResourceFd(identifier);

        // Reuse MediaPlayer or else you will exhaust resources
        mp.reset();
        mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength();
        mp.prepare();
        mp.start();
    }
}

这样您就可以重用您的MediaPlayer实例(如果您还没有遇到错误,请尝试反复点击您的按钮 - 您最终收到错误)并且可以动态设置数据源。您可能希望对其进行优化以将整数格式化为“001”、“001”等,并且也能够处理“010”,但我只是为了示例而对其进行了硬编码。

于 2012-10-22T19:24:56.060 回答