有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java安卓:OnClick随机播放。mp3来自/res/raw文件

我对安卓应用程序开发还比较陌生,我正在尝试一个随机的游戏。从/res/raw文件夹下载mp3

修复了到目前为止,我已经解决了这个问题,但是我遇到了一个FileNotFoundException

已修复仅在第一次单击时播放随机声音,之后播放相同的声音,除非重新打开应用程序

新发行的现在播放随机声音,但当我多次单击按钮时,声音同时开始播放,并且仍然会在日志中看到“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) 个答案

  1. # 1 楼答案

    你这里有一些问题

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

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

    第三,反思是缓慢的。请不要这样做超过一次。使用R.raw.class.getFields()一次,缓存结果。或者,更好的是,不要考虑使用反射,而是使用你自己的文字java ^ {< CD12>}:

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

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