1

In my app, i want to play sound when a user is moving a tile, i added the following code --

private void moveTile(Tile tile, Cell cell) {
        grid.field[tile.getX()][tile.getY()] = null;
        grid.field[cell.getX()][cell.getY()] = tile;
        tile.updatePosition(cell);

        MediaPlayer mp = null;
        if(mp!=null) {
            mp.release();
        }
        mp = MediaPlayer.create(mContext,R.raw.movetile);
        mp.start();
    }

But whenever i am moving the first tile, the app is not responding, its not crashing also, any help.

Dima Kozhevin
  • 3,602
  • 9
  • 39
  • 52

1 Answers1

0

1) In your code, the if(mp!=null) {mp.release();} should be moved above MediaPlayer mp = null;. Otherwise, it has no purpose (because the condition is always false).

2) Make sure tile.updatePosition(cell) is not the one causing your app to be non-responding.

3) Try this approach instead, it should work:

static MediaPlayer mp = null;

// ...

private void moveTile(Tile tile, Cell cell) {
        grid.field[tile.getX()][tile.getY()] = null;
        grid.field[cell.getX()][cell.getY()] = tile;
        tile.updatePosition(cell);

        try
        {
            if (mp != null)
            {
                if (mp.isPlaying ())
                    mp.stop ();

                mp.reset ();
                mp.release ();
                mp = null;
            }

            mp = MediaPlayer.create (getApplicationContext (), R.raw.movetile);

            if (mp != null)
            {
                mp.start ();
            }
            else
            {
                // Handle the error ...
            }

        } catch (Exception e)
        {
            // Handle the error ...
        }
}
deLock
  • 762
  • 8
  • 16