create Audio Track - Android Media

Android examples for Media:Auto Player

Description

create Audio Track

Demo Code


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.media.AudioTrack.OnPlaybackPositionUpdateListener;

public class Main {
  public static void createAudioTrack(String path) {
    try {/*  w w w  .j a v  a 2s.  c om*/
      byte[] audioData = getBytes(path);
      if (audioData != null) {
        AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 8000, AudioFormat.CHANNEL_OUT_STEREO,
            AudioFormat.ENCODING_PCM_16BIT, audioData.length, AudioTrack.MODE_STATIC);
        audioTrack.write(audioData, 0, audioData.length);
        audioTrack.setNotificationMarkerPosition(audioData.length - 1);
        audioTrack.setPlaybackPositionUpdateListener(new OnPlaybackPositionUpdateListener() {
          @Override
          public void onPeriodicNotification(AudioTrack arg0) {
            // "---onPeriodicNotification");
          }

          @Override
          public void onMarkerReached(AudioTrack arg0) {
            // "---onMarkerReached");
          }
        });
        audioTrack.play();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static byte[] getBytes(String filePath) {
    byte[] buffer = null;
    try {
      File file = new File(filePath);
      if (file.exists()) {
        FileInputStream fis = new FileInputStream(file);
        ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
        byte[] b = new byte[1024];
        int n;
        while ((n = fis.read(b)) != -1) {
          bos.write(b, 0, n);
        }
        fis.close();
        bos.close();
        buffer = bos.toByteArray();
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return buffer;
  }
}

Related Tutorials