Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/200.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
单击android,从文件夹中随机播放音乐_Android_Audio - Fatal编程技术网

单击android,从文件夹中随机播放音乐

单击android,从文件夹中随机播放音乐,android,audio,Android,Audio,我有更改按钮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

我有更改按钮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

            }
        }
    }
我想要的是在点击该按钮时播放随机音乐,而不仅仅是播放指定的音乐。(在这一行中,final 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
}