【问题标题】:How to play a sound clip on a button click in android?如何在android中单击按钮播放声音剪辑?
【发布时间】:2014-09-11 19:19:50
【问题描述】:

我试图在我的按钮上播放声音片段,点击此链接from Stackoverflow

到现在,我还是无法成功播放声音片段。我这里有一个简单的按钮单击事件,它使按钮能够播放声音。谁能帮我找出这里出了什么问题?

这是我正在使用的按钮点击监听器

MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final Button btn = (Button)findViewById(R.id.button1);
    btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            mp = MediaPlayer.create(MainActivity.this, R.raw.sc);
            mp.setLooping(true);
            mp.start();
            btn.setSoundEffectsEnabled(true);
            mp.release();
        }
    });
}

这里是 XML 代码

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:soundEffectsEnabled="true"
        android:layout_marginTop="41dp"
        android:text="Button" />

</RelativeLayout>

提前致谢

【问题讨论】:

    标签: android button onclick media-player audio


    【解决方案1】:

    删除线。

    mp.release();
    

    习惯了。

    Releases resources associated with this MediaPlayer object. 
    It is considered good practice to call this method when you're done 
    using the MediaPlayer
    

    【讨论】:

      【解决方案2】:

      如果你播放声音剪辑,那么

          MediaPlayer mp = MediaPlayer.create(this, R.raw.buttonclick);
          mp.setLooping(true);
          mp.setOnCompletionListener(this);
          mp.start();
      

      试试这个,你实现方法

      @Override
      public void onCompletion(MediaPlayer mp) {
          mp.stop();
          mp.release();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-07
        • 1970-01-01
        • 2014-12-19
        • 1970-01-01
        • 2016-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多