如何匹配android中声音对应的图像?

时间:2011-11-03 06:39:56

标签: android

这是我的java编码..请帮助我..我正在为孩子们做一个项目。

package com.VRG;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Animalsgame extends Activity implements OnClickListener {
    // int answer=0;
    Button voice;
    MediaPlayer mp;
    TextView time;// count down timer
    ImageView img_view1;
    ImageView img_view2;
    ImageView img_view3;
    ImageView img_view4;
    static int index = 0;
    static int index1 = 0;
    static int noOfLapse;
    static int count = 0;
    static boolean isSoundPlay;
    CountDownTimer CountDownTimer;
    int idx;
    Integer next;
    int temp1, temp2;

    private Random random;
    private ArrayList<MediaPlayer> sounds;
    private ArrayList<MediaPlayer> tempSounds;

    final int[] imageViews = { R.id.img_view1, R.id.img_view2, R.id.img_view3,
            R.id.img_view4 };// Array of image views

    int[] Animals_images = { R.drawable.cow, R.drawable.lion, R.drawable.dog,
            R.drawable.sheep, R.drawable.elephant, R.drawable.camel,
            R.drawable.rhinos, R.drawable.horse, R.drawable.donkey,
            R.drawable.wolves }; // Array of Animal images

    String Animals_images_string[] = { "cow", "lion", "dog", "sheep",
            "elephant", "camel" };

    String mfile_sounds_string[] = { "cow", "lion", "dog", "sheep", "elephant",
            "camel" };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.game);

        time = (TextView) this.findViewById(R.id.time);
        img_view1 = (ImageView) this.findViewById(R.id.img_view1);
        img_view2 = (ImageView) this.findViewById(R.id.img_view2);
        img_view3 = (ImageView) this.findViewById(R.id.img_view3);
        img_view4 = (ImageView) this.findViewById(R.id.img_view4);

        img_view1.setOnClickListener(this);
        img_view2.setOnClickListener(this);
        img_view3.setOnClickListener(this);
        img_view4.setOnClickListener(this);

        // Count down timer
        voice = (Button) this.findViewById(R.id.voice);// Animals sounds

        voice.setOnClickListener(this);

        // Initialise Lapse counter
        noOfLapse = 0;
        isSoundPlay = true;

        random = new Random();

        sounds = new ArrayList<MediaPlayer>();
        sounds.add(MediaPlayer.create(this, R.raw.cow));
        sounds.add(MediaPlayer.create(this, R.raw.lion));
        sounds.add(MediaPlayer.create(this, R.raw.dog));
        sounds.add(MediaPlayer.create(this, R.raw.sheep));
        sounds.add(MediaPlayer.create(this, R.raw.elephant));
        sounds.add(MediaPlayer.create(this, R.raw.camel));

        tempSounds = (ArrayList<MediaPlayer>) sounds.clone();

        enableDisableImageView(false);

    }// End of Oncreate method

    public void setDuration(int duration) {

    }

    @Override
    public void onClick(View v) {
        enableDisableImageView(true);

        if (v == img_view1) {

            if (mp != null) {
                if (mp.isPlaying()) {
                    mp.stop();
                }
            }
            count++;
            time.setText("");
            if (CountDownTimer != null) {
                CountDownTimer.cancel();
            }
            enableDisableButton(true);
        }
        if (v == voice) {
            loadImages();
            // answer++;
            freezeButtonAndPlaySoundThenUnfreezeButton();
            countDown();
            // enableDisableButton(true);
        }

        if (v == img_view2) {
            if (mp != null) {
                if (mp.isPlaying()) {
                    mp.stop();
                }
            }
            count++;
            enableDisableButton(true); // Re-enable buttons
        } else if (v == voice) {
            loadImages();
            countDown();
            enableDisableButton(false);
        }

        if (v == img_view3) {
            if (mp != null) {
                if (mp.isPlaying()) {
                    mp.stop();
                }
            }
            count++;
            enableDisableButton(true); // Re-enable buttons
        } else if (v == voice) {
            loadImages();
            countDown();
            enableDisableButton(false);
        }

        if (v == img_view4) {
            if (mp != null) {
                if (mp.isPlaying()) {
                    mp.stop();
                }
            }
            count++;
            enableDisableButton(true); // Re-enable buttons
        } else if (v == voice) {
            loadImages();
            countDown();
            enableDisableButton(false);
        }

        if (count > 4) {
            AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
            setDuration(0);
            mp = MediaPlayer.create(this, R.raw.claps);
            if (mp != null) {
                if (mp.isPlaying()) {
                    mp.stop();
                }
            }
            mp.start();
            Toast.makeText(getApplicationContext(), "Your Score : " + count,
                    Toast.LENGTH_SHORT).show();
            // set the message to display
            alertbox.setMessage("Game Over..! Do you want to play again?");
            // set a positive/yes button and create a listener
            alertbox.setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {

                        // do something when the button is clicked
                        public void onClick(DialogInterface arg0, int arg1) {
                            if (mp != null) {
                                if (mp.isPlaying()) {
                                    mp.stop();
                                }
                            }
                            count = 0;
                            // Intent i = new Intent(VRGActivity2.this,
                            // VRGActivity2.class);
                            // startActivity(i);
                            finish();
                        }
                    });

            // set a negative/no button and create a listener
            alertbox.setNegativeButton("No",
                    new DialogInterface.OnClickListener() {

                        // do something when the button is clicked
                        public void onClick(DialogInterface arg0, int arg1) {
                            if (mp != null) {
                                if (mp.isPlaying()) {
                                    mp.stop();
                                }
                            }
                            finish();
                            // Intent i = new Intent(VRGActivity2.this,
                            // VRGActivity1.class);
                            // startActivity(i);

                        }
                    });

            // display box
            alertbox.show();
            enableDisableButton(false);
        }
    }// End of voice on click

    private void countDown() {

        CountDownTimer = new CountDownTimer(6000, 10000) {

            public void onTick(long millisUntilFinished) {
                if (isSoundPlay) {
                    // freezeButtonAndPlaySoundThenUnfreezeButton();
                    isSoundPlay = false;
                }
                time.setText("" + "" + millisUntilFinished / 10000);

            }

            public void onFinish() {

                // time.setText("UP");
                setDuration(0);
                // Toast.makeText(getApplicationContext(), "Time Up",
                // Toast.LENGTH_SHORT).show();

                isSoundPlay = true;

            }// End of on finish
        }.start(); // End of countDown Constructor
    }// End of countDown method

    public void enableDisableButton(Boolean state) {
        voice.setEnabled(state);

    }

    public void enableDisableImageView(Boolean state) {
        img_view1.setEnabled(state);
        img_view2.setEnabled(state);
        img_view3.setEnabled(state);
        img_view4.setEnabled(state);
    }

    private void loadImages() {
        // img_view1.setImageResource(Compulsory_Animals_images[answer]);

        Random rng = new Random(); // Random function
        List<Integer> generated = new ArrayList<Integer>();
        for (int i = 0; i < 4; i++) {
            while (true) {
                next = rng.nextInt(9);
                index = next;
                if (!generated.contains(next)) {
                    generated.add(next);
                    ImageView iv = (ImageView) findViewById(imageViews[i]);
                    iv.setImageResource(Animals_images[next]);

                    break;
                }// End of if
            }// While loop
        }// End of for loop
    }

    public void freezeButtonAndPlaySoundThenUnfreezeButton() {
        enableDisableButton(false); // disable buttons
        int randomInt = random.nextInt(tempSounds.size());
        mp = tempSounds.get(randomInt);

        // Toast.makeText(getApplicationContext(), "Index: "+sound_index,
        // Toast.LENGTH_SHORT).show();
        temp1 = randomInt;
        temp2 = temp1;
        tempSounds.remove(randomInt);
        temp1 = temp2;
        mp.seekTo(0);
        mp.start();
        mp.setOnCompletionListener(new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mpalmost) {
                // mpalmost.release();
            }
        });

    }

    @Override
    // while back pressed the task is refreshed
    public void onBackPressed() {
        Log.v("44444", "onBackPressed Called");
        if (mp != null) {
            if (mp.isPlaying()) {
                mp.stop();
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        // saveState();
        Log.v("11111111", "onPause Called");

    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.v("111111", "onStart Called");

    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.v("222222", "onResume Called");

        // freezeButtonAndPlaySoundThenUnfreezeButton();

    }

    @Override
    // if key down happens
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        {
            Log.d("333333", "onKeyDown Called");
            onBackPressed();
            finish();
            // calling the OnBackpressed method called
        }

        return true;
    }

}// }

我正在使用四个图像视图和一个声音按钮。  如果我点击声音按钮随机声音  得到提升,突然四个图像视图将  由四个随机获得的图像填充。  现在我必须匹配声音对应的声音。

1 个答案:

答案 0 :(得分:0)

当我说哈希时,我并不是说你必须设置一个哈希映射。这不是一个轻量级的解决方案。 “要哈希”意味着您必须在这两个值组之间建立关系。在Android中,每个资源都使用类R中的ID进行编译。您可以使用两个int []变量.I.e:

//keeps the element at the same position matching.
final int[] animals = new Int[]{R.drawable.cow, R.drawable.lion, ...};
final int[] sounds = new Int[] {R.raw.cow,R.raw.lion, ...};

当孩子按下按钮时,你会得到一个随机的声音文件ID。即

int index = new Random.nextInt(0,TOTAL_RESOURCE_NUMBER);

现在播放声音,“MediaPlayer.create(声音[索引]);” 将正确的imageView链接到此索引。 int imageIndex = new Random(0,4); imageViews[imageIndex].setDrawable(animals[index]);

现在您知道带有imageIndex的imageView是我们想要的imageView,您可以查看。