一.包含头文件和库文件
CMakeLists
1target_link_libraries( # Specifies the target library. 2 native-lib 3 OpenSLES 4 5 # Links the target library to the log library 6 # included in the NDK. 7 ${log-lib} )
代码
1#include <SLES/OpenSLES.h> 2#include <SLES/OpenSLES_Android.h>
二.示例代码
1#include <jni.h> 2#include <string> 3#include <android/log.h> 4#include <SLES/OpenSLES.h> 5#include <SLES/OpenSLES_Android.h> 6 7 8#define LOG_TAG "xp.chen" 9#ifdef LOG_TAG 10 #define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__) 11 #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__) 12 #define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE,LOG_TAG,__VA_ARGS__) 13#else 14 #define LOGI(...) 15 #define LOGE(...) 16 #define LOGV(...) 17#endif 18 19 20static SLObjectItf engineSL = NULL; 21SLEngineItf CreateSL() 22{ 23 SLresult ret; 24 SLEngineItf en; 25 // 创建引擎 26 ret = slCreateEngine(&engineSL, 0, 0, 0, 0, 0); 27 if (ret != SL_RESULT_SUCCESS) { 28 LOGE("slCreateEngine() failed "); 29 return NULL; 30 } 31 // 实例化 32 ret = (*engineSL)->Realize(engineSL, SL_BOOLEAN_FALSE); 33 if (ret != SL_RESULT_SUCCESS) { 34 LOGE("Realize failed"); 35 return NULL; 36 } 37 // 获取接口 38 ret = (*engineSL)->GetInterface(engineSL, SL_IID_ENGINE, &en); 39 if (ret != SL_RESULT_SUCCESS) { 40 LOGE("GetInterface failed"); 41 return NULL; 42 } 43 return en; 44} 45 46 47extern "C" JNIEXPORT jstring 48JNICALL 49Java_com_yuneec_yongdaimi_testopensl_MainActivity_stringFromJNI( 50 JNIEnv *env, 51 jobject /* this */) { 52 std::string hello = "Hello from C++"; 53 // 创建引擎 54 SLEngineItf eng = CreateSL(); 55 if (eng) { 56 LOGI("CreateSL success"); 57 } else { 58 LOGE("CreateSL failed"); 59 } 60 // 创建混音器 61 SLObjectItf mix = NULL; 62 SLresult ret = 0; 63 ret = (*eng)->CreateOutputMix(eng, &mix, 0, 0, 0); 64 if (ret != SL_RESULT_SUCCESS) { 65 LOGE("CreateOutputMix failed"); 66 } 67 ret = (*mix)->Realize(mix, SL_BOOLEAN_FALSE); 68 if (ret != SL_BOOLEAN_FALSE) { 69 LOGE("(*mix)->Realize failed!"); 70 } 71 SLDataLocator_OutputMix outmix = {SL_DATALOCATOR_OUTPUTMIX, mix}; 72 SLDataSink audioSink = {&outmix, 0}; 73 74 return env->NewStringUTF(hello.c_str()); 75}