#ifndef HELMET_AUDIOVIDEO_H
#define HELMET_AUDIOVIDEO_H
#include <jni.h>
#include <android/log.h>
extern "C" {
#include "libavformat/avformat.h"
#include "libavcodec/avcodec.h"
#include "libavfilter/avfilter.h"
#include "libavfilter/buffersink.h"
#include "libavutil/imgutils.h"
#include "libavfilter/buffersrc.h"
}
class AudioVideo {
public:
int audioInit(JNIEnv *env, jstring pushPath);
void audioEncoder(JNIEnv *env, jbyte *byte, int byteLength);
};
#endif
#include "AudioVideo.h"
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, "PushFlow",__VA_ARGS__)
AVFormatContext *audioFormatContext;
AVCodec *audioCodec;
AVCodecContext *audioCodecCtx;
AVStream *audioStream;
int audioBufferSize;
AVFrame *audioFrame;
AVPacket *audioPacket;
uint8_t *audioBuffer;
const char *pushPath;
int AudioVideo::audioInit(JNIEnv *env, jstring path) {
pushPath = env->GetStringUTFChars(path, 0);
av_register_all();
avformat_alloc_output_context2(&audioFormatContext, NULL, "flv", pushPath);
if (avio_open(&audioFormatContext->pb, pushPath, AVIO_FLAG_READ_WRITE) < 0) return -1;
audioCodec = avcodec_find_encoder_by_name("libfdk_aac");
if (audioCodec == NULL) return -1;
audioCodecCtx = avcodec_alloc_context3(audioCodec);
audioCodecCtx->codec_id = audioCodec->id;
audioCodecCtx->codec_type = AVMEDIA_TYPE_AUDIO;
audioCodecCtx->sample_fmt = AV_SAMPLE_FMT_S16;
audioCodecCtx->sample_rate = 8000;
audioCodecCtx->channel_layout = AV_CH_LAYOUT_MONO;
audioCodecCtx->channels = 1;
audioCodecCtx->bit_rate = 128000;
audioStream = avformat_new_stream(audioFormatContext, audioCodec);
if (audioStream == NULL) return -1;
if (avcodec_parameters_from_context(audioStream->codecpar, audioCodecCtx) < 0) return -1;
if (avcodec_open2(audioCodecCtx, audioCodec, NULL) < 0) return -1;
avformat_write_header(audioFormatContext, NULL);
audioFrame = av_frame_alloc();
audioFrame->nb_samples = audioCodecCtx->frame_size;
audioFrame->format = audioCodecCtx->sample_fmt;
audioBufferSize = av_samples_get_buffer_size(NULL,
audioCodecCtx->channels,
audioCodecCtx->frame_size,
audioCodecCtx->sample_fmt,
1);
audioBuffer = (uint8_t *) av_malloc(audioBufferSize);
avcodec_fill_audio_frame(audioFrame,
audioCodecCtx->channels,
audioCodecCtx->sample_fmt,
(const uint8_t *) audioBuffer,
audioBufferSize,
1);
audioPacket = (AVPacket *) av_malloc(audioBufferSize);
return 0;
}
void AudioVideo::audioEncoder(JNIEnv *env, jbyte *byte, int byteLength) {
int ret;
memcpy(audioFrame->data[0], byte, byteLength);
ret = avcodec_send_frame(audioCodecCtx, audioFrame);
if (ret < 0) return;
ret = avcodec_receive_packet(audioCodecCtx, audioPacket);
if (ret < 0) return;
ret = av_interleaved_write_frame(audioFormatContext, audioPacket);
if (ret < 0) return;
LOGE("音频编码写入成功");
av_packet_unref(audioPacket);
}