从onclick android的文件夹中随机播放音乐



我有一段代码,用于更改按钮onclick的图像,然后在3秒后将其恢复。点击时也会播放声音。

    package com.example.btn;
    import android.app.Activity;
    import android.media.MediaPlayer;
    import android.os.Bundle;
    import android.os.Handler;
    import android.view.View;
    public class MainActivity extends Activity {
        Handler mHandler; // global instance
        Runnable your_runnable; // global instance
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
        public void yolo(final View view) {
            if (view == view) {
                view.setBackgroundResource(R.drawable.btn1);//Change to this when clicked
                final MediaPlayer mp1=MediaPlayer.create(getBaseContext(), R.raw.z);//this mp3 is compulsary
                final MediaPlayer mp1=MediaPlayer.create(getBaseContext(), R.raw.r);//this mp3 should be random
                mp1.start();   //play mp3
                mHandler = new Handler();
                your_runnable = new Runnable() {
                    @Override
                    public void run() {
                        view.setBackgroundResource(R.drawable.btn2);//Revert back to this after timer
                    }
                };
                mHandler.postDelayed(your_runnable, 3000L);// 3sec timer
            }
        }
    }

我想要的是当点击该按钮时随机播放音乐,而不仅仅是播放指定的音乐。(在这一行中,最终MediaPlayer mp1=MediaPlayer.create(getBaseContext(),R.raw.R)//这个mp3应该是随机的)

我认为有两种方法可以做到这一点,1.随机播放特定文件夹中的音乐。2.通过代码从指定的音乐中随机播放音乐。

请帮我做这个。

将所有音乐资源的id放在一个数组中,然后随机选择一个来播放,如下所示:

int[] arr = new int[]{R.raw,x, R.raw.y};
public void someFunc() {
    Randome r = new Random(arr.length);
    MediaPlayer mp = MeadiaPlayer.create(getbaseContext(), arr[r.nextInt()]);
    //your rest code
}

最新更新