移动流媒体

Android OpenSL ES播放pcm文件

2019-01-03  本文已影响71人  张俊峰0613

1、OpenSL ES介绍

OpenSL ES (Open Sound Library for Embedded Systems)是无授权费、跨平台、针对嵌入式系统精心优化的硬件音频加速API。它为嵌入式移动多媒体设备上的本地应用程序开发者提供标准化, 高性能,低响应时间的音频功能实现方法,并实现软/硬件音频性能的直接跨平台部署,降低执行难度,促进高级音频市场的发展。简单来说OpenSL ES是一个嵌入式跨平台免费的音频处理库。

2、OpenSL ES开发流程

OpenSL ES 的开发流程主要有如下6个步骤:

1、 创建接口对象

2、设置混音器

3、创建播放器(录音器)

4、设置缓冲队列和回调函数

5、设置播放状态

6、启动回调函数

注明:其中第4步和第6步是OpenSL ES 播放PCM等数据格式的音频是需要用到的

在使用OpenSL ES的API之前,需要引入OpenSL ES的头文件:

#include <SLES/OpenSLES.h>
#include <SLES/OpenSLES_Android.h>

由于是在Native层使用该特性,如果是ndk开发的话,需要在Android.mk中增加链接选项,以便在链接阶段使用到系统系统的OpenSL ES的so库:

LOCAL_LDLIBS += -lOepnSLES

如果是Cmake开发的话,需要在CmakeLists.txt中添加链接选项:

target_link_libraries( # Specifies the target library.
        native-lib
        OpenSLES
        # Links the target library to the log library
        # included in the NDK.
        ${log-lib})

我们知道OpenSL ES提供的是基于C语言的API,但是它是基于对象和接口的方式提供的,会采用面向对象的思想开发API。因此我们先来了解一下OpenSL ES中对象和接口的概念:

如果明白了OpenSL ES 中对象和接口的概念,那么下面我们就继续看看,在代码中是如何使用它们的。

上面我们也提到过,对象是没有实际的代码表示形式的,对象的创建也是通过接口来完成的。通过获取对象的方法来获取出对象,进而可以访问对象的其他的接口方法或者改变对象的状态,下面是使用对象和接口的相关说明。

2.1、OpenSL ES 开发最重要的接口类 SLObjectItf

通过SLObjectItf接口类我们可以创建所需要的各种类型的类接口,比如:

2.2、SLObjectItf 创建的具体的接口对象实例

OpenSL ES中也有具体的接口类,比如(引擎:SLEngineItf,播放器:SLPlayItf,声音控制器:SLVolumeItf等等)。

2.3、创建引擎并实现

OpenSL ES创建引擎步骤:

SLObjectItf engineObject = NULL;//用SLObjectItf声明引擎接口对象
SLEngineItf engineEngine = NULL;//声明具体的引擎对象实例

slCreateEngine(&engineObject,0,0,0,0,0);//第一步创建引擎
(*engineObject)->Realize(engineObject,SL_BOOLEAN_FALSE);//实现(Realize)engineObject接口对象
(*engineObject)->GetInterface(engineObject,SL_IID_ENGINE,&engineEngine);//通过engineObject的GetInterface方法初始化engineEngine

2.4、利用引擎对象创建其他接口对象

其他接口对象(我们要播放pcm文件,就要创建混音器接口对象(SLObjectItf outputMixObject)、播放器接口对象(SLObjectItf playerObject))等都是用引擎接口对象创建的(具体的接口对象需要的参数这里就说了,可参照ndk例子里面的),如:

//混音器
SLObjectItf outputMixObject = NULL;//用SLObjectItf创建混音器接口对象
SLEnvironmentalReverbItf outputMixEnvironmentalReverb = NULL;//创建具体的混音器对象实例
 
(*engineEngine)->CreateOutputMix(engineEngine, &outputMixObject, 1, mids, mreq);//利用引擎接口对象创建混音器接口对象
(*outputMixObject)->Realize(outputMixObject, SL_BOOLEAN_FALSE);//实现(Realize)混音器接口对象
result = (*outputMixObject)->GetInterface(outputMixObject, SL_IID_ENVIRONMENTALREVERB, &outputMixEnvironmentalReverb);//利用混音器接口对象初始化具体混音器实例
 
//播放器
SLObjectItf playerObject = NULL;//用SLObjectItf创建播放器接口对象
SLPlayItf playerPlay = NULL;//创建具体的播放器对象实例
 
(*engineEngine)->CreateAudioPlayer(engineEngine, &playerObject, &audioSrc, &audioSnk, 3, ids, req);//利用引擎接口对象创建播放器接口对象
(*playerObject)->Realize(playerObject, SL_BOOLEAN_FALSE);//实现(Realize)播放器接口对象
(*playerObject)->GetInterface(playerObject, SL_IID_PLAY, &playerPlay);//初始化具体的播放器对象实例

\color{red}{最后就是使用创建好的具体对象实例来实现具体的功能}

3、Android OpenSL ES播放pcm文件

3.1、创建支持C++的Android Studio项目

3.2、编写Android Studio项目的Java代码

3.2.1、布局文件

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/etUrl"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Charlie Puth - Look At Me Now.pcm"/>

    <Button
        android:id="@+id/btnPlay"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="play"
        android:text="播放"/>
</LinearLayout>

3.2.2、Android文件
MainActivity.java

public class MainActivity extends AppCompatActivity {

    String BASE_PATH = Environment.getExternalStorageDirectory().getPath();
    private EditText etUrl;
    private Button btnPlay;
    static {
        System.loadLibrary("native-lib");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        etUrl = (EditText) findViewById(R.id.etUrl);
        btnPlay = (Button) findViewById(R.id.btnPlay);
    }

    public native void palyPcm(String url);

    public void play(View view) {
        String path = BASE_PATH + "/" + etUrl.getText().toString();
        Log.d("ZJF",path);
        palyPcm(path);
    }
}

3.3、编写jni代码

按照OpenSL ES开发流程我们分为6个步骤!

3.3.1、创建接口对象

SLObjectItf engineObject = NULL;//用SLObjectItf声明引擎接口对象
SLEngineItf engineEngine = NULL;//声明具体的引擎对象实例
 // 1、创建一个引擎:三部曲 slCreateEngine->Realize->GetInterface
slCreateEngine(&engineObject,0,0,0,0,0);//第一步创建引擎
(*engineObject)->Realize(engineObject,SL_BOOLEAN_FALSE);//第二步实现(Realize)engineObject接口对象
(*engineObject)->GetInterface(engineObject,SL_IID_ENGINE,&engineEngine);//第三部通过engineObject的GetInterface方法初始化engineEngine

3.3.2、设置混音器

SLObjectItf outputMixObject = NULL;//用SLObjectItf创建混音器接口对象
SLEnvironmentalReverbItf outputMixEnvReb = NULL;//创建具体的混音器对象实例
SLEnvironmentalReverbSettings reverbSettings = SL_I3DL2_ENVIRONMENT_PRESET_STONECORRIDOR;

// 2、设置混音器:创建混音器引擎->设置混音器属性
const SLInterfaceID mids[1] = {SL_IID_ENVIRONMENTALREVERB};
const SLboolean mrep[1] = {SL_BOOLEAN_FALSE};

(*engineEngine)->CreateOutputMix(engineEngine,&outputMixObject,1,mids,mrep);
(*outputMixObject)->Realize(outputMixObject,SL_BOOLEAN_FALSE);
(*outputMixObject)->GetInterface(outputMixObject,SL_IID_ENVIRONMENTALREVERB,&outputMixEnvReb);
(*outputMixEnvReb)->SetEnvironmentalReverbProperties(outputMixEnvReb,&reverbSettings);

3.3.3、创建播放器

SLObjectItf pcmPlayerObject = NULL;
SLPlayItf pcmPlayerPlay = NULL;

// 3、创建播放器
SLDataLocator_AndroidSimpleBufferQueue android_queue = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE,2};//一个队列
SLDataFormat_PCM format_pcm = {//设置PCM播放时的属性
        SL_DATAFORMAT_PCM,//播放pcm格式的数据
        2,//2个声道(立体声)
        SL_SAMPLINGRATE_44_1,//44100hz的频率
        SL_PCMSAMPLEFORMAT_FIXED_16,//位数 16位
        SL_PCMSAMPLEFORMAT_FIXED_16,//和位数一致就行
        SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT,//立体声(前左前右)
        SL_BYTEORDER_LITTLEENDIAN//结束标志
};
SLDataSource slDataSource ={&android_queue,&format_pcm};

SLDataLocator_OutputMix outputMix = {SL_DATALOCATOR_OUTPUTMIX,outputMixObject};
SLDataSink audioSink = {&outputMix,NULL};

const SLInterfaceID ids[1] = {SL_IID_BUFFERQUEUE};
const SLboolean req[1] = {SL_BOOLEAN_TRUE};
(*engineEngine)->CreateAudioPlayer(engineEngine,&pcmPlayerObject,&slDataSource,&audioSink,1,ids,req);
(*pcmPlayerObject)->Realize(pcmPlayerObject,SL_BOOLEAN_FALSE);
(*pcmPlayerObject)->GetInterface(pcmPlayerObject,SL_IID_PLAY,&pcmPlayerPlay);

3.3.4、设置缓冲队列和回调函数

SLAndroidSimpleBufferQueueItf pcmBufferQueue = NULL;
//回调方法
void pcmBufferCallback(SLAndroidSimpleBufferQueueItf bf,void *context){
    int size = getPcmData(&buffer);
    if (buffer != NULL){
        (*pcmBufferQueue)->Enqueue(pcmBufferQueue,buffer,size);
    }
}
/*
*获取pcm文件的数据
**/

FILE *pcmFile;//待播放的文件路径
void *buffer;//保存pcm数据,整个文件的,不断的从out_buffer中读取出来
uint8_t *out_buffer;//保存从pcm文件中每秒读取出来的pcm数据

int getPcmData(void **pcm){
    int size = 0;
    while (!feof(pcmFile)){
        size = fread(out_buffer,1,44100 * 2 * 2,pcmFile);
        if (out_buffer == NULL) {
            LOGD("READ ENG...");
            break;
        } else {
            LOGD("READING...");
        }
        *pcm = out_buffer;
        break;
    }
    return size;
}


//4、设置缓冲队列和回调函数
(*pcmPlayerObject)->GetInterface(pcmPlayerObject,SL_IID_BUFFERQUEUE,&pcmBufferQueue);
(*pcmBufferQueue)->RegisterCallback(pcmBufferQueue,pcmBufferCallback,NULL);

3.3.5、设置播放状态

//5、设置播放状态
(*pcmPlayerPlay)->SetPlayState(pcmPlayerPlay,SL_PLAYSTATE_PLAYING);

3.3.6、启动回调函数

//启动回调函数
pcmBufferCallback(pcmBufferQueue,NULL);

3.3.6、jni源码

#include <jni.h>
#include <string>
#include <android/log.h>
#include <SLES/OpenSLES.h>
#include <SLES/OpenSLES_Android.h>

extern "C" {
    #define LOGD(FORMAT,...) __android_log_print(ANDROID_LOG_DEBUG,"zjf",FORMAT,##__VA_ARGS__);
    #define LOGE(FORMAT,...) __android_log_print(ANDROID_LOG_ERROR,"zjf",FORMAT,##__VA_ARGS__);
};

/**
 *  1、创建接口对象

    2、设置混音器

    3、创建播放器(录音器)

    4、设置缓冲队列和回调函数

    5、设置播放状态

    6、启动回调函数

 */

SLObjectItf engineObject = NULL;
SLEngineItf engineEngine = NULL;

SLObjectItf outputMixObject = NULL;
SLEnvironmentalReverbItf outputMixEnvReb = NULL;
SLEnvironmentalReverbSettings reverbSettings = SL_I3DL2_ENVIRONMENT_PRESET_STONECORRIDOR;

SLObjectItf pcmPlayerObject = NULL;
SLPlayItf pcmPlayerPlay = NULL;

SLAndroidSimpleBufferQueueItf pcmBufferQueue = NULL;


FILE *pcmFile;
void *buffer;
uint8_t *out_buffer;


int getPcmData(void **pcm){
    int size = 0;
    while (!feof(pcmFile)){
        size = fread(out_buffer,1,44100 * 2 * 2,pcmFile);
        if (out_buffer == NULL) {
            LOGD("READ ENG...");
            break;
        } else {
            LOGD("READING...");
        }
        *pcm = out_buffer;
        break;
    }
    return size;
}

void pcmBufferCallback(SLAndroidSimpleBufferQueueItf bf,void *context){
    int size = getPcmData(&buffer);
    if (buffer != NULL){
        (*pcmBufferQueue)->Enqueue(pcmBufferQueue,buffer,size);
    }
}
extern "C"
JNIEXPORT void JNICALL
Java_com_example_zjf_androidopenslaudio_MainActivity_palyPcm(JNIEnv *env, jobject instance,
                                                             jstring url_) {
    const char *url = env->GetStringUTFChars(url_, 0);

    pcmFile = fopen(url,"r");
    if (pcmFile == NULL) {
        LOGE("打不开文件 url === %s",url);
        return;
    }

    out_buffer = (uint8_t *)malloc(44100 * 2 * 2);
    // 1、创建一个引擎:三部曲 slCreateEngine->Realize->GetInterface
    slCreateEngine(&engineObject,0,0,0,0,0);
    (*engineObject)->Realize(engineObject,SL_BOOLEAN_FALSE);
    (*engineObject)->GetInterface(engineObject,SL_IID_ENGINE,&engineEngine);


    // 2、设置混音器:创建混音器引擎->设置混音器属性
    const SLInterfaceID mids[1] = {SL_IID_ENVIRONMENTALREVERB};
    const SLboolean mrep[1] = {SL_BOOLEAN_FALSE};

    (*engineEngine)->CreateOutputMix(engineEngine,&outputMixObject,1,mids,mrep);
    (*outputMixObject)->Realize(outputMixObject,SL_BOOLEAN_FALSE);
    (*outputMixObject)->GetInterface(outputMixObject,SL_IID_ENVIRONMENTALREVERB,&outputMixEnvReb);

    (*outputMixEnvReb)->SetEnvironmentalReverbProperties(outputMixEnvReb,&reverbSettings);


    // 3、创建播放器
    SLDataLocator_AndroidSimpleBufferQueue android_queue = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE,2};//一个队列
    SLDataFormat_PCM format_pcm = {//设置PCM播放时的属性
            SL_DATAFORMAT_PCM,
            2,
            SL_SAMPLINGRATE_44_1,
            SL_PCMSAMPLEFORMAT_FIXED_16,
            SL_PCMSAMPLEFORMAT_FIXED_16,
            SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT,
            SL_BYTEORDER_LITTLEENDIAN
    };
    SLDataSource slDataSource ={&android_queue,&format_pcm};

    SLDataLocator_OutputMix outputMix = {SL_DATALOCATOR_OUTPUTMIX,outputMixObject};
    SLDataSink audioSink = {&outputMix,NULL};

    const SLInterfaceID ids[1] = {SL_IID_BUFFERQUEUE};
    const SLboolean req[1] = {SL_BOOLEAN_TRUE};
    (*engineEngine)->CreateAudioPlayer(engineEngine,&pcmPlayerObject,&slDataSource,&audioSink,1,ids,req);
    (*pcmPlayerObject)->Realize(pcmPlayerObject,SL_BOOLEAN_FALSE);
    (*pcmPlayerObject)->GetInterface(pcmPlayerObject,SL_IID_PLAY,&pcmPlayerPlay);


    //4、设置缓冲队列和回调函数
    (*pcmPlayerObject)->GetInterface(pcmPlayerObject,SL_IID_BUFFERQUEUE,&pcmBufferQueue);
    (*pcmBufferQueue)->RegisterCallback(pcmBufferQueue,pcmBufferCallback,NULL);


    //5、设置播放状态
    (*pcmPlayerPlay)->SetPlayState(pcmPlayerPlay,SL_PLAYSTATE_PLAYING);

    pcmBufferCallback(pcmBufferQueue,NULL);


    env->ReleaseStringUTFChars(url_, url);
}

4、遇到的问题

01-03 12:36:32.545 30764-30764/com.example.zjf.androidopenslaudio D/ZJF: /storage/emulated/0/Charlie Puth - Look At Me Now.pcm
01-03 12:36:32.565 30764-30764/com.example.zjf.androidopenslaudio E/libOpenSLES: pAudioSrc: data format 2 not allowed
01-03 12:36:32.565 30764-30764/com.example.zjf.androidopenslaudio W/libOpenSLES: Leaving Engine::CreateAudioPlayer (SL_RESULT_CONTENT_UNSUPPORTED)
01-03 12:36:32.565 30764-30764/com.example.zjf.androidopenslaudio A/libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0x0 in tid 30764 (roidopenslaudio)

创建播放器时:

SLDataLocator_AndroidBufferQueue android_queue = {SL_DATALOCATOR_ANDROIDBUFFERQUEUE,2};//一个队列

改为:

SLDataLocator_AndroidSimpleBufferQueue android_queue = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE,2};//一个队列

源码:https://github.com/Xiaoben336/AndroidOpenSLAudio

上一篇下一篇

猜你喜欢

热点阅读