オーディオの出力方式を選択


イヤホンで再生するかスピーカーで再生するか(Bluetoothは次回まで残しておきましょう)、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();
		}
	}
}