使用此代码,我想播放声音。我为此调用playSound()方法

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


这只是最重要的代码。但是当它应该播放声音时,我收到了Android运行时错误

怎么了?

最佳答案

代替mainActivity.playSound()行尝试:

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


还要删除新的MainActivity()。不得直接实例化活动

关于java - Android MediaPlayer运行时错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18046843/

10-10 16:03