Android NDK開發之旅32 FFmpeg+AudioTrack音頻播放

###前言 #####基於Android NDK開發之旅31--FFmpeg音頻解碼這篇文章,咱們已經學會音頻解碼基本過程。 #####音頻播放有兩種方法:FFmpeg+AudioTrack(Android自帶的播放工具) 、FFmpeg+OpenSL ES。 #####這篇文章就經過FFmpeg+AudioTrack方式對音頻解碼的文件進行播放操做。java

####1.Java中 jni聲明android

package com.haocai.ffmpegtest.util;

import android.view.Surface;

public class VideoPlayer {

	//音頻播放
	public native void audioPlayer(String input);

	static{
		System.loadLibrary("avutil-54");
		System.loadLibrary("swresample-1");
		System.loadLibrary("avcodec-56");
		System.loadLibrary("avformat-56");
		System.loadLibrary("swscale-3");
		System.loadLibrary("postproc-53");
		System.loadLibrary("avfilter-5");
		System.loadLibrary("avdevice-56");
		System.loadLibrary("myffmpeg");
	}


}
複製代碼

####2.定義播放模塊AudioTrackgit

package com.haocai.ffmpegtest.util;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.util.Log;

/**
 * Created by Xionghu on 2017/12/12.
 * Desc:
 */

public class AudioUtil {

    //Todo 生成JNI簽名後刪除 該聲明
    //Todo 該聲明 來源於 audioTrack.write()
    public int write(byte[] audioData, int offsetInBytes, int sizeInBytes) {
        return 0;
    }

    /**
     * 建立一個AudioTrack對象,用於播放
     * @return
     */
    public AudioTrack createAudioTrack(int sampleRateInHz, int nb_channels){
        Log.i("AudioUtil", "nb_channels:"+nb_channels);
        Log.i("AudioUtil", "sampleRateInHz:"+sampleRateInHz);
        //固定格式的音頻碼流
        int audioFormat = AudioFormat.ENCODING_PCM_16BIT;

        //聲道個數 影響聲道的佈局
        int channelConfig;
        if(nb_channels == 1){
            channelConfig = android.media.AudioFormat.CHANNEL_OUT_MONO;
        }else if(nb_channels == 2){
            channelConfig = android.media.AudioFormat.CHANNEL_OUT_STEREO;
        }else{
            channelConfig = android.media.AudioFormat.CHANNEL_OUT_STEREO;
        }

        int bufferSizeInBytes = AudioTrack.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat);
        AudioTrack audioTrack = new AudioTrack(
                AudioManager.STREAM_MUSIC,
                sampleRateInHz, channelConfig,
                audioFormat,
                bufferSizeInBytes, AudioTrack.MODE_STREAM);
        //audioTrack.write()
        return audioTrack;
    }

}

複製代碼

####3.獲取播放模塊AudioTrack相關方法的簽名 #####3.1Build ->Rebuild Project 獲得編譯文件classes github

#####3.2經過javap獲得方法的簽名 ######Windows 命令模式下數組

D:\>CD D:\AndroidProject\FFmpegTest\app\build\intermediates\classes\debug

D:\AndroidProject\FFmpegTest\app\build\intermediates\classes\debug> javap -s -p com.haocai.ffmpegtest.util.AudioUtil
Compiled from "AudioUtil.java"
public class com.haocai.ffmpegtest.util.AudioUtil {
  public com.haocai.ffmpegtest.util.AudioUtil();
    descriptor: ()V

  public int write(byte[], int, int);
    descriptor: ([BII)I

  public android.media.AudioTrack createAudioTrack(int, int);
    descriptor: (II)Landroid/media/AudioTrack;
}
複製代碼

獲取簽名

####4.編寫音頻解碼播放功能 ######ffmpeg_voicer.cbash

#include <com_haocai_ffmpegtest_util_VideoPlayer.h>
#include <android/log.h>
#include <android/native_window_jni.h>
#include <android/native_window.h>
#include <unistd.h>
#include <stdlib.h>
//解碼
#include "include/libavcodec/avcodec.h"
//封裝格式處理
#include "include/libavformat/avformat.h"
//像素處理
#include "include/libswscale/swscale.h"
//重採樣
#include "include/libswresample/swresample.h"


#define LOG_TAG "ffmpegandroidplayer"
#define LOGI(FORMAT,...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,FORMAT,##__VA_ARGS__);
#define LOGE(FORMAT,...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,FORMAT,##__VA_ARGS__);
#define LOGD(FORMAT,...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG,FORMAT, ##__VA_ARGS__)

//音頻解碼 採樣率 新版版可達48000 * 4
#define MAX_AUDIO_FRME_SIZE 2 * 44100


//音頻播放
JNIEXPORT void JNICALL Java_com_haocai_ffmpegtest_util_VideoPlayer_audioPlayer
(JNIEnv *env, jobject jobj, jstring input_jstr) {
	const char* input_cstr = (*env)->GetStringUTFChars(env, input_jstr, NULL);
	LOGI("%s", "init");
	//註冊組件
	av_register_all();
	AVFormatContext *pFormatCtx = avformat_alloc_context();
	//打開音頻文件
	if (avformat_open_input(&pFormatCtx, input_cstr, NULL, NULL) != 0) {
		LOGI("%s", "沒法打開音頻文件");
		return;
	}
	//獲取輸入文件信息
	if (avformat_find_stream_info(pFormatCtx, NULL) < 0) {
		LOGI("%s", "沒法獲取輸入文件信息");
		return;
	}
	//獲取音頻流索引位置
	int i = 0, audio_stream_idx = -1;
	for (; i < pFormatCtx->nb_streams; i++) {
		if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
			audio_stream_idx = i;
			break;
		}
	}
	if (audio_stream_idx == -1)
	{
		LOGI("%s", "找不到音頻流");
		return;
	}
	//獲取解碼器
	AVCodecContext *pCodeCtx = pFormatCtx->streams[audio_stream_idx]->codec;
	AVCodec *codec = avcodec_find_decoder(pCodeCtx->codec_id);
	if (codec == NULL) {
		LOGI("%s", "沒法獲取加碼器");
		return;
	}
	//打開解碼器
	if (avcodec_open2(pCodeCtx, codec, NULL) < 0) {
		LOGI("%s", "沒法打開解碼器");
		return;
	}

	//壓縮數據
	AVPacket *packet = (AVPacket *)av_malloc(sizeof(AVPacket));
	//解壓縮數據
	AVFrame *frame = av_frame_alloc();
	//frame->16bit  44100 PCM 統一音頻採樣格式與採樣率
	SwrContext *swrCtx = swr_alloc();

	//輸入採樣率格式
	enum AVSampleFormat in_sample_fmt = pCodeCtx->sample_fmt;
	//輸出採樣率格式16bit PCM
	enum AVSampleFormat out_sample_fmt = AV_SAMPLE_FMT_S16;
	//輸入採樣率
	int in_sample_rate = pCodeCtx->sample_rate;
	//輸出採樣率
	int out_sample_rate = 44100;
	//獲取輸入的聲道佈局
	//根據聲道個數獲取默認的聲道佈局(2個聲道,默認立體聲)
	//av_get_default_channel_layout(pCodeCtx->channels);
	uint64_t in_ch_layout = pCodeCtx->channel_layout;
	//輸出的聲道佈局
	uint64_t out_ch_layout = AV_CH_LAYOUT_STEREO;


	swr_alloc_set_opts(swrCtx, out_ch_layout, out_sample_fmt, out_sample_rate, in_ch_layout, in_sample_fmt, in_sample_rate, 0, NULL);


	swr_init(swrCtx);

	//獲取輸入輸出的聲道個數
	int out_channel_nb = av_get_channel_layout_nb_channels(out_ch_layout);
	LOGI("out_count:%d", out_channel_nb);

     //jclass  player_class = (*env)->GetObjectClass(env,jobj);

    jclass cls = (*env)->FindClass(env, "com/haocai/ffmpegtest/util/AudioUtil");
     //jmethodID
    jmethodID  constructor_mid= (*env)->GetMethodID(env, cls,"<init>","()V");

    //實例化一個AudioUtil對象(能夠在constructor_mid後加參)
    jobject audioutil_obj =  (*env)->NewObject(env, cls, constructor_mid);   //相似於AudioUtil audioutil =new AudioUtil();

    //AudioTrack對象
    jmethodID create_audio_track_mid =(*env)->GetMethodID(env,cls,"createAudioTrack","(II)Landroid/media/AudioTrack;");
 	jobject audio_track = (*env)->CallObjectMethod(env,audioutil_obj,create_audio_track_mid,out_sample_rate,out_channel_nb);

 	//調用AudioTrack.play方法
 	jclass audio_track_class = (*env)->GetObjectClass(env,audio_track);
 	jmethodID audio_track_play_mid = (*env)->GetMethodID(env,audio_track_class,"play","()V");
 	(*env)->CallVoidMethod(env,audio_track,audio_track_play_mid);

    //AudioTrack.write
    jmethodID audio_track_write_mid =  (*env)->GetMethodID(env,audio_track_class,"write","([BII)I");

	//16bit 44100 PCM 數據
	uint8_t *out_buffer = (uint8_t *)av_malloc(MAX_AUDIO_FRME_SIZE);

	int got_frame = 0, framecount = 0, ret;
	//6.一幀一幀讀取壓縮的音頻數據AVPacket
	while (av_read_frame(pFormatCtx, packet) >= 0) {
		//解碼音頻類型的Packet,  packet 有多是音頻數據流 有多是視頻數據流
		if (packet->stream_index == audio_stream_idx) {
			//解碼
			ret = avcodec_decode_audio4(pCodeCtx, frame, &got_frame, packet);

			if (ret < 0) {
				LOGI("%s", "解碼完成");
				break;
			}
			//非0,正在解碼
			if (got_frame > 0) {
				LOGI("解碼:%d", framecount++);
				swr_convert(swrCtx, &out_buffer, MAX_AUDIO_FRME_SIZE, (const uint8_t **)frame->data, frame->nb_samples);
				//獲取sample的size
				int out_buffer_size = av_samples_get_buffer_size(NULL, out_channel_nb, frame->nb_samples, out_sample_fmt, 1);
                //out_buffer 緩衝區數據,轉換成byte數組
                jbyteArray audio_sample_array =  (*env)->NewByteArray(env,out_buffer_size);

                jbyte* sample_byte = (*env)->GetByteArrayElements(env,audio_sample_array,NULL);

                 //將out_buffer的數據複製到sample_byte
                 memcpy(sample_byte,out_buffer,out_buffer_size);

                 //同步數據 同時釋放sample_byte
                 (*env)->ReleaseByteArrayElements(env,audio_sample_array,sample_byte,0);

                //AudioTrack.write PCM數據
                 (*env)->CallIntMethod(env,audio_track,audio_track_write_mid,audio_sample_array,0,out_buffer_size);

                 //釋放局部引用  不然報錯JNI ERROR (app bug): local reference table overflow (max=512)
                 (*env)->DeleteLocalRef(env,audio_sample_array);
                usleep(1000 * 16); //16ms
			}
		}
		av_free_packet(packet);
	}
	av_frame_free(&frame);
	av_free(out_buffer);
	swr_free(&swrCtx);
	avcodec_close(pCodeCtx);
	avformat_close_input(&pFormatCtx);

	(*env)->ReleaseStringUTFChars(env, input_jstr, input_cstr);


}

複製代碼

####5.調用音頻播放功能app

/**
     * 音頻解碼
     */
    public void audioPlayer(){
        /**
         * 1.播放視頻文件中的音頻
         */
    //   String input = new File(Environment.getExternalStorageDirectory(),"告白氣球.avi").getAbsolutePath();

        /**
         * 2.播放音頻文件中的音頻
         */
        String input = new File(Environment.getExternalStorageDirectory(),"說散就散.mp3").getAbsolutePath();
        VideoPlayer player = new VideoPlayer();
        player.audioPlayer(input);
        Log.d("Main","正在播放");
    }
}
複製代碼

####6.調用音頻播放功能 ######Log輸出ide

I/ffmpegandroidplayer: init
I/ffmpegandroidplayer: out_count:2
I/AudioUtil: nb_channels:2
I/AudioUtil: sampleRateInHz:44100
I/ffmpegandroidplayer: 解碼:0
I/ffmpegandroidplayer: 解碼:1
I/ffmpegandroidplayer: 解碼:2
I/ffmpegandroidplayer: 解碼:3
I/ffmpegandroidplayer: 解碼:4
太多省略......
複製代碼

######至此,音頻播放功能已完成。工具

###源碼下載 #####Github:github.com/kpioneer123…佈局

###特別感謝: 動腦學院Jason

相關文章
相關標籤/搜索