2014-09-11 124 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(); 
}