Android 音频播放

阅读更多
android音频播放方式有两种:一种是MediaPlayer,另一种是SoundPool,下面这个例子是用的第一种

1.首先看布局文件





	




2.响应的Activity代码如下
package com.lamp.audio;


import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Audio extends Activity {
	private EditText fileNameText = null;
	private MediaPlayer mediaPlayer = null;
	private boolean ispause = false;
	private static final String TAG = "Audio";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        fileNameText = (EditText)this.findViewById(R.id.fileName);
        Button startButton = (Button)this.findViewById(R.id.startButton);
        Button pauseButton = (Button)this.findViewById(R.id.pauseButton);
        Button endButton = (Button)this.findViewById(R.id.endButton);
        startButton.setOnClickListener(listener);
        pauseButton.setOnClickListener(listener);
        endButton.setOnClickListener(listener);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
			
			public void onCompletion(MediaPlayer mp) {
				Toast.makeText(Audio.this, "播放结束", Toast.LENGTH_LONG).show();
			}
		});
    }
    private View.OnClickListener listener = new View.OnClickListener() {
		public void onClick(View v) {
			Button button = (Button)v;
			switch (button.getId()) {
			case R.id.startButton:
				String fileName = fileNameText.getText().toString();
				mediaPlayer.reset();
				mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
				try {
					mediaPlayer.setDataSource("/mnt/sdcard/" + fileName);
					//缓冲
					mediaPlayer.prepare();
					//开始播放
					mediaPlayer.start();
				} catch (Exception e) {
					Log.e(TAG, e.toString());
				} 
				break;

			case R.id.pauseButton:
				if(mediaPlayer.isPlaying()){
					//暂停播放
					mediaPlayer.pause();
				}else{
					mediaPlayer.start();
				}
				break;
				
			case R.id.endButton:
				if(mediaPlayer.isPlaying()){
					//停止播放
					mediaPlayer.stop();
				}
				break;
			}
		}
	};
	
	//当手机收到外来响应,比如接到电话,音频播放暂停
	protected void onPause() {
		if(mediaPlayer.isPlaying()){
			mediaPlayer.pause();
			ispause = true;
		}
		super.onPause();
	}
	
	//当挂断电话后恢复播放
	protected void onResume() {
		if(ispause){
			mediaPlayer.start();
			ispause = false;
		}
		super.onResume();
	}
	
	@Override
	protected void onDestroy() {
		mediaPlayer.release();
		mediaPlayer = null;
		super.onDestroy();
	}
}


播放的map3文件可以放在资源文件夹,sdk卡,此例子是放在sdk根目录下

你可能感兴趣的:(android,mediaplayer,soundpool)