2015-05-19 112 views
0

請讓我遇到問題,讓仿真器在我的代碼上工作。我有下面的代碼,我希望能夠播放聲音,當我點擊我在模擬器上創建的按鈕,但是每當我運行代碼時,模擬器不會彈出,而是彈出媒體播放器並播放聲音它自己的。請幫忙。有什麼我做錯了嗎?謝謝你的幫助。讓仿真器運行

下面是我的代碼

公共類聲音擴展ActionBarActivity {

MediaPlayer Sound; 
private static Button btnsound; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_sound); 
    Sound = MediaPlayer.create(this, R.raw.coins); 
    playsound(); 
} 

public void playSound (View view) { 
    Sound.start(); 
} 

public void playsound(){ 
    btnsound=(Button) findViewById(R.id.button_sound); 

    btnsound.setOnClickListener(
      new View.OnClickListener(){ 
       @Override 
      public void onClick (View v){ 

        Sound.start(); 

       } 
}); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_sound, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    //noinspection SimplifiableIfStatement 
    if (id == R.id.action_settings) { 
     return true; 
    } 

    return super.onOptionsItemSelected(item); 
} 

}

的activity.xml

<Button 
    android:layout_width="175dp" 
    android:layout_height="wrap_content" 
    android:text="@string/btnsound" 
    android:onClick="playSound" 
    android:id="@+id/button_sound" 
    android:layout_gravity="center_horizontal" 
    android:layout_alignParentTop="true" 
    android:layout_centerHorizontal="true" 

    android:layout_marginTop="154dp" /> 

回答

0

確保聲音播放在它自己的,你有內部onCreate的方法playsound()一個電話,刪除該行並調用按鈕監聽器內部這種方法,使其保持這樣的:

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_sound); 
    Sound = MediaPlayer.create(this, R.raw.coins); 
    btnsound = (Button) findViewById(R.id.button_sound); 

    btnsound.setOnClickListener(
     new View.OnClickListener(){ 
      @Override 
     public void onClick (View v){ 
       playSound(); 
      } 
    }); 
} 
public void playSound() { 
    Sound.start(); 
} 

你聲明和功能有點混亂,小心。

+0

好的。非常感謝。它確實有幫助。我正在逐漸學習。另外,如果我想要有多個聲音,我應該爲每個聲音使用不同的方法,或者我應該做的最好的事情是什麼。 – Shade01

+0

這是一個好主意,在你的情況下,我可能會做同樣的 – codecharles

+0

謝謝。它終於按照它應該的方式工作。 – Shade01