如何在gridview中单击图像时添加声音效果

时间:2013-06-26 06:42:08

标签: android android-gridview android-image

我正在使用包含一些图像的gridview。我想在gridview中单击每个图像时添加声音效果。我在res / raw文件夹中添加了图像并添加了以下代码。

MediaPlayer mp;
gridView.setAdapter(new ImageAdapter(this));

gridView.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView parent, View v,int position,long id) {
        if (position == 0) {
            mp = MediaPlayer.create(this, R.raw.ok);
            Toast.makeText(getBaseContext(),
                 "Shape Matched",
                 Toast.LENGTH_LONG).show();
            startActivity(new Intent("com.example.TestShapeActivity2"));
        } else {
            mp = MediaPlayer.create(this, R.raw.no);
            Toast.makeText(getBaseContext(),
                    "Please Try Again",
                    Toast.LENGTH_LONG).show();
            //startActivity(new Intent("com.example.TestShapeActivity2"));
        }
    }
});

但是create函数给出了错误

The method create(Context, int) in the type MediaPlayer is not applicable for the arguments (new AdapterView.OnItemClickListener(){}, int).

请帮助我。谢谢。

2 个答案:

答案 0 :(得分:1)

将两个电话改为

mp = MediaPlayer.create(this, R.raw.ok);

mp = MediaPlayer.create(TestShapeActivity.this, R.raw.ok);

或您所在活动的名称是什么。

create()需要Context,但当您在this中引用OnItemClickListener时,它指的是听众,而不是活动。

详细了解this关键字here

答案 1 :(得分:0)

也许你应该使用SoundPool,因为它听起来不那么迟钝; 首先声明你的SoundPool:

     private SoundPool soundPool;
     private int sound1;

在onCreate中加载声音:第一个数字设置可以为再现排队的声音数量。

    soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
    sound1 = soundPool.load(context, R.raw.msound, 1);

最后在你的OnClick:

soundPool.play(sound1, 1, 1, 1, 0, 1);

最后一种方法是这样的:play(int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate)这允许您设置它将重现的次数等。

More info

编辑:

grid.setOnItemSelectedListener(new OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> arg0, View v, int pos, long arg3) {
    soundPool.play(sound1, 1, 1, 1, 0, 1); 
    ...

项目点击的内容相同:

grid.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int pos,long arg3) {
    soundPool.play(soundPulsa, 1, 1, 1, 0, 1);
...