media-codec无法编码和解码

时间:2018-06-17 09:30:16

标签: java android

我正在使用音频记录来录制音频,然后我使用媒体编解码器对其进行编码,稍后在需要时我使用media-codec对其进行解码但是我没有这样做,尽管我使用了类助手和我做了很多努力 任何人都可以告诉我有什么不对,我非常感激 检测到我的问题是dequeueOutputBuffer总是返回-1,它抛出超出绑定的异常 这是我的全部主要活动

package com.androidtechpoint.demo.androidvolley;

import android.media.MediaCodec;

import android.annotation.TargetApi;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaFormat;
import android.media.MediaRecorder;
import android.media.MediaRecorder.AudioSource;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;

public class Main2delete extends AppCompatActivity {
    private AudioRecord recorder;
    private AudioTrack player;
    int bitRate =128000;
    int sampleRate=44100;
    int channels = 1;
    private MediaCodec encoder;
    private MediaCodec decoder;
    private static final String AUDIO_MIME_TYPE = "audio/mp4a-latm";
    private static final int SAMPLE_RATE = 44100;
    private static final int SAMPLES_PER_FRAME = 1024;
    private static final int CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_MONO;
    private static final int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
    private short audioFormat = AudioFormat.ENCODING_PCM_16BIT;
    private short channelConfig = AudioFormat.CHANNEL_IN_MONO;
    private int bufferSize;
private boolean isRecording;
private boolean isPlaying;
Button btnstart ;
Button btnend;
Button btnlisten ;
ByteArrayInputStream is;
ByteArrayOutputStream outStream;
ByteArrayInputStream inputStream;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2delete);
    btnstart=(Button)findViewById(R.id.btnstart);
    btnlisten=(Button)findViewById(R.id.btnlisten);
    btnend=(Button)findViewById(R.id.btnend);
   outStream =new ByteArrayOutputStream();
 //   intSize = android.media.AudioTrack.getMinBufferSize(RECORDER_SAMPLERATE, RECORDER_CHANNELS_OUT, RECORDER_AUDIO_ENCODING);

    try {
        setEncoder();
    } catch (Exception e) {
        System.out.println(e.toString());
    }
    try {
       setDecoder();
    } catch (Exception e) {
        System.out.println(e.toString());
    }
    btnstart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            try {
                startRecording();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    });
    btnlisten.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           startPlaying();
        }
    });
    btnend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

           stopRecording();
        }
    });
}
public void startRecording () throws IOException
{
    int read;

    byte[] buffer1 = new byte[bufferSize];

    ByteBuffer[] inputBuffers;
    ByteBuffer[] outputBuffers;

    ByteBuffer inputBuffer;
    ByteBuffer outputBuffer;

    MediaCodec.BufferInfo bufferInfo;
    int inputBufferIndex;
    int outputBufferIndex;

    byte[] outData;

    encoder.start();
    recorder.startRecording();
    isRecording = true;

    while (isRecording)
    {
        read = recorder.read(buffer1, 0, bufferSize);
        // Log.d("AudioRecoder", read + " bytes read");
        //------------------------

        inputBuffers = encoder.getInputBuffers();
        outputBuffers = encoder.getOutputBuffers();
        inputBufferIndex = encoder.dequeueInputBuffer(-1);
        if (inputBufferIndex >= 0)
        {
            inputBuffer = inputBuffers[inputBufferIndex];
            inputBuffer.clear();

            inputBuffer.put(buffer1);

            encoder.queueInputBuffer(inputBufferIndex, 0, buffer1.length, 0, 0);
        }

        bufferInfo = new MediaCodec.BufferInfo();
        outputBufferIndex = encoder.dequeueOutputBuffer(bufferInfo, 10000);

        while (outputBufferIndex >= 0)
        {
            outputBuffer = outputBuffers[outputBufferIndex];

            outputBuffer.position(bufferInfo.offset);
            outputBuffer.limit(bufferInfo.offset + bufferInfo.size);

            outData = new byte[bufferInfo.size];
            outputBuffer.get(outData);

            //TODO write out Data to stream?
            outStream.write(outData);

            encoder.releaseOutputBuffer(outputBufferIndex, false);
            outputBufferIndex = encoder.dequeueOutputBuffer(bufferInfo, 0);

        }
        // ----------------------;

    }
    encoder.stop();
    recorder.stop();

}


public void stopRecording ()
{
    isRecording = false;
}


public void startPlaying()
{
    is= new ByteArrayInputStream(outStream.toByteArray());
    int len = 1024;
    byte[] buffer2 = new byte[len];

    byte[] data = new byte[len];

    ByteBuffer[] inputBuffers;
    ByteBuffer[] outputBuffers;

    ByteBuffer inputBuffer;
    ByteBuffer outputBuffer;

    MediaCodec.BufferInfo bufferInfo;
    int inputBufferIndex;
    int outputBufferIndex;
    byte[] outData;
    try
    {
        player.play();
        decoder.start();
        isPlaying = true;
        while (isPlaying)
        {

            int read = is.read(data);

            //===========
            inputBuffers = decoder.getInputBuffers();
            outputBuffers = decoder.getOutputBuffers();
            inputBufferIndex = decoder.dequeueInputBuffer(-1);
            if (inputBufferIndex >= 0)
            {
                inputBuffer = inputBuffers[inputBufferIndex];
                inputBuffer.clear();

                inputBuffer.put(data);

                decoder.queueInputBuffer(inputBufferIndex, 0, data.length, 0, 0);
            }

            bufferInfo = new MediaCodec.BufferInfo();
            outputBufferIndex = decoder.dequeueOutputBuffer(bufferInfo, 0);

            while (outputBufferIndex >= 10000)
            {
                outputBuffer = outputBuffers[outputBufferIndex];

                outputBuffer.position(bufferInfo.offset);
                outputBuffer.limit(bufferInfo.offset + bufferInfo.size);

                outData = new byte[bufferInfo.size];
                outputBuffer.get(outData);

                //  Log.d("AudioDecoder", outData.length + " bytes decoded");

                player.write(outData, 0, outData.length);

                decoder.releaseOutputBuffer(outputBufferIndex, false);
                outputBufferIndex = decoder.dequeueOutputBuffer(bufferInfo, 0);

            }

            //===========


        }

        decoder.stop();
        player.stop();

    }
    catch (Exception e)
    {
    }
}




private int initAudioRecord()
{
    try
    {
        int min_buffer_size = AudioRecord.getMinBufferSize(SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT);
        int buffer_size = SAMPLES_PER_FRAME * 10;
        if (buffer_size < min_buffer_size)
            buffer_size = ((min_buffer_size / SAMPLES_PER_FRAME) + 1) * SAMPLES_PER_FRAME * 2;

        recorder = new AudioRecord(
                MediaRecorder.AudioSource.MIC,       // source
                SAMPLE_RATE,                         // sample rate, hz
                CHANNEL_CONFIG,                      // channels
                AUDIO_FORMAT,                        // audio format
                buffer_size);                        // buffer size (bytes)

    }
    catch (Exception e)
    {
        Log.v("error", "rate" );
    }

    return -1;
}

public boolean setEncoder() throws Exception
{
    encoder = MediaCodec.createEncoderByType("audio/mp4a-latm");
    MediaFormat format = new MediaFormat();
    format.setString(MediaFormat.KEY_MIME, "audio/mp4a-latm");
    format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, channels);
    format.setInteger(MediaFormat.KEY_SAMPLE_RATE, sampleRate);
    format.setInteger(MediaFormat.KEY_BIT_RATE, bitRate );//AAC-HE 64kbps
    format.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectHE);
    encoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);

    initAudioRecord();

    return true;
}

public boolean setDecoder() throws Exception
{
    decoder = MediaCodec.createDecoderByType("audio/mp4a-latm");
    MediaFormat format = new MediaFormat();
    format.setString(MediaFormat.KEY_MIME, "audio/mp4a-latm");
    format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, channels/*1*/);
    format.setInteger(MediaFormat.KEY_SAMPLE_RATE, sampleRate/*44100*/);
    format.setInteger(MediaFormat.KEY_BIT_RATE, bitRate/*128000*/ );//AAC-HE 64kbps
    format.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectHE);

    decoder.configure(format, null, null, 0);

    setPlayer(sampleRate);

    return true;
}

public boolean setPlayer(int rate)
{
    int bufferSizePlayer = AudioTrack.getMinBufferSize(rate, AudioFormat.CHANNEL_OUT_MONO, audioFormat);
    Log.d("====buffer Size player ", String.valueOf(bufferSizePlayer));

    player= new AudioTrack(AudioManager.STREAM_MUSIC, rate, AudioFormat.CHANNEL_OUT_MONO, audioFormat, bufferSizePlayer, AudioTrack.MODE_STREAM);


    if (player.getState() == AudioTrack.STATE_INITIALIZED)
    {

        return true;
    }
    else
    {
        return false;
    }

}
}

0 个答案:

没有答案