Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Playing sounds in Android

    • 0
    • 2
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 678
    Comment on it

    Playing sounds in Android

    Copy your sounds in raw/ folder in res/ . If you do not have raw/ folder then make one by right clicking on res/ folder, click on Android resource directory and then giving directory name as raw and selecting resource type as raw and then copy your sounds in this directory.

    The following code starts a sound in onCreate() method and handle its lifecycle:

    • Starts the sound on onCreate().
    • Pause the Sound on onPause() and getting its seek position.
    • Playing the sound on onResume() from where it was stopped at onPause().
    • Release the resources associated with MediaPlayer object on onDestroy().


    public class MainActivity extends Activity {
    
    private static MediaPlayer mp ;
    private int musicSeekLength = 0;
    @Override
    protected void onCreate() {
    startSound();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        mp.seekTo(musicSeekLength);
        mp.start();
    }
    @Override
    protected void onPause() {
        super.onPause();
        mp.pause();
        musicSeekLength = mp.getCurrentPosition();
    }
    /*
     *This method initialise the MediaPlayer object and,
     * start the sound associated with it
     */
    private void startSound() {
        try {
            mp = MediaPlayer.create(this, R.raw.smells_like_teen_spirit);
            //Pass true if you want the sound to Loop
                  mp.setLooping(false);
            mp.start();
            mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                public void onCompletion(MediaPlayer mp) {
                   // Sound Completed
                }
            });
    
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // Releases resources associated with this MediaPlayer object
        mp.release();
    }
    }
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: