---
# System prepended metadata

title: Untitled

---

```java=
public class PGMediaExtractor {

    private static final int DEFAULT_BUFFER_SIZE = 1 * 1024 * 1024;
    private static final String TAG = "AudioExtractorDecoder";
    private int bufferSize = -1;

    public List<Float> getAudioFloatArrayFromVideo(String path) throws IOException {
        MediaExtractor audioExtractor = new MediaExtractor();
        audioExtractor.setDataSource(path);
        MediaFormat audioFormat = null;
        int audioTrackCount = audioExtractor.getTrackCount();
        for (int i = 0; i < audioTrackCount; i++) {
            audioFormat = audioExtractor.getTrackFormat(i);
            String mimeType = audioFormat.getString(MediaFormat.KEY_MIME);
            if (mimeType.startsWith("audio/")) {
                audioExtractor.selectTrack(i);
                if (audioFormat.containsKey(MediaFormat.KEY_MAX_INPUT_SIZE)) {
                    int newSize = audioFormat.getInteger(MediaFormat.KEY_MAX_INPUT_SIZE);
                    bufferSize = Math.max(newSize, bufferSize);
                }
            }
        }

        if (bufferSize < 0) {
            bufferSize = DEFAULT_BUFFER_SIZE;
        }

        int offset = 0;
        ByteBuffer dstBuf = ByteBuffer.allocate(bufferSize);
        List<Float> floatList = new ArrayList<>();
        MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();

        while (true) {
            bufferInfo.offset = offset;
            bufferInfo.size = audioExtractor.readSampleData(dstBuf, offset);
            if (bufferInfo.size < 0) {
                Log.d(TAG, "Saw input EOS.");
                bufferInfo.size = 0;
                break;
            } else {
                bufferInfo.presentationTimeUs = audioExtractor.getSampleTime();
                bufferInfo.flags = audioExtractor.getSampleFlags();

//                int position = dstBuf.position();
//                int limit = dstBuf.limit();
//                while (position < limit) {
//                    int sample = dstBuf.getShort(position);
//                    Timber.d("sample " + sample);
//                    float sample32bit = (float) sample / Short.MAX_VALUE;
//                    position += 2;
//                }
                // 這裡好像要 decode?
                audioExtractor.advance();
            }
        }
        audioExtractor.release();
        audioExtractor = null;
        return floatList;
    }
}