-1

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

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;
} 
4

1 回答 1

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);
         }
于 2012-07-05T16:46:53.770 回答