2013-06-26 51 views
1

我正在使用包含一些圖像的gridview。我想在點擊gridview中的每個圖像時添加聲音效果。我在res/raw文件夾中添加了圖像並添加了以下代碼。如何添加聲音效果點擊gridview中的圖像

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")); 
     } 
    } 
}); 

但創建函數給出了錯誤

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

請幫me.Thank你。

回答

1

更改兩次調用

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

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

或任何你在活動的名稱是。

create()需要Context但是當您在OnItemClickListener內引用this時,它指的是偵聽器,而不是活動。

瞭解更多關於this關鍵字here

+0

謝謝。錯誤消失了,但我聽不到任何聲音。 –

+0

你也應該通過調用'.start()' –

+0

它啓動媒體播放器。我錯過了.start() –

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); 
... 
+0

謝謝。但它會在圖像或gridview的情況下工作?我使用onItemClickListener和onItemClick ... Neron T –

+0

我用它在25個圖像的GridView中,它工作正常。發佈瞭如何在我的回答中調用(編輯) –