2011.08.12(2)——— android MediaPlayer听筒播放

2011.08.12(2)——— android MediaPlayer听筒播放

要实现听筒播放 只需在上一博客的基础上 增加AudioManager即可

am.setSpeakerphoneOn(false);
				setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
am.setMode(AudioManager.MODE_IN_CALL);


增加上面3行代码即可

完整代码如下:


package com.lp;


import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
	private Button play;
	private Button stop;
	private boolean 	isReleased		= false;
	private boolean 	isPlaying		= false;
	private MediaPlayer mMediaPlayer = new MediaPlayer();
	
	private AudioManager am;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        play = (Button)findViewById(R.id.main_play);
        stop = (Button)findViewById(R.id.main_stop);
        am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        play.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
				am.setSpeakerphoneOn(false);
				setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
				am.setMode(AudioManager.MODE_IN_CALL);
				
				try
				{
					if ( !isPlaying )
					{
						/* 装载资源中的音乐 */
						mMediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.test2);
						isPlaying = true;
						isReleased = false;
						/* 设置是否循环 */
						mMediaPlayer.setLooping(true);
						//mMediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
						try
						{
							mMediaPlayer.prepare();
						}
						catch (IllegalStateException e)
						{
							e.printStackTrace();
						}
						catch (IOException e)
						{
							e.printStackTrace();
						}
						
						mMediaPlayer.start();
						
					}
				}
				catch (IllegalStateException e)
				{
					e.printStackTrace();
				}
				mMediaPlayer.setOnCompletionListener(new OnCompletionListener() 
				{
					// @Override
					public void onCompletion(MediaPlayer arg0)
					{
						mMediaPlayer.release(); 
						am.setMode(AudioManager.MODE_NORMAL);
					}
				});
				
			}
        });
        
        stop.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(isPlaying&&!isReleased){
					isReleased = true;
					mMediaPlayer.stop();
					mMediaPlayer.release();
					isPlaying = false;
					am.setMode(AudioManager.MODE_NORMAL);
				}
			}
		});
    }
				
}

你可能感兴趣的:(android)