Stupe
Stupe

Reputation: 83

Android MediaPlayer Runtime Error

With this code I want to play a sound. I call the playSound() method for it

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

This is only the most important code. But when it should play the sound I get an Android Runtime Error

What is wrong?

Upvotes: 0

Views: 113

Answers (1)

Alexandru Circus
Alexandru Circus

Reputation: 5538

Instead of mainActivity.playSound() line try:

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

Also remove new MainActivity(). An activity must NOT be directly instantiated

Upvotes: 1

Related Questions