2013-08-04 160 views
0

使用此代碼我想播放聲音。我把它Android MediaPlayer運行時錯誤

public class MainActivity extends Activity 
{ 
private MediaPlayer cPiano; 
/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(new GameView(this)); 
} 
public void playSound(){ 
    cPiano = MediaPlayer.create(this, R.raw.cpiano); 
    cPiano.start(); 
    } 
} 

public class GameView extends SurfaceView 
{ 
private SurfaceHolder surfaceHolder; 
private MainActivity mainActivity 

public GameView(Context context) 
{ 
    super(context); 
    mainActivity = new MainActivity(); 
    } 

    @Override 
protected void onDraw(Canvas canvas) 
{ 
    for (Pixel pixel : pixelList) 
    { 
     pixel.onDraw(canvas); 
    } 
    for (int i = pixelList.size() - 1; i >= 0; i--) 
    { 
     Pixel pixel = pixelList.get(i); 
     if (pixel.isBar()) 
     { 
      mainActivity.playSound(); 
      removePixel(i); 
      break; 
     } 
    } 
} 

這僅僅是最重要的代碼playSound()方法。但是,當它應該播放聲音我得到一個Android運行時錯誤

什麼是錯的?

+0

刪除這個'mainActivity = new MainActivity()'你可以在gameview中啓動你的媒體播放器,因爲你有活動上下文。 – Raghunandan

+0

好的,但我仍然得到錯誤。 LogCat說onDraw()會出問題 – Stupe

回答

1

相反mainActivity.playSound()行試試:

MainActivity host = (MainActivity)getContext(); 
host.playSound(); 

同時刪除新MainActivity()。一個活動不能直接實例化

+0

它的作品非常感謝你。 – Stupe