【问题标题】:Playing sound after click on imageview/button单击图像视图/按钮后播放声音
【发布时间】:2023-03-28 09:56:01
【问题描述】:

我试图在图像(ImageView/Button)点击时播放点击声音,我看到了一个example here。我也试过用这个:

profile_pick.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            v.playSoundEffect(android.view.SoundEffectConstants.CLICK);
            Intent i=new Intent(getApplicationContext(),Profile_pic.class);
            startActivity(i);
            overridePendingTransition(R.anim.animation,R.anim.animation2);
        }
    });

但它不起作用。谁能建议如何做到这一点?

(添加原始声音不是一个好主意,所以我更喜欢使用使用系统声音...)

【问题讨论】:

    标签: android click


    【解决方案1】:

    将 android:soundEffectsEnabled="true" 添加到 profile_pick 。文档说

    只有在启用音效时才会播放音效 用户,并且 isSoundEffectsEnabled() 为真。

    所以这两个条件都是强制性的。 Here你可以找到文档

    【讨论】:

    • @dev_android 我也有同样的问题。如果你解决了这个问题,请发布你的答案谢谢!。
    【解决方案2】:
    profile_pick.setOnClickListener(new OnClickListener() {
    
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
    
            AudioManager audioManager = 
            (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
            audioManager.playSoundEffect(SoundEffectConstants.CLICK); 
            Intent i=new Intent(getApplicationContext(),Profile_pic.class);
            startActivity(i);
            overridePendingTransition(R.anim.animation,R.anim.animation2);
        }
    });
    

    【讨论】:

      【解决方案3】:

      首先,您需要将语句放在一个块中,在本例中是 onCreate 方法。

      之后,将按钮初始化为变量 1,然后使用变量 0 并将其 onClickListener 设置为不完整的 onClickListener。为 setOnClickListener 使用变量一。

      最后,把播放声音的逻辑放到onClick里面。

      import android.app.Activity;
      import android.media.MediaPlayer;
      import android.os.Bundle;
      import android.view.View;
      import android.view.View.OnClickListener;
      import android.widget.Button;
      
      public class BasicScreenActivity extends Activity {
          @Override
          protected void onCreate(Bundle savedInstanceState) {        
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_basic_screen);
      
              Button one = (Button)this.findViewById(R.id.button1);
              final MediaPlayer mp = MediaPlayer.create(this, R.raw.soho);
              one.setOnClickListener(new OnClickListener(){
      
                  public void onClick(View v) {
                      mp.start();
                  }
              });     
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-22
        • 1970-01-01
        • 1970-01-01
        • 2012-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多