Powered By Blogger

Monday 27 February 2012

MediaPlayer with Visualization And Equalizer


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.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.audiofx.Equalizer;
import android.media.audiofx.Visualizer;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;

public class MediaDemo extends Activity {
    /** Called when the activity is first created. */
   
private static final String TAG = "AudioFxDemo";

    private static final float VISUALIZER_HEIGHT_DIP = 50f;

    private MediaPlayer mp;
    private Visualizer mVisualizer;
    private Equalizer mEqualizer;

    private LinearLayout ll;
    private VideoView vv;
    private VisualizerView mVisualizerView;
    private TextView tv;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        tv=new TextView(this);
        vv=new VideoView(this);
        ll=new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.addView(tv);
        setContentView(ll);
        mp=MediaPlayer.create(getApplicationContext(), R.raw.jan);
        Log.d(TAG, "MediaPlayer audio session ID: " + mp.getAudioSessionId());
       
        setupVisualizer();
        setupEqualizer();
        mVisualizer.setEnabled(true);
        mp.setOnCompletionListener(new OnCompletionListener()
        {

@Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
mVisualizer.setEnabled(false);

}
       
        });
        mp.start();
        tv.setText("playing audio");
    }
    public void setupEqualizer()
    {
    mEqualizer=new Equalizer(0,mp.getAudioSessionId());
    mEqualizer.setEnabled(true);
    TextView tv=new TextView(this);
    tv.setText("equalizer");
    ll.addView(tv);
    short bands=mEqualizer.getNumberOfBands();
    final short min=mEqualizer.getBandLevelRange()[0];
    final short max=mEqualizer.getBandLevelRange()[1];
    for(short i=0;i<bands;i++)
    {
    final short band=1;
    TextView tv1=new TextView(this);
    tv1.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));
    tv1.setGravity(Gravity.CENTER_HORIZONTAL);
    tv1.setText((mEqualizer.getCenterFreq(band)/1000)+"hz");
    ll.addView(tv1);
    LinearLayout lv=new LinearLayout(this);
    lv.setOrientation(LinearLayout.HORIZONTAL);
    //TextView tv2=new TextView(this);
    //tv2.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));
    //tv2.setText((min/100)+"db");
    //TextView tv3=new TextView(this);
    //tv3.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));
    //tv3.setText((max/100)+"db");
    LinearLayout.LayoutParams param=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    param.weight=1;
    SeekBar bar=new SeekBar(this);
    bar.setLayoutParams(param);
    bar.setMax(max-min);
    bar.setProgress(mEqualizer.getBandLevel(band));
    bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub

}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub

}

@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
mEqualizer.setBandLevel(band, (short)(progress+min));

}
});
    //lv.addView(tv2);
    //lv.addView(tv3);
    lv.addView(bar);
    ll.addView(lv);
    }
   
    }
    public void setupVisualizer()
    {
    mVisualizerView=new VisualizerView(this);
    mVisualizerView.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.FILL_PARENT,
                (int)(VISUALIZER_HEIGHT_DIP * getResources().getDisplayMetrics().density)));
    /*vv.getBackground();
    ll.addView(vv);*/
    ll.addView(mVisualizerView);
   
   mVisualizer=new Visualizer(mp.getAudioSessionId());
   
   
   
   
    mVisualizer.setCaptureSize(Visualizer.getCaptureSizeRange()[1]);
    mVisualizer.setDataCaptureListener(new Visualizer.OnDataCaptureListener() {

@Override
public void onWaveFormDataCapture(Visualizer visualizer, byte[] bytes,
int samplingRate) {
// TODO Auto-generated method stub
mVisualizerView.updateVisualizer(bytes);

}

@Override
public void onFftDataCapture(Visualizer visualizer, byte[] fft,
int samplingRate) {
// TODO Auto-generated method stub

}
}, Visualizer.getMaxCaptureRate()/2, true,false);
   
    }
    protected void onPause() {
        super.onPause();

        if (isFinishing() && mp != null) {
            mVisualizer.release();
            mEqualizer.release();
            mp.release();
            mp = null;
        }
    }
}
class VisualizerView extends View {
    private byte[] mBytes;
    private float[] mPoints;
    private Rect mRect = new Rect();

    private Paint mForePaint = new Paint();

    public VisualizerView(Context context) {
        super(context);
        init();
    }

    private void init() {
        mBytes = null;

        mForePaint.setStrokeWidth(1f);
        mForePaint.setAntiAlias(true);
        mForePaint.setColor(Color.rgb(0, 128, 255));
    }

    public void updateVisualizer(byte[] bytes) {
        mBytes = bytes;
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (mBytes == null) {
            return;
        }

        if (mPoints == null || mPoints.length < mBytes.length * 4) {
            mPoints = new float[mBytes.length * 4];
        }

        mRect.set(0, 0, getWidth(), getHeight());

        for (int i = 0; i < mBytes.length - 1; i++) {
            mPoints[i * 4] = mRect.width() * i / (mBytes.length - 1);
            mPoints[i * 4 + 1] = mRect.height() / 2
                    + ((byte) (mBytes[i] + 128)) * (mRect.height() / 2) / 128;
            mPoints[i * 4 + 2] = mRect.width() * (i + 1) / (mBytes.length - 1);
            mPoints[i * 4 + 3] = mRect.height() / 2
                    + ((byte) (mBytes[i + 1] + 128)) * (mRect.height() / 2) / 128;
        }

        canvas.drawLines(mPoints, mForePaint);
    }
}

13 comments:

  1. I can not compile this code, because there is an error:

    mp=MediaPlayer.create(getApplicationContext(), R.raw.jan);

    R.raw.jan: raw can not be resolved

    ReplyDelete
    Replies
    1. Please make a 'raw' Folder in 'res'. Keep any song here and give the name of that song in this line (R.raw.name_of_song).

      Delete
  2. Dhiraj, You copied this code from Android Source sample code. Can you give the example how to show the different Visualization in "Bar" View?

    ReplyDelete
  3. If I need to apply the changes to all the media player files, and not just to a specific file, what should i do?

    ReplyDelete
  4. I am able play audio with visualization, But the speed of visualization is to fast, how can i slow the speed of visualization.

    ReplyDelete
  5. You just need to add following permission to your Android Manifest:

    Then Create a Directory name 'raw' in your 'res' directory and place a mediafile inside with .mp3 format. Leave the layout and the project will work!

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. I got an error: "Attempt to invoke virtual method 'int android.media.MediaPlayer.getAudioSessionId()' on a null object reference". How to fix it?

    ReplyDelete
    Replies
    1. I understood what was my problem, I was trying to play empty mp3 file. Thanks, very good example!

      Delete
  8. can you provide source code for better understanding..?

    ReplyDelete
  9. can you provide source code for better understanding..?

    ReplyDelete
  10. Unable to start activity ComponentInfo{com.validationlibrary/com.validationlibrary.MediaDemo}: java.lang.RuntimeException: Cannot initialize Visualizer engine, error: -3

    ReplyDelete
  11. Hi,

    Below is my code to open the default equalizer comes with android device..

    Intent intent = new Intent(AudioEffect.ACTION_DISPLAY_AUDIO_EFFECT_CONTROL_PANEL);
    startActivityForResult(intent, 0);

    which open the equalizer, but i dont found what should i wrote in onActivityResult..

    Plz help me in this.

    Bret Regards,

    ReplyDelete