2011-08-23 156 views
0

我想爲我創建的動畫添加聲音。每次動畫開始時,都應該開始播放聲音,但我無法開始播放聲音。Android,無法讓MediaPlayer類正常工作

一切正常與動畫,這裏的代碼塊:

public class TestActivity extends Activity { 
AnimationDrawable anim; 
MediaPlayer mp; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    playAnimation(R.id.frameLayout1,R.drawable.anim2,R.raw.bang); 
} 

public void playAnimation(int FrameLayoutAddress, int animationXMLAdress, int soundAddress) 
{ 
    mp = MediaPlayer.create(this.getApplicationContext(), soundAddress); 
    mp.start(); // error here 

    FrameLayout imgView = (FrameLayout)findViewById(FrameLayoutAddress); 
    imgView.setBackgroundResource(animationXMLAdress); 
    anim = (AnimationDrawable) imgView.getBackground(); 
    imgView.post(new Runnable() 
    {  
     @Override 
     public void run() 
     { 
      anim.start(); 

     } 
    });  
} 

}

任何人都可以指出我的錯誤?在此先感謝您的時間。

+0

你得到了什麼錯誤? – Asahi

+1

@Pumpkin:如果'create(...)'失敗,則mp將爲'null' - 在嘗試調用'start()'之前檢查以確保它不爲空。 R.raw.bang是有效聲音文件的有效資源ID嗎? – Squonk

回答

1

您應該在mp.start()之前致電mp.prepare()。建議在致電mp.prepare()之前重置MediaPlayer