This example comes from "Crazy Android Handout", which requires an understanding of the following APIs to achieve specific functionality:
- MediaPlayer Media Player
- Visualizer Spectrum
- Equalizer Equalizer
- Bassboost Heavy bass Controller
- Presetreverb Preset sound field controller
- Paint Drawing
look at the effect as shown below
Vertical Waveform Diagram
Block waveform diagram
Curve waveform diagram
Adjust equalizer, subwoofer
Select sound Field
Here's a look at the specific implementation code Mediaplayertest.java
Package Com.oyp.media;import Java.util.arraylist;import Java.util.list;import android.app.activity;import Android.content.context;import Android.graphics.canvas;import Android.graphics.color;import Android.graphics.paint;import Android.graphics.paint.style;import Android.graphics.rect;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.arrayadapter;import Android.widget.linearlayout;import Android.widget.seekbar;import Android.widget.spinner;import Android.widget.textview;public class Mediaplayertest extends activity{// Defines the mediaplayerprivate MediaPlayer of the playback sound mplayer;//define the system's spectrum private Visualizer mvisualizer;//define the equalizer of the system PrivaTe Equalizer mequalizer;//defines the system's subwoofer controller private Bassboost mbass;//defines the system's preset sound field controller private Presetreverb Mpresetreverb; Private LinearLayout layout;private list<short> reverbnames = new arraylist<short> ();p rivate List< string> reverbvals = new arraylist<string> (), @Overridepublic void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate);//Set Audio stream-Stream_music: Music playback is media volume Setvolumecontrolstream (AUDIOMANAGER.STREAM_ Layout = new LinearLayout (this);//Code creation layouts Layout.setorientation (linearlayout.vertical);// Set to linear layout-up and down Setcontentview (layout),//Add layout to activity//Create MediaPlayer object and add audio//audio path to Res/raw/beautiful.mp3mplayer = Mediaplayer.create (this, r.raw.beautiful);//Initialize the oscilloscope setupvisualizer ();//Initialize The Equalizer Controller setupequalizer ();// Initialize the subwoofer controller setupbassboost ();//Initialize the preset sound field controller setuppresetreverb ();//Develop play music Mplayer.start ();} /** * Initialize Spectrum */private void Setupvisualizer () {//Create Myvisualizerview component to display waveform diagram final Myvisualizerview mvisualizerview =new Myvisualizerview (this); Mvisualizerview. Setlayoutparams (New Viewgroup.layoutparams (ViewGroup.LayoutParams.MATCH_PARENT, (int) (120F * getresources (). Getdisplaymetrics () density));//Add the Myvisualizerview component to the layout container Layout.addview (mvisualizerview);// Creating visualizer//with MediaPlayer Audiosessionid is equivalent to setting the Visualizer is responsible for displaying the MediaPlayer audio data Mvisualizer = new Visualizer ( Mplayer.getaudiosessionid ());//Set the length of the music content that needs to be converted, professionally speaking this is sampling, the sample value is generally 2 of the number of times, such as 64,128,256,512,1024. Mvisualizer.setcapturesize (Visualizer.getcapturesizerange () [1]);//Set listener/* for Mvisualizer */* Visualizer.setdatacapturelistener (Ondatacapturelistener Listener, int rate, Boolean waveform, boolean FFT * * listener, table The Listener function, the anonymous internal class implementation of the interface, the interface needs to implement two function rate, indicating the sampling period, that is, how often sampling, contact before the text is to sample 128 data Iswave, is the waveform signal Isfft, is the FFT signal, is to obtain the waveform signal or frequency domain signal */ Mvisualizer.setdatacapturelistener (New Visualizer.ondatacapturelistener () {// This callback should capture data about the fast Fourier transform @overridepublic void Onfftdatacapture (Visualizer visualizer,byte[] FFT, int samplingrate) {}// This callback should capture the waveform data @overridepublic void Onwaveformdatacapture (Visualizer visualizer,bytE[] waveform, int samplingrate) {//Update Mvisualizerview Component Mvisualizerview.updatevisualizer (waveform) with waveform waveform data;}}, Visualizer.getmaxcapturerate ()/2, True, false); mvisualizer.setenabled (true);} /** * Initialize the Equalizer controller */private void Setupequalizer () {//MediaPlayer Audiosessionid created equalizer// Equivalent to setting equalizer is responsible for controlling the Mediaplayermequalizer = new Equalizer (0, Mplayer.getaudiosessionid ());// Enable equalization Control effect mequalizer.setenabled (true); TextView eqtitle = new TextView (this); Eqtitle.settext ("Equalizer:"); Layout.addview (eqtitle);//Gain Equalization Controller support minimum and maximum final short Mineqlevel = Mequalizer.getbandlevelrange () [0];//The first subscript is the lowest limit range short maxeqlevel = Mequalizer.getbandlevelrange () [1]; The second subscript is the highest limit range//Get all frequencies supported by the equalization controller Short brands = Mequalizer.getnumberofbands (); for (short i = 0; i < brands; i++) {TEXTVI EW Eqtextview = new TextView (this);//Create a TextView to display the frequency eqtextview.setlayoutparams (new Viewgroup.layoutparams ( viewgroup.layoutparams.match_parent,viewgroup.layoutparams.wrap_content)); Eqtextview.setgravity (Gravity.CENTER _horizontal)///Set the Equalizer Controller frequency Eqtextview.settext ((Mequalizer.getcenterfreq (i)/+) + "Hz"); Layout.addview (Eqtextview);// Create a linearlayoutlinearlayout tmplayout = new LinearLayout (this) for a horizontally arranged component; Tmplayout.setorientation ( Linearlayout.horizontal)//create Textviewtextview Mindbtextview = new TextView (this) showing the minimum value of the equalization controller; Mindbtextview.setlayoutparams (New Viewgroup.layoutparams (ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));//Display the minimum value of the Equalization Controller Mindbtextview.settext ((mineqlevel/100) + "DB");// Create a Textviewtextview Maxdbtextview = new TextView (this) that displays the maximum value of the Equalizer controller, Maxdbtextview.setlayoutparams (new Viewgroup.layoutparams (viewgroup.layoutparams.wrap_content,viewgroup.layoutparams.wrap_content));// Displays the maximum value of the Equalizer controller Maxdbtextview.settext ((maxeqlevel/100) + "DB"); Linearlayout.layoutparams layoutparams = new Linearlayout.layoutparams (ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); layoutparams.weight = 1;//definition SeekBar as the adjustment tool SeekBar bar = new SeekBar (this); Bar.setlayoutparams (layouTparams); Bar.setmax (Maxeqlevel-mineqlevel); Bar.setprogress (Mequalizer.getbandlevel (i)); final Short brand = i;// Set event listener Bar.setonseekbarchangelistener for SeekBar drag events (new Seekbar.onseekbarchangelistener () {@Overridepublic void Onprogresschanged (SeekBar seekbar,int Progress, Boolean Fromuser) {//Set the equalization value for this frequency mequalizer.setbandlevel (brand, (short) (Progress + Mineqlevel));} @Overridepublic void Onstarttrackingtouch (SeekBar SeekBar) {} @Overridepublic void Onstoptrackingtouch (SeekBar SeekBar {}}),//"LinearLayout" 3 components Tmplayout.addview (Mindbtextview) with horizontal arrangement of components, Tmplayout.addview (bar); Tmplayout.addview (maxdbtextview);//Add the linearlayout of the horizontally arranged component to the Mylayout container Layout.addview (tmplayout);}} /** * Initialize the subwoofer controller */private void Setupbassboost () {//MediaPlayer Audiosessionid Create bassboost// Equivalent to setting Bassboost is responsible for controlling the Mediaplayermbass = new Bassboost (0, Mplayer.getaudiosessionid ());//setting Enable Bass effect mbass.setenabled ( true); TextView bbtitle = new TextView (this); Bbtitle.settext ("Heavy bass:"); Layout.addview (bbtitle);//use Seekbar to make heavy bass adjustment tool SeekbaR bar = new SeekBar (this);//The range of heavy bass is 0~1000bar.setmax (+); bar.setprogress (0);// Set event listener Bar.setonseekbarchangelistener for SeekBar drag events (new Seekbar.onseekbarchangelistener () {@Overridepublic void Onprogresschanged (SeekBar SeekBar, int progress, Boolean Fromuser) {//Set the intensity of the subwoofer mbass.setstrength ((short) progress);} @Overridepublic void Onstarttrackingtouch (SeekBar SeekBar) {} @Overridepublic void Onstoptrackingtouch (SeekBar SeekBar {}}); Layout.addview (bar);} /** * Initialize the preset sound field controller */private void Setuppresetreverb () {//MediaPlayer Audiosessionid created presetreverb// Equivalent to setting Presetreverb is responsible for controlling the Mediaplayermpresetreverb = new Presetreverb (0,mplayer.getaudiosessionid ());// Set Enable preset sound field control mpresetreverb.setenabled (true); TextView prtitle = new TextView (this);p rtitle.settext ("sound Field"); Layout.addview (prtitle);//Get all preset sound fields supported by the system for (short i = 0; I & Lt Mequalizer.getnumberofpresets (); i++) {reverbnames.add (i); Reverbvals.add (Mequalizer.getpresetname (i));} Use Spinner as the Sound field selection Tool Spinner SP = new Spinner (this); Sp.setadapter (New arrayadapter< String> (mediaplayertest.this,android. R.layout.simple_spinner_item, Reverbvals));//For spinner list item check event set Listener Sp.setonitemselectedlistener (new Spinner.onitemselectedlistener () {@Overridepublic void onitemselected (adapterview<?> arg0, View arg1, int arg2, Long Arg3) {//Set sound field Mpresetreverb.setpreset (Reverbnames.get (ARG2));} @Overridepublic void onnothingselected (adapterview<?> arg0) {}}); Layout.addview (sp);} @Overrideprotected void OnPause () {super.onpause (); if (isfinishing () && mPlayer! = null) {// Release all Objects mvisualizer.release (); Mequalizer.release (); Mpresetreverb.release (); Mbass.release (); Mplayer.release (); MPlayer = null;}} /** * According to the data transmitted by visualizer dynamic waveform effect, respectively: * block waveform, cylindrical waveform, curve waveform */private static class Myvisualizerview extends view{//bytes array to preserve the wave The value of the sample point private byte[] bytes;private float[] points;private paint paint = new Paint ();p rivate rect rect = new rect ();p rivate BYTE type = 0;public Myvisualizerview (context context) {super (context); bytes = null;//Sets the property of the brush paint.setstrokewidth (1f); PAint.setantialias (TRUE);//antialiasing Paint.setcolor (Color.yellow);//Brush Color Paint.setstyle (style.fill);} public void Updatevisualizer (byte[] ftt) {bytes = ftt;//notifies the component to redraw itself. Invalidate ();} @Overridepublic Boolean ontouchevent (motionevent me) {//When the user touches the component, toggles the waveform type if (me.getaction ()! = Motionevent.action_down ) {return false;} Type ++;if (Type >= 3) {type = 0;} return true;} @Overrideprotected void OnDraw (canvas canvas) {super.ondraw (canvas); if (bytes = = null) {return;} Draw a white background canvas.drawcolor (color.white);//Use a Rect object to record the width and height of the component Rect.set (0,0,getwidth (), GetHeight ()), and switch (type) {/ /-------Plot a blocky waveform-------case 0:for (int i = 0; i < bytes.length-1; i++) {Float left = getwidth () * I/(Bytes.length- 1);//Calculate the height of the rectangle based on the waveform value float top = rect.height ()-(byte) (bytes[i+1]+128) * Rect.height ()/128;float right = left + 1;float bot Tom = Rect.height (); Canvas.drawrect (left, top, right, bottom, paint);} break;//-------Draw a histogram of histograms (draw a rectangle every 18 sampling points)-------case 1:for (int i = 0; i < bytes.length-1; i + =) {float left = rect. Width) *i/(bytes.length-1);//Calculates the height of the rectangle based on the waveform value 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;//-------Plot curve waveform-------Case 2://If the point array is not initialized if (points = = NULL | | Points.length < BYTES.LENGTH * 4) {points = New float[bytes.length * 4];} for (int i = 0; i < bytes.length-1; i++) {//calculates the x-coordinate of point I points[i * 4] = Rect.width () *i/(bytes.length-1);//According to Bytes[i] Value (the value of the waveform point) calculates the y-coordinate of the point I points[i * 4 + 1] = (Rect.height ()/2) + ((byte) (Bytes[i] +)) * 128/(Rect.height ()/2);//Calculation Section I+1 The x-coordinate of the dots points[i * 4 + 2] = Rect.width () * (i + 1)/(bytes.length-1);///(the value of the waveform point) calculates the y-coordinate of the first i+1 point Points[i * 4 + 3] = (Rect.height ()/2) + ((byte) (Bytes[i + 1] + +)) * 128/(Rect.height ()/2);} Draw the waveform curve canvas.drawlines (points, paint); break;}}}
Androidmanifest.xml
<?xml version= "1.0" encoding= "Utf-8"? ><manifestxmlns:android= "http://schemas.android.com/apk/res/ Android "package=" Com.oyp.media "android:versioncode=" 1 "android:versionname=" 1.0 "><USES-SDK android: minsdkversion= "android:targetsdkversion=" /><!--the necessary permissions to use the Sound field--><uses-permission android: Name= "Android.permission.RECORD_AUDIO"/> <uses-permission android:name= "android.permission.MODIFY_AUDIO_ SETTINGS "/><applicationandroid:icon=" @drawable/ic_launcher "android:label=" @string/app_name ">< Activityandroid:name= ". Mediaplayertest "android:label=" @string/app_name "><intent-filter><action android:name=" Android.intent.action.MAIN "/><category android:name=" Android.intent.category.LAUNCHER "/></ Intent-filter></activity></application></manifest>
PS: Please run this program in real-world environment, if run under Simulator, may error:
Java.lang.RuntimeException:Cannot Initialize Visualizer engine, error: 4
==================================================================================================
Ouyangpeng welcome reprint, sharing with people is the source of progress!
Reprint please keep the original address : Http://blog.csdn.net/ouyang_peng
==================================================================================================
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
My Android Advanced tour------>android realize music oscilloscope, equalizer, bass and sound field functions