Code example for MediaPlayer

Methods: setOnErrorListenersetOnPreparedListenersetVolumesetWakeMode

0
	    { 
	        case AudioManager.AUDIOFOCUS_GAIN:
	            // resume playback 
	            if (mp == null) initMediaPlayer();
	            else if (!mp.isPlaying()) mp.start();
	            mp.setVolume(1.0f, 1.0f);
	            break; 
 
	        case AudioManager.AUDIOFOCUS_LOSS:
	            // Lost focus for an unbounded amount of time: stop playback and release media player 
	        	if(mp != null)
	        	{ 
		            if (mp.isPlaying()) mp.stop();
		            mp.release();
		            mp = null;
	        	} 
	            break; 
 
	        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
	        	if(mp != null)
	        	{ 
		            // Lost focus for a short time, but we have to stop 
		            // playback. We don't release the media player because playback 
		            // is likely to resume 
	        		if (mp.isPlaying()) mp.pause();
	        	} 
	            break; 
 
	        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
	        	if(mp != null)
	        	{ 
		            // Lost focus for a short time, but it's ok to keep playing 
		            // at an attenuated level 
	        		if (mp.isPlaying()) mp.setVolume(0.1f, 0.1f);
	        	} 
	            break; 
	    } 
	} 
	 
	public void initMediaPlayer()  
	{ 
		mp = new MediaPlayer();
		mp.setOnPreparedListener(new OnPreparedListener() 
		{ 
			public void onPrepared(MediaPlayer mp) 
			{ 
				mp.start();	
			} 
		}); 
		mp.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
        mp.setOnErrorListener(this);
    } 
 
	public boolean onError(MediaPlayer mp, int what, int extra) 
	{ 
        if (mp.isPlaying()) mp.stop();