AudioEngine-tizen.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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. #include "platform/CCPlatformConfig.h"
  21. #if CC_TARGET_PLATFORM == CC_PLATFORM_TIZEN
  22. #include "audio/tizen/AudioEngine-tizen.h"
  23. // for native asset manager
  24. #include <condition_variable>
  25. #include <sys/types.h>
  26. #include <sound_manager.h>
  27. #include "audio/include/AudioEngine.h"
  28. #include "base/CCDirector.h"
  29. #include "base/CCScheduler.h"
  30. #include "platform/CCFileUtils.h"
  31. #include "platform/tizen/CCApplication-tizen.h"
  32. #include <queue>
  33. class AudioEngineThreadPool
  34. {
  35. public:
  36. AudioEngineThreadPool()
  37. : _running(true) {
  38. _threads = std::thread(std::bind(&AudioEngineThreadPool::threadFunc, this));
  39. }
  40. ~AudioEngineThreadPool()
  41. {
  42. _running = false;
  43. _sleepCondition.notify_one();
  44. _threads.join();
  45. }
  46. void addTask(const std::function<void()> &task) {
  47. _tasks.push(task);
  48. _sleepCondition.notify_one();
  49. }
  50. private:
  51. bool _running;
  52. std::thread _threads;
  53. std::queue< std::function<void ()> > _tasks;
  54. void threadFunc(void) {
  55. while (true) {
  56. std::function<void ()> task = nullptr;
  57. if (_tasks.empty())
  58. {
  59. if (!_running)
  60. {
  61. break;
  62. }
  63. std::unique_lock<std::mutex> lk(_sleepMutex);
  64. _sleepCondition.wait(lk);
  65. continue;
  66. }
  67. task = _tasks.front();
  68. task();
  69. _tasks.pop();
  70. }
  71. }
  72. std::mutex _sleepMutex;
  73. std::condition_variable _sleepCondition;
  74. };
  75. static AudioEngineThreadPool* _threadPool = nullptr;
  76. using namespace cocos2d;
  77. using namespace cocos2d::experimental;
  78. static void sessionInterruptedCallback(sound_session_interrupted_code_e code, void *user_data)
  79. {
  80. Application* app = Application::getInstance();
  81. if(app && app->isPaused())
  82. {
  83. return;
  84. }
  85. if(code == SOUND_SESSION_INTERRUPTED_COMPLETED)
  86. {
  87. AudioEngine::resumeAll();
  88. }
  89. else
  90. {
  91. AudioEngine::pauseAll();
  92. if (code == SOUND_SESSION_INTERRUPTED_BY_EARJACK_UNPLUG)
  93. {
  94. AudioEngine::resumeAll();
  95. }
  96. }
  97. }
  98. AudioPlayer::AudioPlayer()
  99. : _playerHandle(nullptr)
  100. , _finishCallback(nullptr)
  101. , _initCallback(nullptr)
  102. , _duration(0.0f)
  103. , _playOver(false)
  104. , _initSucceed(false)
  105. {
  106. }
  107. static void _stopPlayer(player_h player)
  108. {
  109. player_state_e state = PLAYER_STATE_NONE;
  110. player_get_state(player, &state);
  111. if (state == PLAYER_STATE_PLAYING || state == PLAYER_STATE_PAUSED)
  112. {
  113. player_stop(player);
  114. }
  115. player_unprepare(player);
  116. }
  117. static void _pausePlayer(player_h player)
  118. {
  119. player_state_e state;
  120. player_get_state(player, &state);
  121. if(state == PLAYER_STATE_PLAYING)
  122. {
  123. player_pause(player);
  124. }
  125. }
  126. static void _resumePlayer(player_h player)
  127. {
  128. player_state_e state;
  129. player_get_state(player, &state);
  130. if(state != PLAYER_STATE_PLAYING)
  131. {
  132. player_start(player);
  133. }
  134. }
  135. AudioPlayer::~AudioPlayer()
  136. {
  137. _taskMutex.lock();
  138. _threadPool->addTask(std::bind(_stopPlayer, _playerHandle));
  139. _threadPool->addTask(std::bind(player_destroy, _playerHandle));
  140. _taskMutex.unlock();
  141. }
  142. void AudioPlayer::stopPlayer()
  143. {
  144. _playOver = true;
  145. }
  146. static void completed_callback(void* user_data)
  147. {
  148. AudioPlayer* player = (AudioPlayer*)user_data;
  149. player->stopPlayer();
  150. }
  151. void AudioPlayer::init(const std::string& fileFullPath, float volume, bool loop)
  152. {
  153. do
  154. {
  155. player_h player;
  156. auto playerRet = player_create(&player);
  157. if(playerRet != PLAYER_ERROR_NONE)
  158. {
  159. log("Fail to create player.Error code:%d",playerRet);
  160. break;
  161. }
  162. _playerHandle = player;
  163. playerRet = player_set_uri(player, fileFullPath.c_str());
  164. if(playerRet != PLAYER_ERROR_NONE)
  165. {
  166. log("Fail to sets the data source for player.Error code:%d",playerRet);
  167. break;
  168. }
  169. player_set_volume(player, volume, volume);
  170. player_set_completed_cb(player, completed_callback, this);
  171. if (loop)
  172. {
  173. player_set_looping(player, true);
  174. }
  175. playerRet = player_prepare(player);
  176. if(playerRet != PLAYER_ERROR_NONE){
  177. log("Fail to prepares the media player for playback.Error code:%d",playerRet);
  178. break;
  179. }
  180. playerRet = player_start(player);
  181. if(playerRet != PLAYER_ERROR_NONE){
  182. log("Fail to starts playback.Error code:%d",playerRet);
  183. break;
  184. }
  185. _initSucceed = true;
  186. } while (0);
  187. if (_initCallback)
  188. {
  189. _initCallback();
  190. }
  191. _taskMutex.unlock();
  192. }
  193. //====================================================
  194. AudioEngineImpl::AudioEngineImpl()
  195. : currentAudioID(0)
  196. , _lazyInitLoop(true)
  197. {
  198. }
  199. AudioEngineImpl::~AudioEngineImpl()
  200. {
  201. this->stopAll();
  202. if (_threadPool)
  203. {
  204. delete _threadPool;
  205. _threadPool = nullptr;
  206. }
  207. auto scheduler = Director::getInstance()->getScheduler();
  208. scheduler->unschedule(schedule_selector(AudioEngineImpl::update), this);
  209. }
  210. bool AudioEngineImpl::init()
  211. {
  212. sound_manager_set_session_type(SOUND_SESSION_TYPE_MEDIA);
  213. sound_manager_set_media_session_option(SOUND_SESSION_OPTION_MIX_WITH_OTHERS_WHEN_START,
  214. SOUND_SESSION_OPTION_INTERRUPTIBLE_DURING_PLAY);
  215. sound_manager_set_media_session_resumption_option(SOUND_SESSION_OPTION_RESUMPTION_BY_SYSTEM_OR_MEDIA_PAUSED);
  216. sound_manager_set_session_interrupted_cb(sessionInterruptedCallback, this);
  217. if (!_threadPool)
  218. {
  219. _threadPool = new (std::nothrow) AudioEngineThreadPool();
  220. }
  221. return true;
  222. }
  223. int AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume)
  224. {
  225. auto audioId = AudioEngine::INVALID_AUDIO_ID;
  226. do
  227. {
  228. audioId = currentAudioID++;
  229. auto& player = _audioPlayers[audioId];
  230. player._audioID = audioId;
  231. player._initCallback = std::bind(&AudioEngineImpl::initPlayerCallback,this,&player,audioId);
  232. player._taskMutex.lock();
  233. _threadPool->addTask(std::bind(&AudioPlayer::init,&player,FileUtils::getInstance()->fullPathForFilename(filePath), volume, loop));
  234. if (_lazyInitLoop) {
  235. _lazyInitLoop = false;
  236. auto scheduler = Director::getInstance()->getScheduler();
  237. scheduler->schedule(schedule_selector(AudioEngineImpl::update), this, 0.03f, false);
  238. }
  239. } while (0);
  240. return audioId;
  241. }
  242. void AudioEngineImpl::initPlayerCallback(AudioPlayer *player, int audioID)
  243. {
  244. if (player->_initSucceed)
  245. {
  246. AudioEngine::_audioIDInfoMap[audioID].state = AudioEngine::AudioState::PLAYING;
  247. }
  248. else
  249. {
  250. _threadMutex.lock();
  251. _toRemoveAudioIDs.push_back(audioID);
  252. _threadMutex.unlock();
  253. }
  254. }
  255. void AudioEngineImpl::update(float dt)
  256. {
  257. if (_threadMutex.try_lock()) {
  258. int audioID;
  259. size_t removeAudioCount = _toRemoveAudioIDs.size();
  260. for (size_t index = 0; index < removeAudioCount; ++index) {
  261. audioID = _toRemoveAudioIDs[index];
  262. auto playerIt = _audioPlayers.find(audioID);
  263. if (playerIt != _audioPlayers.end()) {
  264. if(playerIt->second._finishCallback) {
  265. auto& audioInfo = AudioEngine::_audioIDInfoMap[audioID];
  266. playerIt->second._finishCallback(audioID, *audioInfo.filePath);
  267. }
  268. _audioPlayers.erase(audioID);
  269. AudioEngine::remove(audioID);
  270. }
  271. }
  272. _threadMutex.unlock();
  273. }
  274. auto itend = _audioPlayers.end();
  275. for (auto iter = _audioPlayers.begin(); iter != itend; ++iter)
  276. {
  277. if(iter->second._playOver)
  278. {
  279. if (iter->second._finishCallback)
  280. iter->second._finishCallback(iter->second._audioID, *AudioEngine::_audioIDInfoMap[iter->second._audioID].filePath);
  281. AudioEngine::remove(iter->second._audioID);
  282. _audioPlayers.erase(iter);
  283. break;
  284. }
  285. }
  286. if(_audioPlayers.empty()){
  287. _lazyInitLoop = true;
  288. auto scheduler = Director::getInstance()->getScheduler();
  289. scheduler->unschedule(schedule_selector(AudioEngineImpl::update), this);
  290. }
  291. }
  292. void AudioEngineImpl::setVolume(int audioID,float volume)
  293. {
  294. auto& player = _audioPlayers[audioID];
  295. player_set_volume(player._playerHandle, volume, volume);
  296. }
  297. void AudioEngineImpl::setLoop(int audioID, bool loop)
  298. {
  299. auto& player = _audioPlayers[audioID];
  300. player_set_looping(player._playerHandle, loop);
  301. }
  302. void AudioEngineImpl::pause(int audioID)
  303. {
  304. auto& player = _audioPlayers[audioID];
  305. _threadPool->addTask(std::bind(_pausePlayer, player._playerHandle));
  306. }
  307. void AudioEngineImpl::resume(int audioID)
  308. {
  309. auto& player = _audioPlayers[audioID];
  310. _threadPool->addTask(std::bind(_resumePlayer, player._playerHandle));
  311. }
  312. void AudioEngineImpl::stop(int audioID)
  313. {
  314. _audioPlayers.erase(audioID);
  315. }
  316. void AudioEngineImpl::stopAll()
  317. {
  318. _audioPlayers.clear();
  319. }
  320. float AudioEngineImpl::getDuration(int audioID)
  321. {
  322. int duration;
  323. auto& player = _audioPlayers[audioID];
  324. auto ret = player_get_duration(player._playerHandle, &duration);
  325. if(ret != PLAYER_ERROR_NONE)
  326. {
  327. log("Fail to get duration:%d",ret);
  328. }
  329. return duration / 1000.0f;
  330. }
  331. float AudioEngineImpl::getCurrentTime(int audioID)
  332. {
  333. int currPos;
  334. auto& player = _audioPlayers[audioID];
  335. auto ret = player_get_play_position(player._playerHandle, &currPos);
  336. if(ret != PLAYER_ERROR_NONE)
  337. {
  338. CCLOG("Fail to get position:%d",ret);
  339. }
  340. return currPos / 1000.0f;
  341. }
  342. bool AudioEngineImpl::setCurrentTime(int audioID, float time)
  343. {
  344. auto& player = _audioPlayers[audioID];
  345. int pos = 1000 * time;
  346. player_set_play_position(player._playerHandle, pos, true, NULL, NULL);
  347. return true;
  348. }
  349. void AudioEngineImpl::setFinishCallback(int audioID, const std::function<void (int, const std::string &)> &callback)
  350. {
  351. _audioPlayers[audioID]._finishCallback = callback;
  352. }
  353. void AudioEngineImpl::preload(const std::string& filePath, std::function<void(bool)> callback)
  354. {
  355. //TODO: implement preload on Tizen platform.
  356. }
  357. #endif