AudioEngine-inl.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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 "cocos2d-x debug info"
  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 "platform/android/CCFileUtils-android.h"
  39. #include "platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h"
  40. #include "audio/android/IAudioPlayer.h"
  41. #include "audio/android/ICallerThreadUtils.h"
  42. #include "audio/android/AudioPlayerProvider.h"
  43. #include "audio/android/cutils/log.h"
  44. #include "audio/android/UrlAudioPlayer.h"
  45. using namespace cocos2d;
  46. using namespace cocos2d::experimental;
  47. #define DELAY_TIME_TO_REMOVE 0.5f
  48. class CallerThreadUtils : public ICallerThreadUtils
  49. {
  50. public:
  51. virtual void performFunctionInCallerThread(const std::function<void()>& func)
  52. {
  53. Director::getInstance()->getScheduler()->performFunctionInCocosThread(func);
  54. };
  55. virtual std::thread::id getCallerThreadId()
  56. {
  57. return _tid;
  58. };
  59. void setCallerThreadId(std::thread::id tid)
  60. {
  61. _tid = tid;
  62. };
  63. private:
  64. std::thread::id _tid;
  65. };
  66. static CallerThreadUtils __callerThreadUtils;
  67. static int fdGetter(const std::string& url, off_t* start, off_t* length)
  68. {
  69. int fd = -1;
  70. if (cocos2d::FileUtilsAndroid::getObbFile() != nullptr)
  71. {
  72. fd = getObbAssetFileDescriptorJNI(url.c_str(), start, length);
  73. }
  74. else
  75. {
  76. auto asset = AAssetManager_open(cocos2d::FileUtilsAndroid::getAssetManager(), url.c_str(), AASSET_MODE_UNKNOWN);
  77. // open asset as file descriptor
  78. fd = AAsset_openFileDescriptor(asset, start, length);
  79. AAsset_close(asset);
  80. }
  81. if (fd <= 0)
  82. {
  83. ALOGE("Failed to open file descriptor for '%s'", url.c_str());
  84. }
  85. return fd;
  86. };
  87. //====================================================
  88. AudioEngineImpl::AudioEngineImpl()
  89. : _engineObject(nullptr)
  90. , _engineEngine(nullptr)
  91. , _outputMixObject(nullptr)
  92. , _audioPlayerProvider(nullptr)
  93. , _onPauseListener(nullptr)
  94. , _onResumeListener(nullptr)
  95. , _audioIDIndex(0)
  96. , _lazyInitLoop(true)
  97. {
  98. __callerThreadUtils.setCallerThreadId(std::this_thread::get_id());
  99. }
  100. AudioEngineImpl::~AudioEngineImpl()
  101. {
  102. if (_audioPlayerProvider != nullptr)
  103. {
  104. delete _audioPlayerProvider;
  105. _audioPlayerProvider = nullptr;
  106. }
  107. if (_outputMixObject)
  108. {
  109. (*_outputMixObject)->Destroy(_outputMixObject);
  110. }
  111. if (_engineObject)
  112. {
  113. (*_engineObject)->Destroy(_engineObject);
  114. }
  115. if (_onPauseListener != nullptr)
  116. {
  117. Director::getInstance()->getEventDispatcher()->removeEventListener(_onPauseListener);
  118. }
  119. if (_onResumeListener != nullptr)
  120. {
  121. Director::getInstance()->getEventDispatcher()->removeEventListener(_onResumeListener);
  122. }
  123. }
  124. bool AudioEngineImpl::init()
  125. {
  126. bool ret = false;
  127. do{
  128. // create engine
  129. auto result = slCreateEngine(&_engineObject, 0, nullptr, 0, nullptr, nullptr);
  130. if(SL_RESULT_SUCCESS != result){ ERRORLOG("create opensl engine fail"); break; }
  131. // realize the engine
  132. result = (*_engineObject)->Realize(_engineObject, SL_BOOLEAN_FALSE);
  133. if(SL_RESULT_SUCCESS != result){ ERRORLOG("realize the engine fail"); break; }
  134. // get the engine interface, which is needed in order to create other objects
  135. result = (*_engineObject)->GetInterface(_engineObject, SL_IID_ENGINE, &_engineEngine);
  136. if(SL_RESULT_SUCCESS != result){ ERRORLOG("get the engine interface fail"); break; }
  137. // create output mix
  138. const SLInterfaceID outputMixIIDs[] = {};
  139. const SLboolean outputMixReqs[] = {};
  140. result = (*_engineEngine)->CreateOutputMix(_engineEngine, &_outputMixObject, 0, outputMixIIDs, outputMixReqs);
  141. if(SL_RESULT_SUCCESS != result){ ERRORLOG("create output mix fail"); break; }
  142. // realize the output mix
  143. result = (*_outputMixObject)->Realize(_outputMixObject, SL_BOOLEAN_FALSE);
  144. if(SL_RESULT_SUCCESS != result){ ERRORLOG("realize the output mix fail"); break; }
  145. _audioPlayerProvider = new AudioPlayerProvider(_engineEngine, _outputMixObject, getDeviceSampleRate(), getDeviceAudioBufferSizeInFrames(), fdGetter, &__callerThreadUtils);
  146. _onPauseListener = Director::getInstance()->getEventDispatcher()->addCustomEventListener(EVENT_COME_TO_BACKGROUND, CC_CALLBACK_1(AudioEngineImpl::onEnterBackground, this));
  147. _onResumeListener = Director::getInstance()->getEventDispatcher()->addCustomEventListener(EVENT_COME_TO_FOREGROUND, CC_CALLBACK_1(AudioEngineImpl::onEnterForeground, this));
  148. ret = true;
  149. }while (false);
  150. return ret;
  151. }
  152. void AudioEngineImpl::onEnterBackground(EventCustom* event)
  153. {
  154. // _audioPlayerProvider->pause() pauses AudioMixer and PcmAudioService,
  155. // but UrlAudioPlayers could not be paused.
  156. if (_audioPlayerProvider != nullptr)
  157. {
  158. _audioPlayerProvider->pause();
  159. }
  160. // pause UrlAudioPlayers which are playing.
  161. for (auto&& e : _audioPlayers)
  162. {
  163. auto player = e.second;
  164. if (dynamic_cast<UrlAudioPlayer*>(player) != nullptr
  165. && player->getState() == IAudioPlayer::State::PLAYING)
  166. {
  167. _urlAudioPlayersNeedResume.push_back(player);
  168. player->pause();
  169. }
  170. }
  171. }
  172. void AudioEngineImpl::onEnterForeground(EventCustom* event)
  173. {
  174. // _audioPlayerProvider->resume() resumes AudioMixer and PcmAudioService,
  175. // but UrlAudioPlayers could not be resumed.
  176. if (_audioPlayerProvider != nullptr)
  177. {
  178. _audioPlayerProvider->resume();
  179. }
  180. // resume UrlAudioPlayers
  181. for (auto&& player : _urlAudioPlayersNeedResume)
  182. {
  183. player->resume();
  184. }
  185. _urlAudioPlayersNeedResume.clear();
  186. }
  187. int AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume)
  188. {
  189. ALOGV("play2d, _audioPlayers.size=%d", (int)_audioPlayers.size());
  190. auto audioId = AudioEngine::INVALID_AUDIO_ID;
  191. do
  192. {
  193. if (_engineEngine == nullptr || _audioPlayerProvider == nullptr)
  194. break;
  195. auto fullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
  196. audioId = _audioIDIndex++;
  197. auto player = _audioPlayerProvider->getAudioPlayer(fullPath);
  198. if (player != nullptr)
  199. {
  200. player->setId(audioId);
  201. _audioPlayers.insert(std::make_pair(audioId, player));
  202. player->setPlayEventCallback([this, player](IAudioPlayer::State state){
  203. if (state != IAudioPlayer::State::OVER && state != IAudioPlayer::State::STOPPED)
  204. {
  205. ALOGV("Ignore state: %d", static_cast<int>(state));
  206. return;
  207. }
  208. int id = player->getId();
  209. std::string filePath = *AudioEngine::_audioIDInfoMap[id].filePath;
  210. ALOGV("Removing player id=%d, state:%d", id, (int)state);
  211. AudioEngine::remove(id);
  212. _audioPlayers.erase(id);
  213. auto iter = _callbackMap.find(id);
  214. if (iter != _callbackMap.end())
  215. {
  216. if (state == IAudioPlayer::State::OVER)
  217. {
  218. iter->second(id, filePath);
  219. }
  220. _callbackMap.erase(iter);
  221. }
  222. });
  223. player->setLoop(loop);
  224. player->setVolume(volume);
  225. player->play();
  226. }
  227. else
  228. {
  229. ALOGE("Oops, player is null ...");
  230. return AudioEngine::INVALID_AUDIO_ID;
  231. }
  232. AudioEngine::_audioIDInfoMap[audioId].state = AudioEngine::AudioState::PLAYING;
  233. } while (0);
  234. return audioId;
  235. }
  236. void AudioEngineImpl::setVolume(int audioID,float volume)
  237. {
  238. auto iter = _audioPlayers.find(audioID);
  239. if (iter != _audioPlayers.end())
  240. {
  241. auto player = iter->second;
  242. player->setVolume(volume);
  243. }
  244. }
  245. void AudioEngineImpl::setLoop(int audioID, bool loop)
  246. {
  247. auto iter = _audioPlayers.find(audioID);
  248. if (iter != _audioPlayers.end())
  249. {
  250. auto player = iter->second;
  251. player->setLoop(loop);
  252. }
  253. }
  254. void AudioEngineImpl::pause(int audioID)
  255. {
  256. auto iter = _audioPlayers.find(audioID);
  257. if (iter != _audioPlayers.end())
  258. {
  259. auto player = iter->second;
  260. player->pause();
  261. }
  262. }
  263. void AudioEngineImpl::resume(int audioID)
  264. {
  265. auto iter = _audioPlayers.find(audioID);
  266. if (iter != _audioPlayers.end())
  267. {
  268. auto player = iter->second;
  269. player->resume();
  270. }
  271. }
  272. void AudioEngineImpl::stop(int audioID)
  273. {
  274. auto iter = _audioPlayers.find(audioID);
  275. if (iter != _audioPlayers.end())
  276. {
  277. auto player = iter->second;
  278. player->stop();
  279. }
  280. }
  281. void AudioEngineImpl::stopAll()
  282. {
  283. if (_audioPlayers.empty())
  284. {
  285. return;
  286. }
  287. // Create a temporary vector for storing all players since
  288. // p->stop() will trigger _audioPlayers.erase,
  289. // and it will cause a crash as it's already in for loop
  290. std::vector<IAudioPlayer*> players;
  291. players.reserve(_audioPlayers.size());
  292. for (const auto& e : _audioPlayers)
  293. {
  294. players.push_back(e.second);
  295. }
  296. for (auto p : players)
  297. {
  298. p->stop();
  299. }
  300. }
  301. float AudioEngineImpl::getDuration(int audioID)
  302. {
  303. auto iter = _audioPlayers.find(audioID);
  304. if (iter != _audioPlayers.end())
  305. {
  306. auto player = iter->second;
  307. return player->getDuration();
  308. }
  309. return 0.0f;
  310. }
  311. float AudioEngineImpl::getCurrentTime(int audioID)
  312. {
  313. auto iter = _audioPlayers.find(audioID);
  314. if (iter != _audioPlayers.end())
  315. {
  316. auto player = iter->second;
  317. return player->getPosition();
  318. }
  319. return 0.0f;
  320. }
  321. bool AudioEngineImpl::setCurrentTime(int audioID, float time)
  322. {
  323. auto iter = _audioPlayers.find(audioID);
  324. if (iter != _audioPlayers.end())
  325. {
  326. auto player = iter->second;
  327. return player->setPosition(time);
  328. }
  329. return false;
  330. }
  331. void AudioEngineImpl::setFinishCallback(int audioID, const std::function<void (int, const std::string &)> &callback)
  332. {
  333. _callbackMap[audioID] = callback;
  334. }
  335. void AudioEngineImpl::preload(const std::string& filePath, const std::function<void(bool)>& callback)
  336. {
  337. if (_audioPlayerProvider != nullptr)
  338. {
  339. std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
  340. _audioPlayerProvider->preloadEffect(fullPath, [callback](bool succeed, PcmData data){
  341. if (callback != nullptr)
  342. {
  343. callback(succeed);
  344. }
  345. });
  346. }
  347. else
  348. {
  349. if (callback != nullptr)
  350. {
  351. callback(false);
  352. }
  353. }
  354. }
  355. void AudioEngineImpl::uncache(const std::string& filePath)
  356. {
  357. if (_audioPlayerProvider != nullptr)
  358. {
  359. std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
  360. _audioPlayerProvider->clearPcmCache(fullPath);
  361. }
  362. }
  363. void AudioEngineImpl::uncacheAll()
  364. {
  365. if (_audioPlayerProvider != nullptr)
  366. {
  367. _audioPlayerProvider->clearAllPcmCaches();
  368. }
  369. }
  370. #endif