我有一个非常基本的应用程序,有 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();
}
});
感谢任何帮助,提前致谢
最佳答案
你应该尝试这样的事情:
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”,但我只是在示例中对其进行了硬编码。
关于android - 单击时播放随机语音文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13018161/