我正在使用包含一些图像的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).
请帮助我。谢谢。
答案 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)
这允许您设置它将重现的次数等。
编辑:
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);
...