AudioEngine-inl.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. /****************************************************************************
  2. Copyright (c) 2014-2017 Chukong Technologies Inc.
  3. http://www.cocos2d-x.org
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. ****************************************************************************/
  20. #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
  21. #define LOG_TAG "AudioEngineImpl"
  22. #include "audio/android/AudioEngine-inl.h"
  23. #include <unistd.h>
  24. // for native asset manager
  25. #include <sys/types.h>
  26. #include <android/asset_manager.h>
  27. #include <android/asset_manager_jni.h>
  28. #include <unordered_map>
  29. #include "platform/android/jni/JniHelper.h"
  30. #include <android/log.h>
  31. #include <jni.h>
  32. #include "audio/include/AudioEngine.h"
  33. #include "base/CCDirector.h"
  34. #include "base/CCScheduler.h"
  35. #include "base/CCEventDispatcher.h"
  36. #include "base/CCEventType.h"
  37. #include "base/CCEventListenerCustom.h"
  38. #include "base/ccUTF8.h"
  39. #include "platform/android/CCFileUtils-android.h"
  40. #include "platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h"
  41. #include "audio/android/IAudioPlayer.h"
  42. #include "audio/android/ICallerThreadUtils.h"
  43. #include "audio/android/AudioPlayerProvider.h"
  44. #include "audio/android/cutils/log.h"
  45. #include "audio/android/UrlAudioPlayer.h"
  46. using namespace cocos2d;
  47. using namespace cocos2d::experimental;
  48. // Audio focus values synchronized with which in cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java
  49. static const int AUDIOFOCUS_GAIN = 0;
  50. static const int AUDIOFOCUS_LOST = 1;
  51. static const int AUDIOFOCUS_LOST_TRANSIENT = 2;
  52. static const int AUDIOFOCUS_LOST_TRANSIENT_CAN_DUCK = 3;
  53. static int __currentAudioFocus = AUDIOFOCUS_GAIN;
  54. static AudioEngineImpl* __impl = nullptr;
  55. class CallerThreadUtils : public ICallerThreadUtils
  56. {
  57. public:
  58. virtual void performFunctionInCallerThread(const std::function<void()>& func)
  59. {
  60. Director::getInstance()->getScheduler()->performFunctionInCocosThread(func);
  61. };
  62. virtual std::thread::id getCallerThreadId()
  63. {
  64. return _tid;
  65. };
  66. void setCallerThreadId(std::thread::id tid)
  67. {
  68. _tid = tid;
  69. };
  70. private:
  71. std::thread::id _tid;
  72. };
  73. static CallerThreadUtils __callerThreadUtils;
  74. static int fdGetter(const std::string& url, off_t* start, off_t* length)
  75. {
  76. int fd = -1;
  77. // if (cocos2d::FileUtilsAndroid::getObbFile() != nullptr)
  78. // {
  79. // fd = getObbAssetFileDescriptorJNI(url.c_str(), start, length);
  80. // }
  81. // else
  82. if (true)
  83. {
  84. auto asset = AAssetManager_open(cocos2d::FileUtilsAndroid::getAssetManager(), url.c_str(), AASSET_MODE_UNKNOWN);
  85. // open asset as file descriptor
  86. fd = AAsset_openFileDescriptor(asset, start, length);
  87. AAsset_close(asset);
  88. }
  89. if (fd <= 0)
  90. {
  91. ALOGE("Failed to open file descriptor for '%s'", url.c_str());
  92. }
  93. return fd;
  94. };
  95. //====================================================
  96. AudioEngineImpl::AudioEngineImpl()
  97. : _engineObject(nullptr)
  98. , _engineEngine(nullptr)
  99. , _outputMixObject(nullptr)
  100. , _audioPlayerProvider(nullptr)
  101. , _onPauseListener(nullptr)
  102. , _onResumeListener(nullptr)
  103. , _audioIDIndex(0)
  104. , _lazyInitLoop(true)
  105. {
  106. __callerThreadUtils.setCallerThreadId(std::this_thread::get_id());
  107. __impl = this;
  108. }
  109. AudioEngineImpl::~AudioEngineImpl()
  110. {
  111. if (_audioPlayerProvider != nullptr)
  112. {
  113. delete _audioPlayerProvider;
  114. _audioPlayerProvider = nullptr;
  115. }
  116. if (_outputMixObject)
  117. {
  118. (*_outputMixObject)->Destroy(_outputMixObject);
  119. }
  120. if (_engineObject)
  121. {
  122. (*_engineObject)->Destroy(_engineObject);
  123. }
  124. if (_onPauseListener != nullptr)
  125. {
  126. Director::getInstance()->getEventDispatcher()->removeEventListener(_onPauseListener);
  127. }
  128. if (_onResumeListener != nullptr)
  129. {
  130. Director::getInstance()->getEventDispatcher()->removeEventListener(_onResumeListener);
  131. }
  132. __impl = nullptr;
  133. }
  134. bool AudioEngineImpl::init()
  135. {
  136. bool ret = false;
  137. do{
  138. // create engine
  139. auto result = slCreateEngine(&_engineObject, 0, nullptr, 0, nullptr, nullptr);
  140. if(SL_RESULT_SUCCESS != result){ ERRORLOG("create opensl engine fail"); break; }
  141. // realize the engine
  142. result = (*_engineObject)->Realize(_engineObject, SL_BOOLEAN_FALSE);
  143. if(SL_RESULT_SUCCESS != result){ ERRORLOG("realize the engine fail"); break; }
  144. // get the engine interface, which is needed in order to create other objects
  145. result = (*_engineObject)->GetInterface(_engineObject, SL_IID_ENGINE, &_engineEngine);
  146. if(SL_RESULT_SUCCESS != result){ ERRORLOG("get the engine interface fail"); break; }
  147. // create output mix
  148. const SLInterfaceID outputMixIIDs[] = {};
  149. const SLboolean outputMixReqs[] = {};
  150. result = (*_engineEngine)->CreateOutputMix(_engineEngine, &_outputMixObject, 0, outputMixIIDs, outputMixReqs);
  151. if(SL_RESULT_SUCCESS != result){ ERRORLOG("create output mix fail"); break; }
  152. // realize the output mix
  153. result = (*_outputMixObject)->Realize(_outputMixObject, SL_BOOLEAN_FALSE);
  154. if(SL_RESULT_SUCCESS != result){ ERRORLOG("realize the output mix fail"); break; }
  155. _audioPlayerProvider = new AudioPlayerProvider(_engineEngine, _outputMixObject, getDeviceSampleRate(), getDeviceAudioBufferSizeInFrames(), fdGetter, &__callerThreadUtils);
  156. _onPauseListener = Director::getInstance()->getEventDispatcher()->addCustomEventListener(EVENT_COME_TO_BACKGROUND, CC_CALLBACK_1(AudioEngineImpl::onEnterBackground, this));
  157. _onResumeListener = Director::getInstance()->getEventDispatcher()->addCustomEventListener(EVENT_COME_TO_FOREGROUND, CC_CALLBACK_1(AudioEngineImpl::onEnterForeground, this));
  158. ret = true;
  159. }while (false);
  160. return ret;
  161. }
  162. void AudioEngineImpl::onEnterBackground(EventCustom* event)
  163. {
  164. // _audioPlayerProvider->pause() pauses AudioMixer and PcmAudioService,
  165. // but UrlAudioPlayers could not be paused.
  166. if (_audioPlayerProvider != nullptr)
  167. {
  168. _audioPlayerProvider->pause();
  169. }
  170. // pause UrlAudioPlayers which are playing.
  171. for (auto&& e : _audioPlayers)
  172. {
  173. auto player = e.second;
  174. if (dynamic_cast<UrlAudioPlayer*>(player) != nullptr
  175. && player->getState() == IAudioPlayer::State::PLAYING)
  176. {
  177. _urlAudioPlayersNeedResume.emplace(e.first, player);
  178. player->pause();
  179. }
  180. }
  181. }
  182. void AudioEngineImpl::onEnterForeground(EventCustom* event)
  183. {
  184. // _audioPlayerProvider->resume() resumes AudioMixer and PcmAudioService,
  185. // but UrlAudioPlayers could not be resumed.
  186. if (_audioPlayerProvider != nullptr)
  187. {
  188. _audioPlayerProvider->resume();
  189. }
  190. // resume UrlAudioPlayers
  191. for (auto&& iter : _urlAudioPlayersNeedResume)
  192. {
  193. iter.second->resume();
  194. }
  195. _urlAudioPlayersNeedResume.clear();
  196. }
  197. void AudioEngineImpl::setAudioFocusForAllPlayers(bool isFocus)
  198. {
  199. for (const auto& e : _audioPlayers)
  200. {
  201. e.second->setAudioFocus(isFocus);
  202. }
  203. }
  204. int AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume)
  205. {
  206. ALOGV("play2d, _audioPlayers.size=%d", (int)_audioPlayers.size());
  207. auto audioId = AudioEngine::INVALID_AUDIO_ID;
  208. do
  209. {
  210. if (_engineEngine == nullptr || _audioPlayerProvider == nullptr)
  211. break;
  212. auto fullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
  213. audioId = _audioIDIndex++;
  214. auto player = _audioPlayerProvider->getAudioPlayer(fullPath);
  215. if (player != nullptr)
  216. {
  217. player->setId(audioId);
  218. _audioPlayers.insert(std::make_pair(audioId, player));
  219. player->setPlayEventCallback([this, player, filePath](IAudioPlayer::State state){
  220. if (state != IAudioPlayer::State::OVER && state != IAudioPlayer::State::STOPPED)
  221. {
  222. ALOGV("Ignore state: %d", static_cast<int>(state));
  223. return;
  224. }
  225. int id = player->getId();
  226. ALOGV("Removing player id=%d, state:%d", id, (int)state);
  227. AudioEngine::remove(id);
  228. if (_audioPlayers.find(id) != _audioPlayers.end())
  229. {
  230. _audioPlayers.erase(id);
  231. }
  232. if (_urlAudioPlayersNeedResume.find(id) != _urlAudioPlayersNeedResume.end())
  233. {
  234. _urlAudioPlayersNeedResume.erase(id);
  235. }
  236. auto iter = _callbackMap.find(id);
  237. if (iter != _callbackMap.end())
  238. {
  239. if (state == IAudioPlayer::State::OVER)
  240. {
  241. iter->second(id, filePath);
  242. }
  243. _callbackMap.erase(iter);
  244. }
  245. });
  246. player->setLoop(loop);
  247. player->setVolume(volume);
  248. player->setAudioFocus(__currentAudioFocus == AUDIOFOCUS_GAIN);
  249. player->play();
  250. }
  251. else
  252. {
  253. ALOGE("Oops, player is null ...");
  254. return AudioEngine::INVALID_AUDIO_ID;
  255. }
  256. AudioEngine::_audioIDInfoMap[audioId].state = AudioEngine::AudioState::PLAYING;
  257. } while (0);
  258. return audioId;
  259. }
  260. void AudioEngineImpl::setVolume(int audioID,float volume)
  261. {
  262. auto iter = _audioPlayers.find(audioID);
  263. if (iter != _audioPlayers.end())
  264. {
  265. auto player = iter->second;
  266. player->setVolume(volume);
  267. }
  268. }
  269. void AudioEngineImpl::setLoop(int audioID, bool loop)
  270. {
  271. auto iter = _audioPlayers.find(audioID);
  272. if (iter != _audioPlayers.end())
  273. {
  274. auto player = iter->second;
  275. player->setLoop(loop);
  276. }
  277. }
  278. void AudioEngineImpl::pause(int audioID)
  279. {
  280. auto iter = _audioPlayers.find(audioID);
  281. if (iter != _audioPlayers.end())
  282. {
  283. auto player = iter->second;
  284. player->pause();
  285. }
  286. }
  287. void AudioEngineImpl::resume(int audioID)
  288. {
  289. auto iter = _audioPlayers.find(audioID);
  290. if (iter != _audioPlayers.end())
  291. {
  292. auto player = iter->second;
  293. player->resume();
  294. }
  295. }
  296. void AudioEngineImpl::stop(int audioID)
  297. {
  298. auto iter = _audioPlayers.find(audioID);
  299. if (iter != _audioPlayers.end())
  300. {
  301. auto player = iter->second;
  302. player->stop();
  303. }
  304. }
  305. void AudioEngineImpl::stopAll()
  306. {
  307. if (_audioPlayers.empty())
  308. {
  309. return;
  310. }
  311. // Create a temporary vector for storing all players since
  312. // p->stop() will trigger _audioPlayers.erase,
  313. // and it will cause a crash as it's already in for loop
  314. std::vector<IAudioPlayer*> players;
  315. players.reserve(_audioPlayers.size());
  316. for (const auto& e : _audioPlayers)
  317. {
  318. players.push_back(e.second);
  319. }
  320. for (auto p : players)
  321. {
  322. p->stop();
  323. }
  324. }
  325. float AudioEngineImpl::getDuration(int audioID)
  326. {
  327. auto iter = _audioPlayers.find(audioID);
  328. if (iter != _audioPlayers.end())
  329. {
  330. auto player = iter->second;
  331. return player->getDuration();
  332. }
  333. return 0.0f;
  334. }
  335. float AudioEngineImpl::getCurrentTime(int audioID)
  336. {
  337. auto iter = _audioPlayers.find(audioID);
  338. if (iter != _audioPlayers.end())
  339. {
  340. auto player = iter->second;
  341. return player->getPosition();
  342. }
  343. return 0.0f;
  344. }
  345. bool AudioEngineImpl::setCurrentTime(int audioID, float time)
  346. {
  347. auto iter = _audioPlayers.find(audioID);
  348. if (iter != _audioPlayers.end())
  349. {
  350. auto player = iter->second;
  351. return player->setPosition(time);
  352. }
  353. return false;
  354. }
  355. void AudioEngineImpl::setFinishCallback(int audioID, const std::function<void (int, const std::string &)> &callback)
  356. {
  357. _callbackMap[audioID] = callback;
  358. }
  359. void AudioEngineImpl::preload(const std::string& filePath, const std::function<void(bool)>& callback)
  360. {
  361. if (_audioPlayerProvider != nullptr)
  362. {
  363. std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
  364. _audioPlayerProvider->preloadEffect(fullPath, [callback](bool succeed, PcmData data){
  365. if (callback != nullptr)
  366. {
  367. callback(succeed);
  368. }
  369. });
  370. }
  371. else
  372. {
  373. if (callback != nullptr)
  374. {
  375. callback(false);
  376. }
  377. }
  378. }
  379. void AudioEngineImpl::uncache(const std::string& filePath)
  380. {
  381. if (_audioPlayerProvider != nullptr)
  382. {
  383. std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
  384. _audioPlayerProvider->clearPcmCache(fullPath);
  385. }
  386. }
  387. void AudioEngineImpl::uncacheAll()
  388. {
  389. if (_audioPlayerProvider != nullptr)
  390. {
  391. _audioPlayerProvider->clearAllPcmCaches();
  392. }
  393. }
  394. // It's invoked from javaactivity-android.cpp
  395. void cocos_audioengine_focus_change(int focusChange)
  396. {
  397. if (focusChange < AUDIOFOCUS_GAIN || focusChange > AUDIOFOCUS_LOST_TRANSIENT_CAN_DUCK)
  398. {
  399. CCLOGERROR("cocos_audioengine_focus_change: unknown value: %d", focusChange);
  400. return;
  401. }
  402. CCLOG("cocos_audioengine_focus_change: %d", focusChange);
  403. __currentAudioFocus = focusChange;
  404. if (__impl == nullptr)
  405. {
  406. CCLOGWARN("cocos_audioengine_focus_change: AudioEngineImpl isn't ready!");
  407. return;
  408. }
  409. if (__currentAudioFocus == AUDIOFOCUS_GAIN)
  410. {
  411. __impl->setAudioFocusForAllPlayers(true);
  412. }
  413. else
  414. {
  415. __impl->setAudioFocusForAllPlayers(false);
  416. }
  417. }
  418. #endif