当用户点击选项菜单项时,只想播放一次音频

时间:2012-07-05 16:38:49

标签: android

我想在点击选项菜单项时只播放一次音频。当用户下次点击相同的项目时,音频将停止我想,但无法找到任何解决方案帮助我解决我的问题。这是我的代码。当用户交替点击该项目时,音频将播放并交替停止。

public boolean onCreateOptionsMenu(Menu menu) 
{
    // TODO Auto-generated method stub
    MenuInflater menuInflater= getMenuInflater();
    menuInflater.inflate(R.menu.menu, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    if (item.getItemId()== R.id.item1)
    {
        Intent intent = new Intent(AthravaShirshaActivity.this, EnglishExpln.class);
        startActivity(intent);
    }
    if(item.getItemId()== R.id.item2)
    {
        MediaPlayer mp= MediaPlayer.create(AthravaShirshaActivity.this, R.raw.mantra);
        mp.start();
        mp.setLooping(false);
        mp.setOnCompletionListener(new OnCompletionListener() 
        {
            @Override
            public void onCompletion(MediaPlayer mp)
            {
                mp.stop();
            }
        });
        item.setIcon(android.R.drawable.ic_media_pause);
    }
    return true;
} 

1 个答案:

答案 0 :(得分:0)

您可以将mp公开并在onCreate()MediaPlayer mp= MediaPlayer.create(AthravaShirshaActivity.this, R.raw.mantra);

中初始化

现在在onOptionsItemSelected

if(mp.isPlaying())
         {
             mp.stop();
         mp=null;
             item.setIcon(android.R.drawable.ic_media_play);
         }
         else
         {
                    mp= MediaPlayer.create(AthravaShirshaActivity.this, R.raw.mantra);
            mp.start();
                mp.setLooping(false);
                mp.setOnCompletionListener(new OnCompletionListener() 
                {
                    @Override
                    public void onCompletion(MediaPlayer mp)
                    {
                        mp.stop();
                    }
                });
                item.setIcon(android.R.drawable.ic_media_pause);
         }