Android development-control mobile audio
This example uses MediaPlayer to play a piece of music and use AudioManager to control the mobile audio. For more information about AudioManager, see AudioManager for Android development.
Program running:
Instance code:
Package com. jph. audiomanagerdemo; import android. media. audioManager; import android. media. mediaPlayer; import android. OS. bundle; import android. app. activity; import android. app. service; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. compoundButton; import android. widget. compoundButton. onCheckedChangeListener; import android. widget. toggleButton;/*** Describe:
* Control Data audio * This instance uses MediaPlayer to play a piece of music and * uses AudioManager to control mobile phone audio **/public class AudioManagerDemo extends Activity {Button btnPlay, btnUp, btnDown; ToggleButton btnMute; audioManager aManager; MediaPlayer mPlayer; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); btnDown = (Button) findViewById (R. id. btnDown); btnPlay = (Button) findViewById (R. id. btnPlay); btnUp = (Button) findViewById (R. id. btnUp); btnMute = (ToggleButton) findViewById (R. id. btnMute); // initialize AudioManageraManager = (AudioManager) getSystemService (Service. AUDIO_SERVICE); OnClickListener listener = new OnClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubswitch (v. getId () {case R. id. btnPlay: // initialize MediaPlayer to prepare for playing music. mPlayer = MediaPlayer. create (AudioManagerDemo. this, R. raw. music); // sets the music loop to play mPlayer. setLooping (true); // play the mPlayer. start (); break; case R. id. btnUp: // adjust the audio of the music to increase, and display the volume chart aManager. adjustStreamVolume (AudioManager. STREAM_MUSIC, AudioManager. ADJUST_RAISE, AudioManager. FLAG_SHOW_UI); break; case R. id. btnDown: // specify to adjust the audio of the music to reduce, and display the volume graphics aManager. adjustStreamVolume (AudioManager. STREAM_MUSIC, AudioManager. ADJUST_LOWER, AudioManager. FLAG_SHOW_UI); break; default: break ;}}; // Add listener btnDown for the button. setOnClickListener (listener); btnPlay. setOnClickListener (listener); btnUp. setOnClickListener (listener); btnMute. setOnCheckedChangeListener (new OnCheckedChangeListener () {@ Overridepublic void onCheckedChanged (CompoundButton buttonView, boolean isChecked) {// TODO Auto-generated method stub // set music mute aManager. setStreamMute (AudioManager. STREAM_MUSIC, isChecked );}});}}
Main. xml