选择音频的输出方式

可以选择用耳机还是扬声器播放(蓝牙的就留到下次吧),要求SDK不小于5
public class MainActivity extends Activity implements OnClickListener {

	private AudioManager mAudioManager;
	private MediaPlayer mMediaPlayer;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);

		mMediaPlayer = new MediaPlayer();
		mMediaPlayer.reset();
		try {
			File audio = new File(Environment.getExternalStorageDirectory(),
					"/Music/xxx.mp3");
			mMediaPlayer.setDataSource(audio.getAbsolutePath());
			mMediaPlayer.prepare();
			mMediaPlayer.setOnPreparedListener(new PrepareListener());
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		findViewById(R.id.btn_speaker).setOnClickListener(this);
		findViewById(R.id.btn_headset).setOnClickListener(this);
		findViewById(R.id.btn_bluetooth).setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {

		int id = v.getId();
		switch (id) {
		case R.id.btn_speaker:

//			if (!mAudioManager.isSpeakerphoneOn())
//				return;

			mAudioManager.setMode(AudioManager.ROUTE_SPEAKER);
			mAudioManager.setSpeakerphoneOn(true);

			break;
		case R.id.btn_headset:

//			if (!mAudioManager.isWiredHeadsetOn())
//				return;

			mAudioManager.setMode(AudioManager.MODE_NORMAL);
			mAudioManager.setWiredHeadsetOn(true);

			break;
		case R.id.btn_bluetooth:

			break;
		default:
			break;
		}
	}

	@Override
	protected void onDestroy() {

		// change mode back to normal
		mAudioManager.setMode(AudioManager.MODE_NORMAL);

		// release resource, important
		mMediaPlayer.stop();
		mMediaPlayer.release();
		mMediaPlayer = null;

		super.onDestroy();
	}

	private final class PrepareListener implements OnPreparedListener {

		public void onPrepared(MediaPlayer mp) {
			mMediaPlayer.start();
		}
	}
}

你可能感兴趣的:(android,AudioManager,Speaker,Headset)