当前位置:   article > 正文

OpenHarmony OpenSl ES音频播放开发_openharmony opensles

openharmony opensles

1、OpenHarmony OpenSl ES音频播放简介

        开发者可以通过本博文了解在OpenHarmony中如何使用OpenSL ES接口进行音频播放相关操作;当前仅实现了部分OpenSL ES接口,因此调用未实现接口后会返回SL_RESULT_FEATURE_UNSUPPORTED

2、 OpenHarmony OpenSl ES音频播放开发指导

        以下步骤描述了在OpenHarmony如何使用OpenSL ES开发音频播放功能:

(1).添加头文件

  1. #include <OpenSLES.h>
  2. #include <OpenSLES_OpenHarmony.h>
  3. #include <OpenSLES_Platform.h>

(2).使用 slCreateEngine 接口和获取 engine 实例

  1. SLObjectItf engineObject = nullptr;
  2. slCreateEngine(&engineObject, 0, nullptr, 0, nullptr, nullptr);
  3. (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE);

(3).获取接口 SL_IID_ENGINE 的 engineEngine 实例

  1. SLEngineItf engineEngine = nullptr;
  2. (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine);

(4).配置播放器信息,创建 AudioPlayer

  1. SLDataLocator_BufferQueue slBufferQueue = {
  2. SL_DATALOCATOR_BUFFERQUEUE,
  3. 0
  4. };
  5. // 具体参数需要根据音频文件格式进行适配
  6. SLDataFormat_PCM pcmFormat = {
  7. SL_DATAFORMAT_PCM,
  8. 2,
  9. 48000,
  10. 16,
  11. 0,
  12. 0,
  13. 0
  14. };
  15. SLDataSource slSource = {&slBufferQueue, &pcmFormat};
  16. SLObjectItf pcmPlayerObject = nullptr;
  17. (*engineEngine)->CreateAudioPlayer(engineEngine, &pcmPlayerObject, &slSource, null, 0, nullptr, nullptr);
  18. (*pcmPlayerObject)->Realize(pcmPlayerObject, SL_BOOLEAN_FALSE);

(5).获取接口 SL_IID_OH_BUFFERQUEUE 的 bufferQueueItf 实例

  1. SLOHBufferQueueItf bufferQueueItf;
  2. (*pcmPlayerObject)->GetInterface(pcmPlayerObject, SL_IID_OH_BUFFERQUEUE, &bufferQueueItf);

(6).打开音频文件,注册 BufferQueueCallback 回调

  1. FILE *wavFile_ = nullptr;
  2. static void BufferQueueCallback (SLOHBufferQueueItf bufferQueueItf, void *pContext, SLuint32 size)
  3. {
  4. FILE *wavFile = (FILE *)pContext;
  5. if (!feof(wavFile)) {
  6. SLuint8 *buffer = nullptr;
  7. SLuint32 pSize = 0;
  8. (*bufferQueueItf)->GetBuffer(bufferQueueItf, &buffer, pSize);
  9. //从文件读取数据
  10. fread(buffer, 1, size, wavFile);
  11. (*bufferQueueItf)->Enqueue(bufferQueueItf, buffer, size);
  12. }
  13. return;
  14. }
  15. // wavFile_ 需要设置为用户想要播放的文件描述符
  16. wavFile_ = fopen(path, "rb");
  17. (*bufferQueueItf)->RegisterCallback(bufferQueueItf, BufferQueueCallback, wavFile_);

(7).获取接口 SL_PLAYSTATE_PLAYING 的 playItf 实例,开始播放

  1. SLPlayItf playItf = nullptr;
  2. (*pcmPlayerObject)->GetInterface(pcmPlayerObject, SL_IID_PLAY, &playItf);
  3. (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_PLAYING);

(8).结束音频播放

  1. (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_STOPPED);
  2. (*pcmPlayerObject)->Destroy(pcmPlayerObject);
  3. (*engineObject)->Destroy(engineObject);

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/329281
推荐阅读
相关标签
  

闽ICP备14008679号