Search code examples
touch-eventlive-wallpaperaudio

Live Wallpaper onTouchEvent ACTION_DOWN only play 1/3 of a sound clip


I just made a Fish Aquarium Live Wallpaper and wanted to add a sound effect when user touches a moving fish. Unfortunately, I have no idea how to make it because only one third of the sound clip was played. Grateful if some experts can help. Here below are my code:

@Override
public void onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {

Region region1 = new Region(image1x, image1y, image1x+image1.getWidth(),
image1y+image1.getHeight());


if(region1.contains((int)event.getX(), (int)event.getY()))
{image1x=(int) (event.getX()+60);   

MediaPlayer myplayer = MediaPlayer.create(getBaseContext(), R.raw.hi);
myplayer.setVolume(100, 100);

myplayer.start();               
}

Region region2 = new Region(image2x, image2y,
image2x+image2.getWidth(),image2y+image2.getHeight());

if(region2.contains((int)event.getX(), (int)event.getY()))
{

image2x=(int) (event.getX()-100);

} super.onTouchEvent(event);


  return;
}           

}
}

Solution

  • You should not create your MediaPlayer in the on Touch Method, its better to declare a MediaPlayer field, and create it only once in your WallpaperService onCreate() Method like this :

    private MediaPlayer myPlayer;
    
    @Override
    public void onCreate() {
        super.onCreate();
        myPlayer = MediaPlayer.create(getApplicationContext(),
            R.raw.hi);                    
    }
    

    // then in your onTouch Method you start the sound :

    @Override
    public void onTouchEvent(MotionEvent event) {
    
    // ...
    
    myPlayer.start();
    }
    

    // that should work and also save resources.