2014-09-11 221 views
1

我试图在我的按钮上播放声音片段点击此链接from Stackoverflow如何在Android中按钮上单击播放声音片段?

现在仍然无法播放声音片段。我在这里是一个简单的按钮的单击事件,它使按钮可以播放声音。任何人都可以帮助我找出这里有什么问题吗?

这里是我使用

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代码提前

回答

2

删除线。

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

<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> 

谢谢如果你播放声音剪辑,然后

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(); 
} 
相关问题