当前位置:首页 > 开发 > 移动开发 > 正文

选择音频的输出方式

发表于: 2012-12-12   作者:dai_lm   来源:转载   浏览:
摘要: 可以选择用耳机还是扬声器播放(蓝牙的就留到下次吧),要求SDK不小于5 public class MainActivity extends Activity implements OnClickListener { private AudioManager mAudioManager; private MediaPlayer mMediaPlayer; @Overri
可以选择用耳机还是扬声器播放(蓝牙的就留到下次吧),要求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();
		}
	}
}

选择音频的输出方式

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号