静音媒体播放器,但在Android中播放图形

时间:2015-01-21 06:01:18

标签: android graph media-player android-mediaplayer waveform

我正在使用两个媒体播放器,第一个媒体播放器将播放带有音乐的歌曲,另一个是歌曲的声音,这个声乐播放器应该静音但播放声乐的波形图,如何获得请帮助我。 !

我需要在从音频生成波形图时将媒体播放器静音。

I am using two media player, first media player will play songs with music and the other is vocal of that songs, this vocal player should be mute but play the wave graph of vocal music, how to get please help me out..!
I need to mute the media player while generating the waveform graph from audio.
Here is my code.

public class MainFinalAllActivity extends Activity {

    private Button btnPlay;
    // Media Player
    private MediaPlayer mp;
    private MediaPlayer mSilentPlayer;  /* to avoid tunnel player issue */
    private MediaPlayer vocalMediaPlayer;
    private VisualizerView mVisualizerView;
    // Handler to update UI timer, progress bar etc,.
    private Handler mHandler = new Handler();
    private int currentSongIndex = 0;
    private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
    private MediaRecorder myAudioRecorder;
    private String outputFile = null;


    String vocalPath = "/sdcard/test_v.mp3";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_final_layout);

        // All player buttons
        btnPlay = (Button) findViewById(R.id.btnPlay);
        songTitleLabel = (TextView) findViewById(R.id.songTitle);
        // Mediaplayer
        mp = new MediaPlayer();
        vocalMediaPlayer = new MediaPlayer();

        songsList = SelectedAlbumPlayList.goToFinalPageSongsList;
        int songIndex = SelectedAlbumPlayList.songIndex;
        mp.setLooping(true);
        playSong(songIndex);

        String pathOfSelectedSong = songsList.get(songIndex).get("songPath");

        // We need to link the visualizer view to the media player so that
        // it displays something
        mVisualizerView = (VisualizerView) findViewById(R.id.visualizerView);
        mVisualizerView.link(vocalMediaPlayer);

        //start the line renderer
        addLineRenderer();

        /**
         * Play button click event
         * plays a song and changes button to pause image
         * pauses a song and changes button to play image
         * */
        btnPlay.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // check for already playing
                if (mp.isPlaying()) {
                    if (mp != null) {
                        mp.pause();
                        vocalMediaPlayer.pause();
                        // Changing button image to play button
                        btnPlay.setText("Play");
                    }
                } else {
                    // Resume song
                    if (mp != null) {
                        mp.start();
                        vocalMediaPlayer.start();
                        // Changing button image to pause button
                        btnPlay.setText("Pause");                      
                    }
                }

            }
        });
    }

    /**
     * Receiving song index from playlist view
     * and play the song
     */
    @Override
    protected void onActivityResult(int requestCode,
                                    int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 100) {
            currentSongIndex = data.getExtras().getInt("songIndex");
            // play selected song
            playSong(currentSongIndex);
        }
    }

    /**
     * Function to play a song
     *
     * @param songIndex - index of song
     */
    public void playSong(int songIndex) {
        // Play song
        try {
            mp.reset();
            vocalMediaPlayer.reset();
            //vocalMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mp.setDataSource(songsList.get(songIndex).get("songPath"));
            vocalMediaPlayer.setDataSource(vocalPath);
            mp.prepare();
            vocalMediaPlayer.prepare();
            mp.start();
            vocalMediaPlayer.start();
            //vocalMediaPlayer.setVolume(0,0);
            // Displaying Song title
            String songTitle = songsList.get(songIndex).get("songTitle");
            songTitleLabel.setText(songTitle);

            //playVocalSong(vocalPath);
            // Changing Button Image to pause image
            btnPlay.setText("Pause");

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * Update timer on seekbar
     * */
    public void updateProgressBar() {
        mHandler.postDelayed(mUpdateTimeTask, 100);
    }

    int currentAmplitude;
    String TAG = null;
    byte[] bytes;
    /**
     * Background Runnable thread
     * */
    private Runnable mUpdateTimeTask = new Runnable() {
           public void run() {
               Bundle b = new Bundle();
               Message msg = mHandler.obtainMessage();
               if (myAudioRecorder != null) {
                   int previousValue = currentAmplitude;
                   currentAmplitude = myAudioRecorder.getMaxAmplitude();
                   //bytes = currentAmplitude.toByteArray();

                   //amplitude = mRecorder.getMaxAmplitude();
                   b.putLong("currentTime", currentAmplitude);
                   //Log.i("AMPLITUDE", new Integer(currentAmplitude).toString());
               } else {
                   b.putLong("currentTime", 0);
               }
               msg.setData(b);
               mHandler.sendMessage(msg);
                   mHandler.postDelayed(this, 100);
           }
        };

    private void addLineRenderer()
    {
        Paint linePaint = new Paint();
        linePaint.setStrokeWidth(1f);
        linePaint.setAntiAlias(true);
        linePaint.setColor(Color.argb(88, 0, 128, 255));
        Paint lineFlashPaint = new Paint();
        lineFlashPaint.setStrokeWidth(5f);
        lineFlashPaint.setAntiAlias(true);
        //lineFlashPaint.setColor(Color.argb(188, 255, 255, 255));
        lineFlashPaint.setColor(Color.rgb(255,69,0));
        //LineRenderer lineRenderer = new LineRenderer(linePaint,    lineFlashPaint, true);
        LineRenderer lineRenderer = new LineRenderer(linePaint, lineFlashPaint, true);
        mVisualizerView.addRenderer(lineRenderer);
    }

    @Override
     public void onDestroy(){
     super.onDestroy();
        mp.stop();
        vocalMediaPlayer.stop();
     }
}

//VisualizerView class

/**
 * A class that draws visualizations of data received from a
 * {@link android.media.audiofx.Visualizer.OnDataCaptureListener#onWaveFormDataCapture } and
 * {@link android.media.audiofx.Visualizer.OnDataCaptureListener#onFftDataCapture }
 */
public class VisualizerView extends View {
  private static final String TAG = "VisualizerView";
  private Handler mHandler = new Handler();;

  private byte[] mBytes;
  private byte[] mFFTBytes;
  private Rect mRect = new Rect();
  private Visualizer mVisualizer;

  private Set<Renderer> mRenderers;

  private Paint mFlashPaint = new Paint();
  private Paint mFadePaint = new Paint();

  public VisualizerView(Context context, AttributeSet attrs, int defStyle)
  {
    super(context, attrs);
    init();
  }

  public VisualizerView(Context context, AttributeSet attrs)
  {
    this(context, attrs, 0);
  }

  public VisualizerView(Context context)
  {
    this(context, null, 0);
  }

  private void init() {
    mBytes = null;
    mFFTBytes = null;

    mFlashPaint.setColor(Color.argb(122, 255, 255, 255));
    mFadePaint.setColor(Color.argb(238, 255, 255, 255)); // Adjust alpha to change how quickly the image fades
    mFadePaint.setXfermode(new PorterDuffXfermode(Mode.MULTIPLY));

    mRenderers = new HashSet<Renderer>();
  }

  /**
   * Links the visualizer to a player
   * @param player - MediaPlayer instance to link to
   */
  public void link(final MediaPlayer player)
  {
    if(player == null)
    {
      throw new NullPointerException("Cannot link to null MediaPlayer");
    }

    // Create the Visualizer object and attach it to our media player.
    mVisualizer = new Visualizer(player.getAudioSessionId());
    mVisualizer.setCaptureSize(Visualizer.getCaptureSizeRange()[1]);
    //mVisualizer.setMeasurementMode(Visualizer.MEASUREMENT_MODE_PEAK_RMS);

    // Pass through Visualizer data to VisualizerView
    Visualizer.OnDataCaptureListener captureListener = new Visualizer.OnDataCaptureListener()
    {
      @Override
      public void onWaveFormDataCapture(Visualizer visualizer, byte[] bytes,
          int samplingRate)
      {
        updateVisualizer(bytes);
        getDisplay();
        player.setVolume(0,0);
      }

      @Override
      public void onFftDataCapture(Visualizer visualizer, byte[] bytes,
          int samplingRate)
      {
        //updateVisualizerFFT(bytes);
      }
    };

    mVisualizer.setDataCaptureListener(captureListener,
        Visualizer.getMaxCaptureRate() / 2, true, true);
    // Enabled Visualizer and disable when we're done with the stream
    mVisualizer.setEnabled(true);
    player.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
    {
      @Override
      public void onCompletion(MediaPlayer mediaPlayer)
      {
        mVisualizer.setEnabled(false);
      }
    });
  }

  public void addRenderer(Renderer renderer)
  {
    if(renderer != null)
    {
      mRenderers.add(renderer);
    }
  }

  public void clearRenderers()
  {
    mRenderers.clear();
  }

  /**
   * Call to release the resources used by VisualizerView. Like with the
   * MediaPlayer it is good practice to call this method
   */
  public void release()
  {
    mVisualizer.release();
  }

    //calculating RMS Value from byte array
    public int calculateRMSLevel(byte[] audioData) {
        // audioData might be buffered data read from a data line
        long lSum = 0;
        for (int i = 0; i < audioData.length; i++) {
            lSum = lSum + audioData[i];
        }

        double dAvg = lSum / audioData.length;
        double sumMeanSquare = 0d;

        for (int j = 0; j < audioData.length; j++) {
            sumMeanSquare = sumMeanSquare + Math.pow(audioData[j] - dAvg, 2d);
        }

        double averageMeanSquare = sumMeanSquare / audioData.length;
        return (int) (Math.pow(averageMeanSquare, 0.5d) + 0.5);
    }

  /**
   * Pass data to the visualizer. Typically this will be obtained from the
   * Android Visualizer.OnDataCaptureListener call back. See
   * {@link android.media.audiofx.Visualizer.OnDataCaptureListener#onWaveFormDataCapture }
   * @param bytes
   */
  public void updateVisualizer(byte[] bytes) {
      int t = calculateRMSLevel(bytes);
      Visualizer.MeasurementPeakRms measurementPeakRms = new Visualizer.MeasurementPeakRms();
      int x = mVisualizer.getMeasurementPeakRms(measurementPeakRms);
      mBytes = bytes;
      invalidate();
  }

  /**
   * Pass FFT data to the visualizer. Typically this will be obtained from the
   * Android Visualizer.OnDataCaptureListener call back. See
   * {@link android.media.audiofx.Visualizer.OnDataCaptureListener#onFftDataCapture }
   * @param bytes
   */
  public void updateVisualizerFFT(byte[] bytes) {
      int t = calculateRMSLevel(bytes);
      //System.out.println("Amplitude:"+t);
    mFFTBytes = bytes;
    invalidate();
  }

  boolean mFlash = false;

  /**
   * Call this to make the visualizer flash. Useful for flashing at the start
   * of a song/loop etc...
   */
  public void flash() {
    mFlash = true;
    invalidate();
  }

  Bitmap mCanvasBitmap;
  Canvas mCanvas;


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

    // Create canvas once we're ready to draw
    mRect.set(0, 0, getWidth(), getHeight());

    if(mCanvasBitmap == null)
    {
      mCanvasBitmap = Bitmap.createBitmap(canvas.getWidth(), canvas.getHeight(), Config.ARGB_8888);
    }
    if(mCanvas == null)
    {
      mCanvas = new Canvas(mCanvasBitmap);
    }

    if (mBytes != null) {
      // Render all audio renderers
      AudioData audioData = new AudioData(mBytes);
      for(Renderer r : mRenderers)
      {
        r.render(mCanvas, audioData, mRect);
      }
    }

    if (mFFTBytes != null) {
      // Render all FFT renderers
      FFTData fftData = new FFTData(mFFTBytes);
      for(Renderer r : mRenderers)
      {
        r.render(mCanvas, fftData, mRect);
      }
    }

    // Fade out old contents
    mCanvas.drawPaint(mFadePaint);

    if(mFlash)
    {
      mFlash = false;
      mCanvas.drawPaint(mFlashPaint);
    }
    canvas.drawBitmap(mCanvasBitmap, new Matrix(), null);
  }

}

0 个答案:

没有答案
相关问题