1
0

AudioPlayer.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. #define LOG_TAG "AudioPlayer"
  21. #include "platform/CCPlatformConfig.h"
  22. #if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
  23. #include "audio/win32/AudioPlayer.h"
  24. #include "audio/win32/AudioCache.h"
  25. #include "platform/CCFileUtils.h"
  26. #include "audio/win32/AudioDecoderManager.h"
  27. #include "audio/win32/Audiodecoder.h"
  28. #define VERY_VERY_VERBOSE_LOGGING
  29. #ifdef VERY_VERY_VERBOSE_LOGGING
  30. #define ALOGVV ALOGV
  31. #else
  32. #define ALOGVV(...) do{} while(false)
  33. #endif
  34. using namespace cocos2d;
  35. using namespace cocos2d::experimental;
  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. }
  190. assert(state == AL_PLAYING);
  191. _ready = true;
  192. ret = true;
  193. } while (false);
  194. if (!ret)
  195. {
  196. _removeByAudioEngine = true;
  197. }
  198. _play2dMutex.unlock();
  199. return ret;
  200. }
  201. void AudioPlayer::rotateBufferThread(int offsetFrame)
  202. {
  203. char* tmpBuffer = nullptr;
  204. AudioDecoder* decoder = AudioDecoderManager::createDecoder(_audioCache->_fileFullPath.c_str());
  205. do
  206. {
  207. BREAK_IF(decoder == nullptr || !decoder->open(_audioCache->_fileFullPath.c_str()));
  208. uint32_t framesRead = 0;
  209. const uint32_t framesToRead = _audioCache->_queBufferFrames;
  210. const uint32_t bufferSize = framesToRead * decoder->getBytesPerFrame();
  211. tmpBuffer = (char*)malloc(bufferSize);
  212. memset(tmpBuffer, 0, bufferSize);
  213. if (offsetFrame != 0) {
  214. decoder->seek(offsetFrame);
  215. }
  216. ALint sourceState;
  217. ALint bufferProcessed = 0;
  218. bool needToExitThread = false;
  219. while (!_isDestroyed) {
  220. alGetSourcei(_alSource, AL_SOURCE_STATE, &sourceState);
  221. if (sourceState == AL_PLAYING) {
  222. alGetSourcei(_alSource, AL_BUFFERS_PROCESSED, &bufferProcessed);
  223. while (bufferProcessed > 0) {
  224. bufferProcessed--;
  225. if (_timeDirty) {
  226. _timeDirty = false;
  227. offsetFrame = _currTime * decoder->getSampleRate();
  228. decoder->seek(offsetFrame);
  229. }
  230. else {
  231. _currTime += QUEUEBUFFER_TIME_STEP;
  232. if (_currTime > _audioCache->_duration) {
  233. if (_loop) {
  234. _currTime = 0.0f;
  235. } else {
  236. _currTime = _audioCache->_duration;
  237. }
  238. }
  239. }
  240. framesRead = decoder->readFixedFrames(framesToRead, tmpBuffer);
  241. if (framesRead == 0) {
  242. if (_loop) {
  243. decoder->seek(0);
  244. framesRead = decoder->readFixedFrames(framesToRead, tmpBuffer);
  245. } else {
  246. needToExitThread = true;
  247. break;
  248. }
  249. }
  250. ALuint bid;
  251. alSourceUnqueueBuffers(_alSource, 1, &bid);
  252. alBufferData(bid, _audioCache->_format, tmpBuffer, framesRead * decoder->getBytesPerFrame(), decoder->getSampleRate());
  253. alSourceQueueBuffers(_alSource, 1, &bid);
  254. }
  255. }
  256. std::unique_lock<std::mutex> lk(_sleepMutex);
  257. if (_isDestroyed || needToExitThread) {
  258. break;
  259. }
  260. _sleepCondition.wait_for(lk,std::chrono::milliseconds(75));
  261. }
  262. } while(false);
  263. ALOGV("Exit rotate buffer thread ...");
  264. if (decoder != nullptr)
  265. {
  266. decoder->close();
  267. }
  268. AudioDecoderManager::destroyDecoder(decoder);
  269. free(tmpBuffer);
  270. _isRotateThreadExited = true;
  271. ALOGV("%s exited.\n", __FUNCTION__);
  272. }
  273. bool AudioPlayer::setLoop(bool loop)
  274. {
  275. if (!_isDestroyed ) {
  276. _loop = loop;
  277. return true;
  278. }
  279. return false;
  280. }
  281. bool AudioPlayer::setTime(float time)
  282. {
  283. if (!_isDestroyed && time >= 0.0f && time < _audioCache->_duration) {
  284. _currTime = time;
  285. _timeDirty = true;
  286. return true;
  287. }
  288. return false;
  289. }
  290. #endif