0

我对 Android 应用程序开发相当陌生,我正在尝试播放 /res/raw 文件夹中的随机 .mp3。

已修复到目前为止我有这个,但我遇到了 FileNotFoundException。

FIXED仅在第一次单击时播放随机声音,之后除非重新打开应用程序,否则它是相同的声音。

新问题现在播放随机声音,但是当我多次单击该按钮时,声音同时开始播放,并且仍然在日志中收到“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 为空

4

1 回答 1

0

你在这里有几个问题。

首先,调用toString()aField将为您提供对象实例的字符串表示形式,例如"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};

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

于 2013-09-21T23:08:55.903 回答