android mediaplayer 音效 代码

package com.example.mediaplayertest;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Paint.Style;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.audiofx.BassBoost;
import android.media.audiofx.Equalizer;
import android.media.audiofx.PresetReverb;
import android.media.audiofx.Visualizer;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;

public class MediaPlayerTest extends Activity {
	private LinearLayout layout;
	private MediaPlayer mPlayer;
	//定义系统的示波器
	private Visualizer mVisualizer;
	//定义系统的均衡器
	private Equalizer mEqualizer;
	//定义系统的重低音控制器
	private BassBoost mBass;
	//定义系统的预设音场控制器
	private PresetReverb mPresetReverb;
	private List reverbNames = new ArrayList();
	private List reverbVals = new ArrayList();
	
	private TextView mInfoView;

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//设定控制音乐声音
		setVolumeControlStream(AudioManager.STREAM_MUSIC);

		layout = new LinearLayout(this);
		layout.setOrientation(LinearLayout.VERTICAL);
		setContentView(layout);
		//创建mediaplayer对像
		mPlayer = MediaPlayer.create(this, R.raw.meihuasannong);
		//衩始化示波器
		setupVisualizer();
		mVisualizer.setEnabled(true);
		//初始化均衡控制器
		setupEqualizer();
		//初始化重低音控制器
		setupBassBoost();
		//初始化预设音场控制器
		setupPresetReverb();
		//开始播放音乐
		mPlayer.start();

	}
	//音场控制器	
	@SuppressLint("NewApi")
	private void setupPresetReverb() {
		//以MediaPlayer的AudioSessionId创建PresetReverb
		//相当于设置PresetReverb负责控制该MediaPlayer
		mPresetReverb = new PresetReverb(0, mPlayer.getAudioSessionId());
		mPresetReverb.setEnabled(true);//设置启用音场控制器
		TextView prTitle = new TextView(this);
		prTitle.setText("音场");
		layout.addView(prTitle);
		//获取系统支持的所有预设音场
		for (short i = 0; i < mEqualizer.getNumberOfPresets(); i++) {
			reverbNames.add(i);
			reverbVals.add(mEqualizer.getPresetName(i));
		}
		//使用Spinner作为音场选择器
		Spinner sp = new Spinner(this);

		sp.setAdapter(new ArrayAdapter(MediaPlayerTest.this,
				android.R.layout.simple_spinner_item, reverbVals));
		
		sp.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView parent, View view,
					int position, long id) {
				//设置所选的音场
				mPresetReverb.setPreset(reverbNames.get(position));
			}

			@Override
			public void onNothingSelected(AdapterView parent) {
				
			}
		});
		
		layout.addView(sp);

	}

	@SuppressLint("NewApi")
	@Override
	protected void onPause() {
		super.onPause();
		if(isFinishing() && mPlayer != null){
			mVisualizer.release();
			mEqualizer.release();
			mPresetReverb.release();
			mBass.release();
			mPlayer.release();
			mPlayer = null;
		}
	}
	//重低音控制器
	@SuppressLint("NewApi")
	private void setupBassBoost() {
		//以MediaPlayer的AudioSessionId创建BassBoost
		//相当于设置BassBoost负责控制该mediaplayer
		mBass = new BassBoost(0, mPlayer.getAudioSessionId());
		mBass.setEnabled(true);//设置启用重低音效果
		TextView bbText = new TextView(this);
		bbText.setText("重低音:");
		layout.addView(bbText);
		//使用seekbar作为重低音的调整工具
		SeekBar bar = new SeekBar(this);
		//设置进度条的范围为0~1000
		bar.setMax(1000);
		bar.setProgress(0);
		bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {

			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {

			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				//设置重低音的强度
				mBass.setStrength((short) progress);
			}
		});
		layout.addView(bar);

	}
	//均衡控制器
	@SuppressLint("NewApi")
	private void setupEqualizer() {
		//以MediaPlayer的AudioSessionId创建均衡器
		mEqualizer = new Equalizer(0, mPlayer.getAudioSessionId());
		//设置启用均衡器
		mEqualizer.setEnabled(true);
		TextView eqTitle = new TextView(this);
		eqTitle.setText("均衡器:");
		layout.addView(eqTitle);
		//获取均衡器的最大值和最小值
		final short minEQLevel = mEqualizer.getBandLevelRange()[0];
		short maxEQLevel = mEqualizer.getBandLevelRange()[1];
		//获取均衡器所支持的所有频率
		short brands = mEqualizer.getNumberOfBands();

		for (short i = 0; i < brands; i++) {
			//创建一个TextView,用于显示频率
			TextView eqTextView = new TextView(this);
			eqTextView.setLayoutParams(new ViewGroup.LayoutParams(
					ViewGroup.LayoutParams.MATCH_PARENT,
					ViewGroup.LayoutParams.WRAP_CONTENT));
			eqTextView.setGravity(Gravity.CENTER_HORIZONTAL);
			//设置该均衡控制器的频率
			eqTextView.setText(mEqualizer.getCenterFreq(i) / 1000 + "Hz");
			layout.addView(eqTextView);
			//创建一个LinearLayout,水平排列组件
			LinearLayout tmpLayout = new LinearLayout(this);
			tmpLayout.setOrientation(LinearLayout.HORIZONTAL);
			//显示均衡器最小值的textview
			TextView minDbTextView = new TextView(this);
			minDbTextView.setLayoutParams(new ViewGroup.LayoutParams(
					ViewGroup.LayoutParams.WRAP_CONTENT,
					ViewGroup.LayoutParams.WRAP_CONTENT));
			minDbTextView.setText((minEQLevel / 100) + "dB");
			//显示均衡器最大值的textview
			TextView maxDbTextView = new TextView(this);
			maxDbTextView.setLayoutParams(new ViewGroup.LayoutParams(
					ViewGroup.LayoutParams.WRAP_CONTENT,
					ViewGroup.LayoutParams.WRAP_CONTENT));
			maxDbTextView.setText((maxEQLevel / 100) + "dB");

			LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
					ViewGroup.LayoutParams.WRAP_CONTENT,
					ViewGroup.LayoutParams.WRAP_CONTENT);
			layoutParams.weight = 1;
			//定义seekbar作为调整工具
			SeekBar bar = new SeekBar(this);
			bar.setLayoutParams(layoutParams);
			bar.setMax(maxEQLevel - minEQLevel);
			bar.setProgress(mEqualizer.getBandLevel(i));

			final short brand = i;
			bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

				@Override
				public void onStopTrackingTouch(SeekBar seekBar) {

				}

				@Override
				public void onStartTrackingTouch(SeekBar seekBar) {

				}

				@Override
				public void onProgressChanged(SeekBar seekBar, int progress,
						boolean fromUser) {
					//设置该频率的均衡值
					mEqualizer.setBandLevel(brand,
							(short) (progress + minEQLevel));
				}
			});
			
			tmpLayout.addView(minDbTextView);
			tmpLayout.addView(bar);
			tmpLayout.addView(maxDbTextView);

			layout.addView(tmpLayout);
		}

	}

	@SuppressLint("NewApi")
	private void setupVisualizer() {
		//创建MyVisualizerView组件,用于显示波形图
		final MyVisualizerView mVisualizerView = new MyVisualizerView(this);
		mVisualizerView.setLayoutParams(new ViewGroup.LayoutParams(
				ViewGroup.LayoutParams.FILL_PARENT,
				(int) (160f * getResources().getDisplayMetrics().density)));
		//将组件添加到layout容器中
		layout.addView(mVisualizerView);
		 mInfoView = new TextView(this);  
	        String infoStr = "";  
	          
	        int[] csr = Visualizer.getCaptureSizeRange();  
	        if(csr != null)  
	        {  
	            String csrStr = "CaptureSizeRange: ";  
	            for(int i = 0; i < csr.length; i ++)  
	            {  
	                csrStr += csr[i];  
	                csrStr +=" ";  
	            }  
	            infoStr += csrStr;  
	        }  
	          
	        final int maxCR = Visualizer.getMaxCaptureRate();  
	          
	        infoStr = infoStr + "\nMaxCaptureRate: " + maxCR;  
	          
	        mInfoView.setText(infoStr);  
	        layout.addView(mInfoView);  
		//以MediaPlayer的AudioSessionId创建Visualizer对像
		//相当于设置Visualizer负责显示该MediaPlayer的音频数据
		mVisualizer = new Visualizer(mPlayer.getAudioSessionId());
		mVisualizer.setCaptureSize(Visualizer.getCaptureSizeRange()[1]);
		mVisualizer.setDataCaptureListener(
				new Visualizer.OnDataCaptureListener() {

					@Override
					public void onWaveFormDataCapture(Visualizer visualizer,
							byte[] waveform, int samplingRate) {
						
						mVisualizerView.updateVisualizer(waveform);
					}

					@Override
					public void onFftDataCapture(Visualizer visualizer,
							byte[] fft, int samplingRate) {
						mVisualizerView.updateVisualizer(fft);
					}
				}, Visualizer.getMaxCaptureRate() / 2, true, false);
	}
	
	
	
	 class MyVisualizerView extends View {
			private byte[] bytes;
			private float[] points;
			private Paint paint = new Paint();
			private Rect rect = new Rect();
			private byte type = 0;
			private boolean mFirst = true; 

			public MyVisualizerView(Context context) {
				super(context);
				bytes = null;
				paint.setStrokeWidth(1f);
				paint.setAntiAlias(true);
				paint.setColor(Color.GREEN);
				paint.setStyle(Style.FILL);
				
			}

			public void updateVisualizer(byte[] fft) {
				if(mFirst )  
		        {  
		            mInfoView.setText(mInfoView.getText().toString() + "\nCaptureSize: " + fft.length);  
		            mFirst = false;  
		        } 
				bytes = fft;
		        
				invalidate();
			}

			@Override
			public boolean onTouchEvent(MotionEvent event) {
				if(event.getAction() != MotionEvent.ACTION_DOWN){
					return false;
				}
				type ++;
				if(type >= 3){
					type = 0;
				}
				return true;
			}

			@Override
			protected void onDraw(Canvas canvas) {
				super.onDraw(canvas);
				if(bytes == null){
					return;
				}
				canvas.drawColor(Color.WHITE);
				System.out.println("height-->"+getHeight());
				rect.set(0, 0, getWidth(), getHeight());
				switch(type){
				case 0:
					for(int i = 0;i < bytes.length - 1;i ++){
						float left = getWidth() * i / (bytes.length - 1);
						float top = rect.height() - (byte)(bytes[i + 1] + 128) * rect .height() / 128;
						float right = left + 1;
						float bottom = rect.height();
						canvas.drawRect(left, top, right, bottom, paint);
					}
					break;
				case 1:
					for(int i = 0;i < bytes.length - 1;i += 18){
						float left = getWidth() * i / (bytes.length - 1);
						float top = rect.height() - (byte)(bytes[i + 1] + 128) * rect .height() / 128;
						float right = left + 6;
						float bottom = rect.height();
						canvas.drawRect(left, top, right, bottom, paint);
					}
					break;
				case 2:
					if(points == null || points.length < bytes.length * 4){
						points = new float[bytes.length * 4];
					}
					for(int i = 0;i < bytes.length - 1;i ++){
						points[i * 4] = rect.width() * i / (bytes.length -1);
						points[i * 4 + 1] = (rect.height() / 2) + ((byte) (bytes[i]+ 128)) * 128 / (rect.height() / 2 );
						points[i * 4 + 2] = rect.width() * (i + 1) / (bytes.length - 1);
						points[i * 4 + 3] = (rect.height() / 2) + ((byte) (bytes[i + 1] + 128)) * 128 /(rect.height()/ 2); 
					}
					
					canvas.drawLines(points, paint);
					break;
				/*case 2:
					//bytes = null;  
					paint.setStrokeWidth(8f);  
		            paint.setAntiAlias(true);  
		            paint.setColor(Color.rgb(0, 128, 255));  
			        byte[] model = new byte[bytes.length / 2 + 1];  

			        model[0] = (byte) Math.abs(bytes[0]);  
			        for (int i = 2, j = 1; j < 48;)  
			        {  
			            model[j] = (byte) Math.hypot(bytes[i], bytes[i + 1]);  
			            i += 2;  
			            j++;  
			        }  
			        bytes = model; 
					if(points == null || points.length < bytes.length * 4){
						points = new float[bytes.length * 4];
					}
					rect.set(0, 0, getWidth(),(int) (160f * getResources().getDisplayMetrics().density));
					final int baseX = rect.width()/48;  
		            final int height = rect.height(); 
		            System.out.println("height===>"+height);
					for (int i = 0; i < 48 ; i++)  
		            {  
		                if (bytes[i] < 0)  
		                {  
		                    bytes[i] = 127;  
		                }  
		                  
		                final int xi = baseX*i + baseX/2;  
		                  
		                points[i * 4] = xi;  
		                points[i * 4 + 1] = height;  
		                  
		                points[i * 4 + 2] = xi;  
		                points[i * 4 + 3] = height - bytes[i];  
		            }  
					canvas.drawLines(points, paint);
					break;*/
				}
			}

		}

}

需要下载请到这个地址:

点击打开链接

你可能感兴趣的:(移动,开发,android)