AudioPlayer.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. /****************************************************************************
  2. Copyright (c) 2014-2016 Chukong Technologies Inc.
  3. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  4. http://www.cocos2d-x.org
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. ****************************************************************************/
  21. #define LOG_TAG "AudioPlayer"
  22. #include "platform/CCPlatformConfig.h"
  23. #if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
  24. #include "audio/win32/AudioPlayer.h"
  25. #include "audio/win32/AudioCache.h"
  26. #include "platform/CCFileUtils.h"
  27. #include "audio/win32/AudioDecoderManager.h"
  28. #include "audio/win32/Audiodecoder.h"
  29. #define VERY_VERY_VERBOSE_LOGGING
  30. #ifdef VERY_VERY_VERBOSE_LOGGING
  31. #define ALOGVV ALOGV
  32. #else
  33. #define ALOGVV(...) do{} while(false)
  34. #endif
  35. using namespace cocos2d;
  36. namespace {
  37. unsigned int __idIndex = 0;
  38. }
  39. AudioPlayer::AudioPlayer()
  40. : _audioCache(nullptr)
  41. , _finishCallbak(nullptr)
  42. , _isDestroyed(false)
  43. , _removeByAudioEngine(false)
  44. , _ready(false)
  45. , _currTime(0.0f)
  46. , _streamingSource(false)
  47. , _rotateBufferThread(nullptr)
  48. , _timeDirty(false)
  49. , _isRotateThreadExited(false)
  50. , _id(++__idIndex)
  51. {
  52. memset(_bufferIds, 0, sizeof(_bufferIds));
  53. }
  54. AudioPlayer::~AudioPlayer()
  55. {
  56. ALOGVV("~AudioPlayer() (%p), id=%u", this, _id);
  57. destroy();
  58. if (_streamingSource)
  59. {
  60. alDeleteBuffers(3, _bufferIds);
  61. }
  62. }
  63. void AudioPlayer::destroy()
  64. {
  65. if (_isDestroyed)
  66. return;
  67. ALOGVV("AudioPlayer::destroy begin, id=%u", _id);
  68. _isDestroyed = true;
  69. do
  70. {
  71. if (_audioCache != nullptr)
  72. {
  73. if (_audioCache->_state == AudioCache::State::INITIAL)
  74. {
  75. ALOGV("AudioPlayer::destroy, id=%u, cache isn't ready!", _id);
  76. break;
  77. }
  78. while (!_audioCache->_isLoadingFinished)
  79. {
  80. std::this_thread::sleep_for(std::chrono::milliseconds(5));
  81. }
  82. }
  83. // Wait for play2d to be finished.
  84. _play2dMutex.lock();
  85. _play2dMutex.unlock();
  86. if (_streamingSource)
  87. {
  88. if (_rotateBufferThread != nullptr)
  89. {
  90. while (!_isRotateThreadExited)
  91. {
  92. _sleepCondition.notify_one();
  93. std::this_thread::sleep_for(std::chrono::milliseconds(5));
  94. }
  95. if (_rotateBufferThread->joinable()) {
  96. _rotateBufferThread->join();
  97. }
  98. delete _rotateBufferThread;
  99. _rotateBufferThread = nullptr;
  100. ALOGVV("rotateBufferThread exited!");
  101. }
  102. }
  103. } while(false);
  104. ALOGVV("Before alSourceStop");
  105. alSourceStop(_alSource); CHECK_AL_ERROR_DEBUG();
  106. ALOGVV("Before alSourcei");
  107. alSourcei(_alSource, AL_BUFFER, NULL); CHECK_AL_ERROR_DEBUG();
  108. _removeByAudioEngine = true;
  109. _ready = false;
  110. ALOGVV("AudioPlayer::destroy end, id=%u", _id);
  111. }
  112. void AudioPlayer::setCache(AudioCache* cache)
  113. {
  114. _audioCache = cache;
  115. }
  116. bool AudioPlayer::play2d()
  117. {
  118. _play2dMutex.lock();
  119. ALOGV("AudioPlayer::play2d, _alSource: %u, player id=%u", _alSource, _id);
  120. /*********************************************************************/
  121. /* Note that it may be in sub thread or in main thread. **/
  122. /*********************************************************************/
  123. bool ret = false;
  124. do
  125. {
  126. if (_audioCache->_state != AudioCache::State::READY)
  127. {
  128. ALOGE("alBuffer isn't ready for play!");
  129. break;
  130. }
  131. alSourcei(_alSource, AL_BUFFER, 0);CHECK_AL_ERROR_DEBUG();
  132. alSourcef(_alSource, AL_PITCH, 1.0f);CHECK_AL_ERROR_DEBUG();
  133. alSourcef(_alSource, AL_GAIN, _volume);CHECK_AL_ERROR_DEBUG();
  134. alSourcei(_alSource, AL_LOOPING, AL_FALSE);CHECK_AL_ERROR_DEBUG();
  135. if (_audioCache->_queBufferFrames == 0)
  136. {
  137. if (_loop) {
  138. alSourcei(_alSource, AL_LOOPING, AL_TRUE);
  139. CHECK_AL_ERROR_DEBUG();
  140. }
  141. }
  142. else
  143. {
  144. alGenBuffers(3, _bufferIds);
  145. auto alError = alGetError();
  146. if (alError == AL_NO_ERROR)
  147. {
  148. for (int index = 0; index < QUEUEBUFFER_NUM; ++index)
  149. {
  150. alBufferData(_bufferIds[index], _audioCache->_format, _audioCache->_queBuffers[index], _audioCache->_queBufferSize[index], _audioCache->_sampleRate);
  151. }
  152. CHECK_AL_ERROR_DEBUG();
  153. }
  154. else
  155. {
  156. ALOGE("%s:alGenBuffers error code:%x", __FUNCTION__,alError);
  157. break;
  158. }
  159. _streamingSource = true;
  160. }
  161. {
  162. std::unique_lock<std::mutex> lk(_sleepMutex);
  163. if (_isDestroyed)
  164. break;
  165. if (_streamingSource)
  166. {
  167. alSourceQueueBuffers(_alSource, QUEUEBUFFER_NUM, _bufferIds);
  168. CHECK_AL_ERROR_DEBUG();
  169. _rotateBufferThread = new std::thread(&AudioPlayer::rotateBufferThread, this, _audioCache->_queBufferFrames * QUEUEBUFFER_NUM + 1);
  170. }
  171. else
  172. {
  173. alSourcei(_alSource, AL_BUFFER, _audioCache->_alBufferId);
  174. CHECK_AL_ERROR_DEBUG();
  175. }
  176. alSourcePlay(_alSource);
  177. }
  178. auto alError = alGetError();
  179. if (alError != AL_NO_ERROR)
  180. {
  181. ALOGE("%s:alSourcePlay error code:%x", __FUNCTION__,alError);
  182. break;
  183. }
  184. ALint state;
  185. alGetSourcei(_alSource, AL_SOURCE_STATE, &state);
  186. if (state != AL_PLAYING)
  187. {
  188. ALOGE("state isn't playing, %d, %s, cache id=%u, player id=%u", state, _audioCache->_fileFullPath.c_str(), _audioCache->_id, _id);
  189. //abort playing if the state is incorrect
  190. break;
  191. }
  192. _ready = true;
  193. ret = true;
  194. } while (false);
  195. if (!ret)
  196. {
  197. _removeByAudioEngine = true;
  198. }
  199. _play2dMutex.unlock();
  200. return ret;
  201. }
  202. void AudioPlayer::rotateBufferThread(int offsetFrame)
  203. {
  204. char* tmpBuffer = nullptr;
  205. AudioDecoder* decoder = AudioDecoderManager::createDecoder(_audioCache->_fileFullPath.c_str());
  206. do
  207. {
  208. BREAK_IF(decoder == nullptr || !decoder->open(_audioCache->_fileFullPath.c_str()));
  209. uint32_t framesRead = 0;
  210. const uint32_t framesToRead = _audioCache->_queBufferFrames;
  211. const uint32_t bufferSize = framesToRead * decoder->getBytesPerFrame();
  212. tmpBuffer = (char*)malloc(bufferSize);
  213. memset(tmpBuffer, 0, bufferSize);
  214. if (offsetFrame != 0) {
  215. decoder->seek(offsetFrame);
  216. }
  217. ALint sourceState;
  218. ALint bufferProcessed = 0;
  219. bool needToExitThread = false;
  220. while (!_isDestroyed) {
  221. alGetSourcei(_alSource, AL_SOURCE_STATE, &sourceState);
  222. if (sourceState == AL_PLAYING) {
  223. alGetSourcei(_alSource, AL_BUFFERS_PROCESSED, &bufferProcessed);
  224. while (bufferProcessed > 0) {
  225. bufferProcessed--;
  226. if (_timeDirty) {
  227. _timeDirty = false;
  228. offsetFrame = _currTime * decoder->getSampleRate();
  229. decoder->seek(offsetFrame);
  230. }
  231. else {
  232. _currTime += QUEUEBUFFER_TIME_STEP;
  233. if (_currTime > _audioCache->_duration) {
  234. if (_loop) {
  235. _currTime = 0.0f;
  236. } else {
  237. _currTime = _audioCache->_duration;
  238. }
  239. }
  240. }
  241. framesRead = decoder->readFixedFrames(framesToRead, tmpBuffer);
  242. if (framesRead == 0) {
  243. if (_loop) {
  244. decoder->seek(0);
  245. framesRead = decoder->readFixedFrames(framesToRead, tmpBuffer);
  246. } else {
  247. needToExitThread = true;
  248. break;
  249. }
  250. }
  251. ALuint bid;
  252. alSourceUnqueueBuffers(_alSource, 1, &bid);
  253. alBufferData(bid, _audioCache->_format, tmpBuffer, framesRead * decoder->getBytesPerFrame(), decoder->getSampleRate());
  254. alSourceQueueBuffers(_alSource, 1, &bid);
  255. }
  256. }
  257. std::unique_lock<std::mutex> lk(_sleepMutex);
  258. if (_isDestroyed || needToExitThread) {
  259. break;
  260. }
  261. _sleepCondition.wait_for(lk,std::chrono::milliseconds(75));
  262. }
  263. } while(false);
  264. ALOGV("Exit rotate buffer thread ...");
  265. if (decoder != nullptr)
  266. {
  267. decoder->close();
  268. }
  269. AudioDecoderManager::destroyDecoder(decoder);
  270. free(tmpBuffer);
  271. _isRotateThreadExited = true;
  272. ALOGV("%s exited.\n", __FUNCTION__);
  273. }
  274. bool AudioPlayer::setLoop(bool loop)
  275. {
  276. if (!_isDestroyed ) {
  277. _loop = loop;
  278. return true;
  279. }
  280. return false;
  281. }
  282. bool AudioPlayer::setTime(float time)
  283. {
  284. if (!_isDestroyed && time >= 0.0f && time < _audioCache->_duration) {
  285. _currTime = time;
  286. _timeDirty = true;
  287. return true;
  288. }
  289. return false;
  290. }
  291. #endif