mirror of
https://github.com/cocos/cocos4.git
synced 2026-11-20 15:42:39 +08:00
Sync with cocos2d-x v3 branch ddb4dc8 commit.
This commit is contained in:
@@ -572,6 +572,10 @@
|
||||
1ABA68B11888D700007D1BB4 /* CCFontCharMap.h in Headers */ = {isa = PBXBuildFile; fileRef = 1ABA68AD1888D700007D1BB4 /* CCFontCharMap.h */; };
|
||||
1ACF6A3C1E4AFDC80033C137 /* libcrypto.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1ACF6A3A1E4AFDC80033C137 /* libcrypto.a */; };
|
||||
1ACF6A3D1E4AFDC80033C137 /* libssl.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 1ACF6A3B1E4AFDC80033C137 /* libssl.a */; };
|
||||
1AD473AC1EAD9A5200202582 /* Uri.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1AD473AA1EAD9A5200202582 /* Uri.cpp */; };
|
||||
1AD473AD1EAD9A5300202582 /* Uri.h in Headers */ = {isa = PBXBuildFile; fileRef = 1AD473AB1EAD9A5200202582 /* Uri.h */; };
|
||||
1AD473AE1EAD9A5600202582 /* Uri.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 1AD473AA1EAD9A5200202582 /* Uri.cpp */; };
|
||||
1AD473AF1EAD9A5900202582 /* Uri.h in Headers */ = {isa = PBXBuildFile; fileRef = 1AD473AB1EAD9A5200202582 /* Uri.h */; };
|
||||
291901431B05895600F8B4BA /* CCNinePatchImageParser.h in Headers */ = {isa = PBXBuildFile; fileRef = 291901411B05895600F8B4BA /* CCNinePatchImageParser.h */; };
|
||||
291901441B05895600F8B4BA /* CCNinePatchImageParser.h in Headers */ = {isa = PBXBuildFile; fileRef = 291901411B05895600F8B4BA /* CCNinePatchImageParser.h */; };
|
||||
291901451B05895600F8B4BA /* CCNinePatchImageParser.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 291901421B05895600F8B4BA /* CCNinePatchImageParser.cpp */; };
|
||||
@@ -2080,6 +2084,8 @@
|
||||
1ABA68AD1888D700007D1BB4 /* CCFontCharMap.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCFontCharMap.h; sourceTree = "<group>"; };
|
||||
1ACF6A3A1E4AFDC80033C137 /* libcrypto.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libcrypto.a; path = ../external/ios/libs/libcrypto.a; sourceTree = "<group>"; };
|
||||
1ACF6A3B1E4AFDC80033C137 /* libssl.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libssl.a; path = ../external/ios/libs/libssl.a; sourceTree = "<group>"; };
|
||||
1AD473AA1EAD9A5200202582 /* Uri.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Uri.cpp; sourceTree = "<group>"; };
|
||||
1AD473AB1EAD9A5200202582 /* Uri.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Uri.h; sourceTree = "<group>"; };
|
||||
1AD71CFA180E26E600808F54 /* CCBAnimationManager.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCBAnimationManager.cpp; sourceTree = "<group>"; };
|
||||
1AD71CFB180E26E600808F54 /* CCBAnimationManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CCBAnimationManager.h; sourceTree = "<group>"; };
|
||||
1AD71CFC180E26E600808F54 /* CCBFileLoader.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CCBFileLoader.cpp; sourceTree = "<group>"; };
|
||||
@@ -3535,6 +3541,8 @@
|
||||
1AAF5360180E3374000584C8 /* network */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
1AD473AA1EAD9A5200202582 /* Uri.cpp */,
|
||||
1AD473AB1EAD9A5200202582 /* Uri.h */,
|
||||
507003251B69820100E83DDD /* HttpClient */,
|
||||
507003261B69820B00E83DDD /* SocketIO */,
|
||||
507003271B69821300E83DDD /* WebSocket */,
|
||||
@@ -5298,6 +5306,7 @@
|
||||
50ABC0231926664800A911A9 /* CCGLViewImpl-desktop.h in Headers */,
|
||||
A63CF0081CD9CF3500A6971D /* CCUIPasswordTextField.h in Headers */,
|
||||
15AE188D19AAD33D00C27E9E /* CCLabelBMFontLoader.h in Headers */,
|
||||
1AD473AD1EAD9A5300202582 /* Uri.h in Headers */,
|
||||
4DED48521DFFA4AF0070C5C4 /* b2PolygonAndCircleContact.h in Headers */,
|
||||
4DED48861DFFA4AF0070C5C4 /* b2WheelJoint.h in Headers */,
|
||||
4DED485A1DFFA4AF0070C5C4 /* b2DistanceJoint.h in Headers */,
|
||||
@@ -5541,6 +5550,7 @@
|
||||
4DED48471DFFA4AF0070C5C4 /* b2ContactSolver.h in Headers */,
|
||||
50ABBD3F1925AB0000A911A9 /* CCGeometry.h in Headers */,
|
||||
BAFF7CAB1D59E0DA0051B92F /* CCComBase.h in Headers */,
|
||||
1AD473AF1EAD9A5900202582 /* Uri.h in Headers */,
|
||||
BAFF7CBB1D59E0DB0051B92F /* CCDataReaderHelper.h in Headers */,
|
||||
BA68D7B51D62F66300B7A3F9 /* CCPass.h in Headers */,
|
||||
BAFF7C8D1D59E0DA0051B92F /* CCArmatureAnimation.h in Headers */,
|
||||
@@ -6103,6 +6113,7 @@
|
||||
1A5701B9180BCB5A0088DEC7 /* CCLabel.cpp in Sources */,
|
||||
1A5701BD180BCB5A0088DEC7 /* CCLabelAtlas.cpp in Sources */,
|
||||
BA68D7B21D62F66300B7A3F9 /* CCPass.cpp in Sources */,
|
||||
1AD473AC1EAD9A5200202582 /* Uri.cpp in Sources */,
|
||||
4DED48541DFFA4AF0070C5C4 /* b2PolygonContact.cpp in Sources */,
|
||||
BA68D78D1D62F4A500B7A3F9 /* sweep.cc in Sources */,
|
||||
15AE1B5319AADA9900C27E9E /* UIRichText.cpp in Sources */,
|
||||
@@ -6555,6 +6566,7 @@
|
||||
1A57009F180BC5D20088DEC7 /* CCNode.cpp in Sources */,
|
||||
BA68D78A1D62F4A500B7A3F9 /* cdt.cc in Sources */,
|
||||
1A57010F180BC8EE0088DEC7 /* CCDrawingPrimitives.cpp in Sources */,
|
||||
1AD473AE1EAD9A5600202582 /* Uri.cpp in Sources */,
|
||||
1A570113180BC8EE0088DEC7 /* CCDrawNode.cpp in Sources */,
|
||||
1A57011C180BC90D0088DEC7 /* CCGrabber.cpp in Sources */,
|
||||
1A570120180BC90D0088DEC7 /* CCGrid.cpp in Sources */,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2014-2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2014-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -36,6 +36,12 @@
|
||||
#include "audio/apple/AudioEngine-inl.h"
|
||||
#elif CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
|
||||
#include "audio/win32/AudioEngine-win32.h"
|
||||
#elif CC_TARGET_PLATFORM == CC_PLATFORM_WINRT
|
||||
#include "audio/winrt/AudioEngine-winrt.h"
|
||||
#elif CC_TARGET_PLATFORM == CC_PLATFORM_LINUX
|
||||
#include "audio/linux/AudioEngine-linux.h"
|
||||
#elif CC_TARGET_PLATFORM == CC_PLATFORM_TIZEN
|
||||
#include "audio/tizen/AudioEngine-tizen.h"
|
||||
#endif
|
||||
|
||||
#define TIME_DELAY_PRECISION 0.0001
|
||||
@@ -61,20 +67,30 @@ AudioEngineImpl* AudioEngine::_audioEngineImpl = nullptr;
|
||||
|
||||
AudioEngine::AudioEngineThreadPool* AudioEngine::s_threadPool = nullptr;
|
||||
|
||||
AudioEngine::AudioInfo::AudioInfo()
|
||||
: filePath(nullptr)
|
||||
, profileHelper(nullptr)
|
||||
, volume(1.0f)
|
||||
, loop(false)
|
||||
, duration(TIME_UNKNOWN)
|
||||
, state(AudioState::INITIALIZING)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
AudioEngine::AudioInfo::~AudioInfo()
|
||||
{
|
||||
}
|
||||
|
||||
class AudioEngine::AudioEngineThreadPool
|
||||
{
|
||||
public:
|
||||
AudioEngineThreadPool(bool detach, int threads = 4)
|
||||
: _detach(detach)
|
||||
, _stop(false)
|
||||
AudioEngineThreadPool(int threads = 4)
|
||||
: _stop(false)
|
||||
{
|
||||
for (int index = 0; index < threads; ++index)
|
||||
{
|
||||
_workers.emplace_back(std::thread(std::bind(&AudioEngineThreadPool::threadFunc, this)));
|
||||
if (_detach)
|
||||
{
|
||||
_workers[index].detach();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,11 +108,8 @@ public:
|
||||
_taskCondition.notify_all();
|
||||
}
|
||||
|
||||
if (!_detach)
|
||||
{
|
||||
for (auto&& worker : _workers) {
|
||||
worker.join();
|
||||
}
|
||||
for (auto&& worker : _workers) {
|
||||
worker.join();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -132,7 +145,6 @@ private:
|
||||
|
||||
std::mutex _queueMutex;
|
||||
std::condition_variable _taskCondition;
|
||||
bool _detach;
|
||||
bool _stop;
|
||||
};
|
||||
|
||||
@@ -165,15 +177,10 @@ bool AudioEngine::lazyInit()
|
||||
}
|
||||
}
|
||||
|
||||
#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
|
||||
#if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID)
|
||||
if (_audioEngineImpl && s_threadPool == nullptr)
|
||||
{
|
||||
s_threadPool = new (std::nothrow) AudioEngineThreadPool(true);
|
||||
}
|
||||
#elif CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID
|
||||
if (_audioEngineImpl && s_threadPool == nullptr)
|
||||
{
|
||||
s_threadPool = new (std::nothrow) AudioEngineThreadPool(false);
|
||||
s_threadPool = new (std::nothrow) AudioEngineThreadPool();
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -199,7 +206,7 @@ int AudioEngine::play2d(const std::string& filePath, bool loop, float volume, co
|
||||
profileHelper = &_audioPathProfileHelperMap[profile->name];
|
||||
profileHelper->profile = *profile;
|
||||
}
|
||||
|
||||
|
||||
if (_audioIDInfoMap.size() >= _maxInstances) {
|
||||
log("Fail to play %s cause by limited max instance of AudioEngine",filePath.c_str());
|
||||
break;
|
||||
@@ -218,20 +225,20 @@ int AudioEngine::play2d(const std::string& filePath, bool loop, float volume, co
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (volume < 0.0f) {
|
||||
volume = 0.0f;
|
||||
}
|
||||
else if (volume > 1.0f){
|
||||
volume = 1.0f;
|
||||
}
|
||||
|
||||
|
||||
ret = _audioEngineImpl->play2d(filePath, loop, volume);
|
||||
if (ret != INVALID_AUDIO_ID)
|
||||
{
|
||||
_audioPathIDMap[filePath].push_back(ret);
|
||||
auto it = _audioPathIDMap.find(filePath);
|
||||
|
||||
|
||||
auto& audioRef = _audioIDInfoMap[ret];
|
||||
audioRef.volume = volume;
|
||||
audioRef.loop = loop;
|
||||
@@ -371,7 +378,7 @@ void AudioEngine::uncache(const std::string &filePath)
|
||||
for (int audioID : copiedIDs)
|
||||
{
|
||||
_audioEngineImpl->stop(audioID);
|
||||
|
||||
|
||||
auto itInfo = _audioIDInfoMap.find(audioID);
|
||||
if (itInfo != _audioIDInfoMap.end())
|
||||
{
|
||||
@@ -385,15 +392,15 @@ void AudioEngine::uncache(const std::string &filePath)
|
||||
_audioPathIDMap.erase(filePath);
|
||||
}
|
||||
|
||||
if (_audioEngineImpl){
|
||||
if (_audioEngineImpl)
|
||||
{
|
||||
_audioEngineImpl->uncache(filePath);
|
||||
}
|
||||
}
|
||||
|
||||
void AudioEngine::uncacheAll()
|
||||
{
|
||||
if (!_audioEngineImpl)
|
||||
{
|
||||
if(!_audioEngineImpl){
|
||||
return;
|
||||
}
|
||||
stopAll();
|
||||
@@ -403,7 +410,7 @@ void AudioEngine::uncacheAll()
|
||||
float AudioEngine::getDuration(int audioID)
|
||||
{
|
||||
auto it = _audioIDInfoMap.find(audioID);
|
||||
if (it != _audioIDInfoMap.end() && it->second.state != AudioState::INITIALZING)
|
||||
if (it != _audioIDInfoMap.end() && it->second.state != AudioState::INITIALIZING)
|
||||
{
|
||||
if (it->second.duration == TIME_UNKNOWN)
|
||||
{
|
||||
@@ -411,14 +418,14 @@ float AudioEngine::getDuration(int audioID)
|
||||
}
|
||||
return it->second.duration;
|
||||
}
|
||||
|
||||
|
||||
return TIME_UNKNOWN;
|
||||
}
|
||||
|
||||
bool AudioEngine::setCurrentTime(int audioID, float time)
|
||||
{
|
||||
auto it = _audioIDInfoMap.find(audioID);
|
||||
if (it != _audioIDInfoMap.end() && it->second.state != AudioState::INITIALZING){
|
||||
if (it != _audioIDInfoMap.end() && it->second.state != AudioState::INITIALIZING) {
|
||||
return _audioEngineImpl->setCurrentTime(audioID, time);
|
||||
}
|
||||
|
||||
@@ -428,7 +435,7 @@ bool AudioEngine::setCurrentTime(int audioID, float time)
|
||||
float AudioEngine::getCurrentTime(int audioID)
|
||||
{
|
||||
auto it = _audioIDInfoMap.find(audioID);
|
||||
if (it != _audioIDInfoMap.end() && it->second.state != AudioState::INITIALZING){
|
||||
if (it != _audioIDInfoMap.end() && it->second.state != AudioState::INITIALIZING) {
|
||||
return _audioEngineImpl->getCurrentTime(audioID);
|
||||
}
|
||||
return 0.0f;
|
||||
@@ -459,7 +466,7 @@ bool AudioEngine::isLoop(int audioID)
|
||||
{
|
||||
return tmpIterator->second.loop;
|
||||
}
|
||||
|
||||
|
||||
log("AudioEngine::isLoop-->The audio instance %d is non-existent", audioID);
|
||||
return false;
|
||||
}
|
||||
@@ -483,7 +490,7 @@ AudioEngine::AudioState AudioEngine::getState(int audioID)
|
||||
{
|
||||
return tmpIterator->second.state;
|
||||
}
|
||||
|
||||
|
||||
return AudioState::ERROR;
|
||||
}
|
||||
|
||||
@@ -494,7 +501,7 @@ AudioProfile* AudioEngine::getProfile(int audioID)
|
||||
{
|
||||
return &it->second.profileHelper->profile;
|
||||
}
|
||||
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
@@ -504,7 +511,7 @@ AudioProfile* AudioEngine::getDefaultProfile()
|
||||
{
|
||||
_defaultProfileHelper = new (std::nothrow) ProfileHelper();
|
||||
}
|
||||
|
||||
|
||||
return &_defaultProfileHelper->profile;
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ LOCAL_SRC_FILES := AudioEngine-inl.cpp \
|
||||
AudioDecoderSLES.cpp \
|
||||
AudioDecoderOgg.cpp \
|
||||
AudioDecoderMp3.cpp \
|
||||
AudioDecoderWav.cpp \
|
||||
AudioPlayerProvider.cpp \
|
||||
AudioResampler.cpp \
|
||||
AudioResamplerCubic.cpp \
|
||||
@@ -31,7 +32,8 @@ LOCAL_SRC_FILES := AudioEngine-inl.cpp \
|
||||
audio_utils/minifloat.cpp \
|
||||
audio_utils/primitives.c \
|
||||
utils/Utils.cpp \
|
||||
mp3reader.cpp
|
||||
mp3reader.cpp \
|
||||
tinysndfile.cpp
|
||||
|
||||
|
||||
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/../include
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -93,7 +93,7 @@ bool AudioDecoder::init(const std::string &url, int sampleRate)
|
||||
bool AudioDecoder::start()
|
||||
{
|
||||
auto oldTime = clockNow();
|
||||
|
||||
auto nowTime = oldTime;
|
||||
bool ret;
|
||||
do
|
||||
{
|
||||
@@ -103,23 +103,31 @@ bool AudioDecoder::start()
|
||||
ALOGE("decodeToPcm (%s) failed!", _url.c_str());
|
||||
break;
|
||||
}
|
||||
|
||||
nowTime = clockNow();
|
||||
ALOGD("Decoding (%s) to pcm data wasted %fms", _url.c_str(), intervalInMS(oldTime, nowTime));
|
||||
oldTime = nowTime;
|
||||
|
||||
ret = resample();
|
||||
if (!ret)
|
||||
{
|
||||
ALOGE("resample (%s) failed!", _url.c_str());
|
||||
break;
|
||||
}
|
||||
|
||||
nowTime = clockNow();
|
||||
ALOGD("Resampling (%s) wasted %fms", _url.c_str(), intervalInMS(oldTime, nowTime));
|
||||
oldTime = nowTime;
|
||||
|
||||
ret = interleave();
|
||||
if (!ret)
|
||||
{
|
||||
ALOGE("interleave (%s) failed!", _url.c_str());
|
||||
break;
|
||||
}
|
||||
|
||||
auto nowTime = clockNow();
|
||||
|
||||
ALOGV("Decoding (%s) to pcm data wasted %fms", _url.c_str(),
|
||||
intervalInMS(oldTime, nowTime));
|
||||
|
||||
nowTime = clockNow();
|
||||
ALOGD("Interleave (%s) wasted %fms", _url.c_str(), intervalInMS(oldTime, nowTime));
|
||||
|
||||
} while(false);
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
|
||||
@@ -1,3 +1,27 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
#define LOG_TAG "AudioDecoderMp3"
|
||||
|
||||
#include "audio/android/AudioDecoderMp3.h"
|
||||
@@ -33,20 +57,26 @@ bool AudioDecoderMp3::decodeToPcm()
|
||||
int numChannels = 0;
|
||||
int sampleRate = 0;
|
||||
int numFrames = 0;
|
||||
decodeMP3(&callbacks, this, *_result.pcmBuffer, &numChannels, &sampleRate, &numFrames);
|
||||
|
||||
if (EXIT_SUCCESS == decodeMP3(&callbacks, this, *_result.pcmBuffer, &numChannels, &sampleRate, &numFrames)
|
||||
&& numChannels > 0 && sampleRate > 0 && numFrames > 0)
|
||||
{
|
||||
_result.numChannels = numChannels;
|
||||
_result.sampleRate = sampleRate;
|
||||
_result.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16;
|
||||
_result.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16;
|
||||
_result.channelMask = numChannels == 1 ? SL_SPEAKER_FRONT_CENTER : (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT);
|
||||
_result.endianness = SL_BYTEORDER_LITTLEENDIAN;
|
||||
_result.numFrames = numFrames;
|
||||
_result.duration = 1.0f * numFrames / sampleRate;
|
||||
|
||||
_result.numChannels = numChannels;
|
||||
_result.sampleRate = sampleRate;
|
||||
_result.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16;
|
||||
_result.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16;
|
||||
_result.channelMask = numChannels == 1 ? SL_SPEAKER_FRONT_CENTER : (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT);
|
||||
_result.endianness = SL_BYTEORDER_LITTLEENDIAN;
|
||||
_result.numFrames = numFrames;
|
||||
_result.duration = 1.0f * numFrames / sampleRate;
|
||||
std::string info = _result.toString();
|
||||
ALOGI("Original audio info: %s, total size: %d", info.c_str(), (int)_result.pcmBuffer->size());
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string info = _result.toString();
|
||||
ALOGI("Original audio info: %s, total size: %d", info.c_str(), (int)_result.pcmBuffer->size());
|
||||
return true;
|
||||
ALOGE("Decode MP3 (%s) failed, channels: %d, rate: %d, frames: %d", _url.c_str(), numChannels, sampleRate, numFrames);
|
||||
return false;
|
||||
}
|
||||
|
||||
}} // namespace cocos2d { namespace experimental {
|
||||
@@ -1,3 +1,27 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
#define LOG_TAG "AudioDecoderOgg"
|
||||
|
||||
#include "audio/android/AudioDecoderOgg.h"
|
||||
@@ -46,35 +70,43 @@ bool AudioDecoderOgg::decodeToPcm()
|
||||
// header
|
||||
auto vi = ov_info(&vf, -1);
|
||||
|
||||
uint32_t uiPCMSamples = (uint32_t) ov_pcm_total(&vf, -1);
|
||||
uint32_t pcmSamples = (uint32_t) ov_pcm_total(&vf, -1);
|
||||
|
||||
uint32_t bufferSize = uiPCMSamples * vi->channels * sizeof(short);
|
||||
char* pvPCMBuffer = (char*)malloc(bufferSize);
|
||||
memset(pvPCMBuffer, 0, bufferSize);
|
||||
uint32_t bufferSize = pcmSamples * vi->channels * sizeof(short);
|
||||
char* pcmBuffer = (char*)malloc(bufferSize);
|
||||
memset(pcmBuffer, 0, bufferSize);
|
||||
|
||||
int currentSection = 0;
|
||||
long curPos = 0;
|
||||
long readBytes = 0;
|
||||
// decode
|
||||
do {
|
||||
readBytes = ov_read(&vf, pvPCMBuffer + curPos, 4096, ¤tSection);
|
||||
|
||||
do
|
||||
{
|
||||
readBytes = ov_read(&vf, pcmBuffer + curPos, 4096, ¤tSection);
|
||||
curPos += readBytes;
|
||||
} while (readBytes > 0);
|
||||
|
||||
_result.pcmBuffer->insert(_result.pcmBuffer->end(), pvPCMBuffer, pvPCMBuffer + bufferSize);
|
||||
_result.numChannels = vi->channels;
|
||||
_result.sampleRate = vi->rate;
|
||||
_result.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16;
|
||||
_result.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16;
|
||||
_result.channelMask = vi->channels == 1 ? SL_SPEAKER_FRONT_CENTER : (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT);
|
||||
_result.endianness = SL_BYTEORDER_LITTLEENDIAN;
|
||||
_result.numFrames = uiPCMSamples;
|
||||
_result.duration = 1.0f * uiPCMSamples / vi->rate;
|
||||
if (curPos > 0)
|
||||
{
|
||||
_result.pcmBuffer->insert(_result.pcmBuffer->end(), pcmBuffer, pcmBuffer + bufferSize);
|
||||
_result.numChannels = vi->channels;
|
||||
_result.sampleRate = vi->rate;
|
||||
_result.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16;
|
||||
_result.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16;
|
||||
_result.channelMask = vi->channels == 1 ? SL_SPEAKER_FRONT_CENTER : (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT);
|
||||
_result.endianness = SL_BYTEORDER_LITTLEENDIAN;
|
||||
_result.numFrames = pcmSamples;
|
||||
_result.duration = 1.0f * pcmSamples / vi->rate;
|
||||
}
|
||||
else
|
||||
{
|
||||
ALOGE("ov_read returns 0 byte!");
|
||||
}
|
||||
|
||||
ov_clear(&vf);
|
||||
free(pvPCMBuffer);
|
||||
free(pcmBuffer);
|
||||
|
||||
return true;
|
||||
return (curPos > 0);
|
||||
}
|
||||
|
||||
}} // namespace cocos2d { namespace experimental {
|
||||
@@ -4,6 +4,7 @@
|
||||
#include "audio/android/AudioDecoderSLES.h"
|
||||
#include "audio/android/AudioDecoderOgg.h"
|
||||
#include "audio/android/AudioDecoderMp3.h"
|
||||
#include "audio/android/AudioDecoderWav.h"
|
||||
#include "platform/CCFileUtils.h"
|
||||
|
||||
namespace cocos2d { namespace experimental {
|
||||
@@ -31,6 +32,15 @@ AudioDecoder* AudioDecoderProvider::createAudioDecoder(SLEngineItf engineItf, co
|
||||
decoder = nullptr;
|
||||
}
|
||||
}
|
||||
else if (extension == ".wav")
|
||||
{
|
||||
decoder = new AudioDecoderWav();
|
||||
if (!decoder->init(url, sampleRate))
|
||||
{
|
||||
delete decoder;
|
||||
decoder = nullptr;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
auto slesDecoder = new AudioDecoderSLES();
|
||||
|
||||
@@ -1,3 +1,27 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
#define LOG_TAG "AudioDecoderSLES"
|
||||
|
||||
#include "audio/android/AudioDecoderSLES.h"
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
#define LOG_TAG "AudioDecoderWav"
|
||||
|
||||
#include "audio/android/AudioDecoderWav.h"
|
||||
#include "audio/android/tinysndfile.h"
|
||||
#include "platform/CCFileUtils.h"
|
||||
|
||||
namespace cocos2d { namespace experimental {
|
||||
|
||||
AudioDecoderWav::AudioDecoderWav()
|
||||
{
|
||||
ALOGV("Create AudioDecoderWav");
|
||||
}
|
||||
|
||||
AudioDecoderWav::~AudioDecoderWav()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void* AudioDecoderWav::onWavOpen(const char* path, void* user)
|
||||
{
|
||||
return user;
|
||||
}
|
||||
|
||||
int AudioDecoderWav::onWavSeek(void* datasource, long offset, int whence)
|
||||
{
|
||||
return AudioDecoder::fileSeek(datasource, (int64_t) offset, whence);
|
||||
}
|
||||
|
||||
int AudioDecoderWav::onWavClose(void* datasource)
|
||||
{
|
||||
}
|
||||
|
||||
bool AudioDecoderWav::decodeToPcm()
|
||||
{
|
||||
_fileData = FileUtils::getInstance()->getDataFromFile(_url);
|
||||
if (_fileData.isNull())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
SF_INFO info;
|
||||
|
||||
snd_callbacks cb;
|
||||
cb.open = onWavOpen;
|
||||
cb.read = AudioDecoder::fileRead;
|
||||
cb.seek = onWavSeek;
|
||||
cb.close = onWavClose;
|
||||
cb.tell = AudioDecoder::fileTell;
|
||||
|
||||
SNDFILE* handle = NULL;
|
||||
bool ret = false;
|
||||
do
|
||||
{
|
||||
handle = sf_open_read(_url.c_str(), &info, &cb, this);
|
||||
if (handle == nullptr)
|
||||
break;
|
||||
|
||||
if (info.frames == 0)
|
||||
break;
|
||||
|
||||
ALOGD("wav info: frames: %d, samplerate: %d, channels: %d, format: %d", info.frames, info.samplerate, info.channels, info.format);
|
||||
size_t bufSize = sizeof(short) * info.frames * info.channels;
|
||||
unsigned char* buf = (unsigned char*)malloc(bufSize);
|
||||
sf_count_t readFrames = sf_readf_short(handle, (short*)buf, info.frames);
|
||||
assert(readFrames == info.frames);
|
||||
|
||||
_result.pcmBuffer->insert(_result.pcmBuffer->end(), buf, buf + bufSize);
|
||||
_result.numChannels = info.channels;
|
||||
_result.sampleRate = info.samplerate;
|
||||
_result.bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16;
|
||||
_result.containerSize = SL_PCMSAMPLEFORMAT_FIXED_16;
|
||||
_result.channelMask = _result.numChannels == 1 ? SL_SPEAKER_FRONT_CENTER : (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT);
|
||||
_result.endianness = SL_BYTEORDER_LITTLEENDIAN;
|
||||
_result.numFrames = info.frames;
|
||||
_result.duration = 1.0f * info.frames / _result.sampleRate;
|
||||
|
||||
free(buf);
|
||||
ret = true;
|
||||
} while (false);
|
||||
|
||||
if (handle != NULL)
|
||||
sf_close(handle);
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
}} // namespace cocos2d { namespace experimental {
|
||||
@@ -0,0 +1,46 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "audio/android/AudioDecoder.h"
|
||||
|
||||
namespace cocos2d { namespace experimental {
|
||||
|
||||
class AudioDecoderWav : public AudioDecoder
|
||||
{
|
||||
protected:
|
||||
AudioDecoderWav();
|
||||
virtual ~AudioDecoderWav();
|
||||
|
||||
virtual bool decodeToPcm() override;
|
||||
|
||||
static void* onWavOpen(const char* path, void* user);
|
||||
static int onWavSeek(void* datasource, long offset, int whence);
|
||||
static int onWavClose(void* datasource);
|
||||
|
||||
friend class AudioDecoderProvider;
|
||||
};
|
||||
|
||||
}} // namespace cocos2d { namespace experimental {
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2014-2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2014-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -23,8 +23,6 @@
|
||||
****************************************************************************/
|
||||
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
|
||||
|
||||
#define LOG_TAG "cocos2d-x debug info"
|
||||
|
||||
#include "audio/android/AudioEngine-inl.h"
|
||||
|
||||
#include <unistd.h>
|
||||
@@ -43,6 +41,7 @@
|
||||
#include "base/CCEventDispatcher.h"
|
||||
#include "base/CCEventType.h"
|
||||
#include "base/CCEventListenerCustom.h"
|
||||
#include "base/ccUTF8.h"
|
||||
#include "platform/android/CCFileUtils-android.h"
|
||||
#include "platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h"
|
||||
|
||||
@@ -55,8 +54,14 @@
|
||||
using namespace cocos2d;
|
||||
using namespace cocos2d::experimental;
|
||||
|
||||
#define DELAY_TIME_TO_REMOVE 0.5f
|
||||
// Audio focus values synchronized with which in cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java
|
||||
static const int AUDIOFOCUS_GAIN = 0;
|
||||
static const int AUDIOFOCUS_LOST = 1;
|
||||
static const int AUDIOFOCUS_LOST_TRANSIENT = 2;
|
||||
static const int AUDIOFOCUS_LOST_TRANSIENT_CAN_DUCK = 3;
|
||||
|
||||
static int __currentAudioFocus = AUDIOFOCUS_GAIN;
|
||||
static AudioEngineImpl* __impl = nullptr;
|
||||
|
||||
class CallerThreadUtils : public ICallerThreadUtils
|
||||
{
|
||||
@@ -107,16 +112,17 @@ static int fdGetter(const std::string& url, off_t* start, off_t* length)
|
||||
|
||||
//====================================================
|
||||
AudioEngineImpl::AudioEngineImpl()
|
||||
: _audioIDIndex(0)
|
||||
, _engineObject(nullptr)
|
||||
: _engineObject(nullptr)
|
||||
, _engineEngine(nullptr)
|
||||
, _outputMixObject(nullptr)
|
||||
, _lazyInitLoop(true)
|
||||
, _audioPlayerProvider(nullptr)
|
||||
, _onPauseListener(nullptr)
|
||||
, _onResumeListener(nullptr)
|
||||
, _audioIDIndex(0)
|
||||
, _lazyInitLoop(true)
|
||||
{
|
||||
__callerThreadUtils.setCallerThreadId(std::this_thread::get_id());
|
||||
__impl = this;
|
||||
}
|
||||
|
||||
AudioEngineImpl::~AudioEngineImpl()
|
||||
@@ -145,6 +151,8 @@ AudioEngineImpl::~AudioEngineImpl()
|
||||
{
|
||||
Director::getInstance()->getEventDispatcher()->removeEventListener(_onResumeListener);
|
||||
}
|
||||
|
||||
__impl = nullptr;
|
||||
}
|
||||
|
||||
bool AudioEngineImpl::init()
|
||||
@@ -225,6 +233,14 @@ void AudioEngineImpl::onEnterForeground(EventCustom* event)
|
||||
_urlAudioPlayersNeedResume.clear();
|
||||
}
|
||||
|
||||
void AudioEngineImpl::setAudioFocusForAllPlayers(bool isFocus)
|
||||
{
|
||||
for (const auto& e : _audioPlayers)
|
||||
{
|
||||
e.second->setAudioFocus(isFocus);
|
||||
}
|
||||
}
|
||||
|
||||
int AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume)
|
||||
{
|
||||
ALOGV("play2d, _audioPlayers.size=%d", (int)_audioPlayers.size());
|
||||
@@ -254,24 +270,27 @@ int AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume
|
||||
}
|
||||
|
||||
int id = player->getId();
|
||||
std::string filePath = *AudioEngine::_audioIDInfoMap[id].filePath;
|
||||
|
||||
ALOGV("Removing player id=%d, state:%d", id, (int)state);
|
||||
|
||||
AudioEngine::remove(id);
|
||||
_audioPlayers.erase(id);
|
||||
|
||||
auto iter = _callbackMap.find(id);
|
||||
if (iter != _callbackMap.end())
|
||||
{
|
||||
if (state == IAudioPlayer::State::OVER)
|
||||
{
|
||||
iter->second(id, *AudioEngine::_audioIDInfoMap[id].filePath);
|
||||
iter->second(id, filePath);
|
||||
}
|
||||
_callbackMap.erase(iter);
|
||||
}
|
||||
AudioEngine::remove(id);
|
||||
_audioPlayers.erase(id);
|
||||
});
|
||||
|
||||
player->setLoop(loop);
|
||||
player->setVolume(volume);
|
||||
player->setAudioFocus(__currentAudioFocus == AUDIOFOCUS_GAIN);
|
||||
player->play();
|
||||
}
|
||||
else
|
||||
@@ -437,4 +456,31 @@ void AudioEngineImpl::uncacheAll()
|
||||
}
|
||||
}
|
||||
|
||||
// It's invoked from javaactivity-android.cpp
|
||||
void cocos_audioengine_focus_change(int focusChange)
|
||||
{
|
||||
if (focusChange < AUDIOFOCUS_GAIN || focusChange > AUDIOFOCUS_LOST_TRANSIENT_CAN_DUCK)
|
||||
{
|
||||
CCLOGERROR("cocos_audioengine_focus_change: unknown value: %d", focusChange);
|
||||
return;
|
||||
}
|
||||
CCLOG("cocos_audioengine_focus_change: %d", focusChange);
|
||||
__currentAudioFocus = focusChange;
|
||||
|
||||
if (__impl == nullptr)
|
||||
{
|
||||
CCLOGWARN("cocos_audioengine_focus_change: AudioEngineImpl isn't ready!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (__currentAudioFocus == AUDIOFOCUS_GAIN)
|
||||
{
|
||||
__impl->setAudioFocusForAllPlayers(true);
|
||||
}
|
||||
else
|
||||
{
|
||||
__impl->setAudioFocusForAllPlayers(false);
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2014-2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2014-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -72,6 +72,7 @@ public:
|
||||
void uncacheAll();
|
||||
void preload(const std::string& filePath, const std::function<void(bool)>& callback);
|
||||
|
||||
void setAudioFocusForAllPlayers(bool isFocus);
|
||||
private:
|
||||
|
||||
void onEnterBackground(EventCustom* event);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -147,21 +147,23 @@ IAudioPlayer *AudioPlayerProvider::getAudioPlayer(const std::string &audioFilePa
|
||||
auto pcmData = std::make_shared<PcmData>();
|
||||
auto isSucceed = std::make_shared<bool>(false);
|
||||
auto isReturnFromCache = std::make_shared<bool>(false);
|
||||
auto isPreloadFinished = std::make_shared<bool>(false);
|
||||
|
||||
std::thread::id threadId = std::this_thread::get_id();
|
||||
|
||||
void* infoPtr = &info;
|
||||
std::string url = info.url;
|
||||
preloadEffect(info, [infoPtr, url, threadId, pcmData, isSucceed, isReturnFromCache](bool succeed, PcmData data){
|
||||
preloadEffect(info, [infoPtr, url, threadId, pcmData, isSucceed, isReturnFromCache, isPreloadFinished](bool succeed, PcmData data){
|
||||
// If the callback is in the same thread as caller's, it means that we found it
|
||||
// in the cache
|
||||
*isReturnFromCache = std::this_thread::get_id() == threadId;
|
||||
*pcmData = data;
|
||||
*isSucceed = succeed;
|
||||
*isPreloadFinished = true;
|
||||
ALOGV("FileInfo (%p), Set isSucceed flag: %d, path: %s", infoPtr, succeed, url.c_str());
|
||||
}, true);
|
||||
|
||||
if (!*isReturnFromCache)
|
||||
if (!*isReturnFromCache && !*isPreloadFinished)
|
||||
{
|
||||
std::unique_lock<std::mutex> lk(_preloadWaitMutex);
|
||||
// Wait for 2 seconds for the decoding in sub thread finishes.
|
||||
@@ -272,11 +274,12 @@ void AudioPlayerProvider::preloadEffect(const AudioFileInfo &info, const Preload
|
||||
ALOGV("audio (%s) is being preloaded, add to callback vector!", audioFilePath.c_str());
|
||||
PreloadCallbackParam param;
|
||||
param.callback = cb;
|
||||
param.isPreloadInPlay2d = isPreloadInPlay2d;
|
||||
preloadIter->second.push_back(std::move(param));
|
||||
return;
|
||||
}
|
||||
|
||||
// 3. Check it in cache again. If it has been removed from map just now, the file is in
|
||||
// 3. Check it in cache again. If it has been removed from map just now, the file is in
|
||||
// the cache absolutely.
|
||||
_pcmCacheMutex.lock();
|
||||
auto&& iter = _pcmCache.find(audioFilePath);
|
||||
@@ -289,15 +292,15 @@ void AudioPlayerProvider::preloadEffect(const AudioFileInfo &info, const Preload
|
||||
}
|
||||
_pcmCacheMutex.unlock();
|
||||
|
||||
|
||||
PreloadCallbackParam param;
|
||||
param.callback = cb;
|
||||
param.isPreloadInPlay2d = isPreloadInPlay2d;
|
||||
std::vector<PreloadCallbackParam> callbacks;
|
||||
callbacks.push_back(std::move(param));
|
||||
_preloadCallbackMap.insert(std::make_pair(audioFilePath, std::move(callbacks)));
|
||||
}
|
||||
|
||||
_threadPool->pushTask([this, audioFilePath, isPreloadInPlay2d](int tid) {
|
||||
_threadPool->pushTask([this, audioFilePath](int tid) {
|
||||
ALOGV("AudioPlayerProvider::preloadEffect: (%s)", audioFilePath.c_str());
|
||||
PcmData d;
|
||||
AudioDecoder* decoder = AudioDecoderProvider::createAudioDecoder(_engineItf, audioFilePath, _bufferSizeInFrames, _deviceSampleRate, _fdGetterCallback);
|
||||
@@ -325,13 +328,12 @@ void AudioPlayerProvider::preloadEffect(const AudioFileInfo &info, const Preload
|
||||
for (auto&& param : params)
|
||||
{
|
||||
param.callback(ret, result);
|
||||
if (param.isPreloadInPlay2d)
|
||||
{
|
||||
_preloadWaitCond.notify_one();
|
||||
}
|
||||
}
|
||||
_preloadCallbackMap.erase(preloadIter);
|
||||
|
||||
if (isPreloadInPlay2d)
|
||||
{
|
||||
_preloadWaitCond.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
AudioDecoderProvider::destroyAudioDecoder(&decoder);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -108,6 +108,7 @@ private:
|
||||
struct PreloadCallbackParam
|
||||
{
|
||||
PreloadCallback callback;
|
||||
bool isPreloadInPlay2d;
|
||||
};
|
||||
|
||||
std::unordered_map<std::string, std::vector<PreloadCallbackParam>> _preloadCallbackMap;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -102,7 +102,7 @@ ThreadPool *ThreadPool::newSingleThreadPool()
|
||||
}
|
||||
|
||||
ThreadPool::ThreadPool(int minNum, int maxNum)
|
||||
: _isStop(false), _isDone(false), _idleThreadNum(0), _minThreadNum(minNum),
|
||||
: _isDone(false), _isStop(false), _idleThreadNum(0), _minThreadNum(minNum),
|
||||
_maxThreadNum(maxNum), _initedThreadNum(0), _shrinkInterval(DEFAULT_SHRINK_INTERVAL),
|
||||
_shrinkStep(DEFAULT_SHRINK_STEP), _stretchStep(DEFAULT_STRETCH_STEP),
|
||||
_isFixedSize(false)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -68,6 +68,8 @@ public:
|
||||
|
||||
virtual float getVolume() const = 0;
|
||||
|
||||
virtual void setAudioFocus(bool isFocus) = 0;
|
||||
|
||||
virtual void setLoop(bool isLoop) = 0;
|
||||
|
||||
virtual bool isLoop() const = 0;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -110,6 +110,11 @@ float PcmAudioPlayer::getVolume() const
|
||||
return _track->getVolume();
|
||||
}
|
||||
|
||||
void PcmAudioPlayer::setAudioFocus(bool isFocus)
|
||||
{
|
||||
_track->setAudioFocus(isFocus);
|
||||
}
|
||||
|
||||
void PcmAudioPlayer::setLoop(bool isLoop)
|
||||
{
|
||||
_track->setLoop(isLoop);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -62,6 +62,8 @@ public:
|
||||
|
||||
virtual float getVolume() const override;
|
||||
|
||||
virtual void setAudioFocus(bool isFocus) override;
|
||||
|
||||
virtual void setLoop(bool isLoop) override;
|
||||
|
||||
virtual bool isLoop() const override;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -41,6 +41,7 @@ Track::Track(const PcmData &pcmData)
|
||||
, _isVolumeDirty(true)
|
||||
, _isLoop(false)
|
||||
, _isInitialized(false)
|
||||
, _isAudioFocus(true)
|
||||
{
|
||||
init(_pcmData.pcmBuffer->data(), _pcmData.numFrames, _pcmData.bitsPerSample / 8 * _pcmData.numChannels);
|
||||
}
|
||||
@@ -52,7 +53,8 @@ Track::~Track()
|
||||
|
||||
gain_minifloat_packed_t Track::getVolumeLR()
|
||||
{
|
||||
gain_minifloat_t v = gain_from_float(_volume);
|
||||
float volume = _isAudioFocus ? _volume : 0.0f;
|
||||
gain_minifloat_t v = gain_from_float(volume);
|
||||
return gain_minifloat_pack(v, v);
|
||||
}
|
||||
|
||||
@@ -83,6 +85,12 @@ float Track::getVolume() const
|
||||
return _volume;
|
||||
}
|
||||
|
||||
void Track::setAudioFocus(bool isFocus)
|
||||
{
|
||||
_isAudioFocus = isFocus;
|
||||
setVolumeDirty(true);
|
||||
}
|
||||
|
||||
void Track::setState(State state)
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(_stateMutex);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -62,6 +62,8 @@ public:
|
||||
void setVolume(float volume);
|
||||
float getVolume() const;
|
||||
|
||||
void setAudioFocus(bool isFocus);
|
||||
|
||||
bool setPosition(float pos);
|
||||
float getPosition() const;
|
||||
|
||||
@@ -96,6 +98,7 @@ private:
|
||||
std::mutex _volumeDirtyMutex;
|
||||
bool _isLoop;
|
||||
bool _isInitialized;
|
||||
bool _isAudioFocus;
|
||||
|
||||
friend class AudioMixerController;
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -60,7 +60,7 @@ UrlAudioPlayer::UrlAudioPlayer(SLEngineItf engineItf, SLObjectItf outputMixObjec
|
||||
: _engineItf(engineItf), _outputMixObj(outputMixObject),
|
||||
_callerThreadUtils(callerThreadUtils), _id(-1), _assetFd(nullptr),
|
||||
_playObj(nullptr), _playItf(nullptr), _seekItf(nullptr), _volumeItf(nullptr),
|
||||
_volume(0.0f), _duration(0.0f), _isLoop(false), _state(State::INVALID),
|
||||
_volume(0.0f), _duration(0.0f), _isLoop(false), _isAudioFocus(true), _state(State::INVALID),
|
||||
_playEventCallback(nullptr), _isDestroyed(std::make_shared<bool>(false))
|
||||
{
|
||||
std::call_once(__onceFlag, [](){
|
||||
@@ -215,16 +215,36 @@ void UrlAudioPlayer::play()
|
||||
}
|
||||
}
|
||||
|
||||
void UrlAudioPlayer::setVolume(float volume)
|
||||
void UrlAudioPlayer::setVolumeToSLPlayer(float volume)
|
||||
{
|
||||
_volume = volume;
|
||||
int dbVolume = 2000 * log10(volume);
|
||||
if (dbVolume < SL_MILLIBEL_MIN)
|
||||
{
|
||||
dbVolume = SL_MILLIBEL_MIN;
|
||||
}
|
||||
SLresult r = (*_volumeItf)->SetVolumeLevel(_volumeItf, dbVolume);
|
||||
SL_RETURN_IF_FAILED(r, "UrlAudioPlayer::setVolume %d failed", dbVolume);
|
||||
SL_RETURN_IF_FAILED(r, "UrlAudioPlayer::setVolumeToSLPlayer %d failed", dbVolume);
|
||||
}
|
||||
|
||||
void UrlAudioPlayer::setVolume(float volume)
|
||||
{
|
||||
_volume = volume;
|
||||
if (_isAudioFocus)
|
||||
{
|
||||
setVolumeToSLPlayer(_volume);
|
||||
}
|
||||
}
|
||||
|
||||
float UrlAudioPlayer::getVolume() const
|
||||
{
|
||||
return _volume;
|
||||
}
|
||||
|
||||
void UrlAudioPlayer::setAudioFocus(bool isFocus)
|
||||
{
|
||||
_isAudioFocus = isFocus;
|
||||
float volume = _isAudioFocus ? _volume : 0.0f;
|
||||
setVolumeToSLPlayer(volume);
|
||||
}
|
||||
|
||||
float UrlAudioPlayer::getDuration() const
|
||||
@@ -362,11 +382,6 @@ void UrlAudioPlayer::rewind()
|
||||
// Not supported currently. since cocos audio engine will new -> prepare -> play again.
|
||||
}
|
||||
|
||||
float UrlAudioPlayer::getVolume() const
|
||||
{
|
||||
return _volume;
|
||||
}
|
||||
|
||||
void UrlAudioPlayer::setLoop(bool isLoop)
|
||||
{
|
||||
_isLoop = isLoop;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -68,6 +68,8 @@ public:
|
||||
|
||||
virtual float getVolume() const override;
|
||||
|
||||
virtual void setAudioFocus(bool isFocus) override;
|
||||
|
||||
virtual void setLoop(bool isLoop) override;
|
||||
|
||||
virtual bool isLoop() const override;
|
||||
@@ -97,6 +99,8 @@ private:
|
||||
|
||||
void playEventCallback(SLPlayItf caller, SLuint32 playEvent);
|
||||
|
||||
void setVolumeToSLPlayer(float volume);
|
||||
|
||||
private:
|
||||
SLEngineItf _engineItf;
|
||||
SLObjectItf _outputMixObj;
|
||||
@@ -115,6 +119,7 @@ private:
|
||||
float _volume;
|
||||
float _duration;
|
||||
bool _isLoop;
|
||||
bool _isAudioFocus;
|
||||
State _state;
|
||||
|
||||
PlayEventCallback _playEventCallback;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2010-2012 cocos2d-x.org
|
||||
Copyright (c) 2013-2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2013-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2010-2012 cocos2d-x.org
|
||||
Copyright (c) 2013-2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2013-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2010-2012 cocos2d-x.org
|
||||
Copyright (c) 2013-2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2013-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2010-2012 cocos2d-x.org
|
||||
Copyright (c) 2013-2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2013-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -271,6 +271,10 @@ void AndroidJavaEngine::preloadEffect(const char* filePath)
|
||||
std::string fullPath = CocosDenshion::android::getFullPathWithoutAssetsPrefix(filePath);
|
||||
JniHelper::callStaticVoidMethod(helperClassName, "preloadEffect", fullPath);
|
||||
}
|
||||
else
|
||||
{
|
||||
AudioEngine::preload(filePath);
|
||||
}
|
||||
}
|
||||
|
||||
void AndroidJavaEngine::unloadEffect(const char* filePath)
|
||||
@@ -280,4 +284,8 @@ void AndroidJavaEngine::unloadEffect(const char* filePath)
|
||||
std::string fullPath = CocosDenshion::android::getFullPathWithoutAssetsPrefix(filePath);
|
||||
JniHelper::callStaticVoidMethod(helperClassName, "unloadEffect", fullPath);
|
||||
}
|
||||
else
|
||||
{
|
||||
AudioEngine::uncache(filePath);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2010-2012 cocos2d-x.org
|
||||
Copyright (c) 2013-2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2013-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
|
||||
@@ -26,6 +26,8 @@
|
||||
* SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#define LOG_TAG "mp3reader"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <assert.h>
|
||||
#include <stdint.h>
|
||||
@@ -34,7 +36,7 @@
|
||||
#include "audio/android/cutils/log.h"
|
||||
|
||||
#include "pvmp3decoder_api.h"
|
||||
#include "mp3reader.h"
|
||||
#include "audio/android/mp3reader.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
@@ -239,6 +241,9 @@ static bool resync(
|
||||
len += 10;
|
||||
|
||||
*inout_pos += len;
|
||||
|
||||
ALOGV("skipped ID3 tag, new starting offset is %lld (0x%016llx)",
|
||||
(long long)*inout_pos, (long long)*inout_pos);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -256,8 +261,9 @@ static bool resync(
|
||||
uint8_t *tmp = buf;
|
||||
|
||||
do {
|
||||
if (pos >= *inout_pos + kMaxBytesChecked) {
|
||||
if (pos >= (off64_t)(*inout_pos + kMaxBytesChecked)) {
|
||||
// Don't scan forever.
|
||||
ALOGV("giving up at offset %lld", (long long)pos);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -306,6 +312,7 @@ static bool resync(
|
||||
continue;
|
||||
}
|
||||
|
||||
// ALOGV("found possible 1st frame at %lld (header = 0x%08x)", (long long)pos, header);
|
||||
// We found what looks like a valid frame,
|
||||
// now find its successors.
|
||||
|
||||
@@ -323,6 +330,8 @@ static bool resync(
|
||||
|
||||
uint32_t test_header = U32_AT(tmp);
|
||||
|
||||
ALOGV("subsequent header is %08x", test_header);
|
||||
|
||||
if ((test_header & kMask) != (header & kMask)) {
|
||||
valid = false;
|
||||
break;
|
||||
@@ -334,6 +343,7 @@ static bool resync(
|
||||
break;
|
||||
}
|
||||
|
||||
ALOGV("found subsequent frame #%d at %lld", j + 2, (long long)test_pos);
|
||||
test_pos += test_frame_size;
|
||||
}
|
||||
|
||||
@@ -343,6 +353,8 @@ static bool resync(
|
||||
if (out_header != NULL) {
|
||||
*out_header = header;
|
||||
}
|
||||
} else {
|
||||
ALOGV("no dice, no valid sequence of frames found.");
|
||||
}
|
||||
|
||||
++pos;
|
||||
@@ -369,7 +381,11 @@ bool Mp3Reader::init(mp3_callbacks *callback, void* source) {
|
||||
off64_t pos = 0;
|
||||
uint32_t header;
|
||||
bool success = resync(callback, source, 0 /*match_header*/, &pos, &header);
|
||||
if (success == false) return false;
|
||||
if (!success)
|
||||
{
|
||||
ALOGE("%s, resync failed", __FUNCTION__);
|
||||
return false;
|
||||
}
|
||||
|
||||
mCurrentPos = pos;
|
||||
mFixedHeader = header;
|
||||
@@ -455,7 +471,7 @@ int decodeMP3(mp3_callbacks* cb, void* source, std::vector<char>& pcmBuffer, int
|
||||
Mp3Reader mp3Reader;
|
||||
bool success = mp3Reader.init(cb, source);
|
||||
if (!success) {
|
||||
fprintf(stderr, "Encountered error reading\n");
|
||||
ALOGE("mp3Reader.init: Encountered error reading\n");
|
||||
free(decoderBuf);
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
@@ -468,7 +484,7 @@ int decodeMP3(mp3_callbacks* cb, void* source, std::vector<char>& pcmBuffer, int
|
||||
// sfInfo.samplerate = mp3Reader.getSampleRate();
|
||||
// SNDFILE *handle = sf_open(argv[2], SFM_WRITE, &sfInfo);
|
||||
// if (handle == NULL) {
|
||||
// fprintf(stderr, "Encountered error writing %s\n", argv[2]);
|
||||
// ALOGE("Encountered error writing %s\n", argv[2]);
|
||||
// mp3Reader.close();
|
||||
// free(decoderBuf);
|
||||
// return EXIT_FAILURE;
|
||||
@@ -504,7 +520,7 @@ int decodeMP3(mp3_callbacks* cb, void* source, std::vector<char>& pcmBuffer, int
|
||||
ERROR_CODE decoderErr;
|
||||
decoderErr = pvmp3_framedecoder(&config, decoderBuf);
|
||||
if (decoderErr != NO_DECODING_ERROR) {
|
||||
fprintf(stderr, "Decoder encountered error\n");
|
||||
ALOGE("Decoder encountered error=%d", decoderErr);
|
||||
retVal = EXIT_FAILURE;
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,518 @@
|
||||
/*
|
||||
* Copyright (C) 2012 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#define LOG_TAG "tinysndfile"
|
||||
|
||||
#include "audio/android/tinysndfile.h"
|
||||
#include "audio/android/audio_utils/include/audio_utils/primitives.h"
|
||||
#include "audio/android/cutils/log.h"
|
||||
|
||||
// #ifdef HAVE_STDERR
|
||||
// #include <stdio.h>
|
||||
// #endif
|
||||
|
||||
#include <string.h>
|
||||
#include <errno.h>
|
||||
|
||||
#ifndef HAVE_STDERR
|
||||
#define HAVE_STDERR
|
||||
#endif
|
||||
|
||||
#define WAVE_FORMAT_PCM 1
|
||||
#define WAVE_FORMAT_IEEE_FLOAT 3
|
||||
#define WAVE_FORMAT_EXTENSIBLE 0xFFFE
|
||||
|
||||
static snd_callbacks __defaultCallback;
|
||||
static int __inited = 0;
|
||||
|
||||
struct SNDFILE_ {
|
||||
uint8_t *temp; // realloc buffer used for shrinking 16 bits to 8 bits and byte-swapping
|
||||
void *stream;
|
||||
size_t bytesPerFrame;
|
||||
size_t remaining; // frames unread for SFM_READ, frames written for SFM_WRITE
|
||||
SF_INFO info;
|
||||
snd_callbacks callback;
|
||||
};
|
||||
|
||||
static unsigned little2u(unsigned char *ptr)
|
||||
{
|
||||
return (ptr[1] << 8) + ptr[0];
|
||||
}
|
||||
|
||||
static unsigned little4u(unsigned char *ptr)
|
||||
{
|
||||
return (ptr[3] << 24) + (ptr[2] << 16) + (ptr[1] << 8) + ptr[0];
|
||||
}
|
||||
|
||||
static int isLittleEndian(void)
|
||||
{
|
||||
static const short one = 1;
|
||||
return *((const char *) &one) == 1;
|
||||
}
|
||||
|
||||
// "swab" conflicts with OS X <string.h>
|
||||
static void my_swab(short *ptr, size_t numToSwap)
|
||||
{
|
||||
while (numToSwap > 0) {
|
||||
*ptr = little2u((unsigned char *) ptr);
|
||||
--numToSwap;
|
||||
++ptr;
|
||||
}
|
||||
}
|
||||
|
||||
static void* open_func(const char* path, void* user)
|
||||
{
|
||||
return fopen(path, "rb");
|
||||
}
|
||||
|
||||
static size_t read_func(void *ptr, size_t size, size_t nmemb, void* datasource)
|
||||
{
|
||||
return fread(ptr, size, nmemb, (FILE*)datasource);
|
||||
}
|
||||
|
||||
static int seek_func(void* datasource, long offset, int whence)
|
||||
{
|
||||
return fseek((FILE*)datasource, offset, whence);
|
||||
}
|
||||
|
||||
static int close_func(void* datasource)
|
||||
{
|
||||
return fclose((FILE*)datasource);
|
||||
}
|
||||
|
||||
static long tell_func(void* datasource)
|
||||
{
|
||||
return ftell((FILE*)datasource);
|
||||
}
|
||||
|
||||
static void lazyInit()
|
||||
{
|
||||
if (__inited == 0)
|
||||
{
|
||||
__defaultCallback.open = open_func;
|
||||
__defaultCallback.read = read_func;
|
||||
__defaultCallback.seek = seek_func;
|
||||
__defaultCallback.close = close_func;
|
||||
__defaultCallback.tell = tell_func;
|
||||
__inited = 1;
|
||||
}
|
||||
}
|
||||
|
||||
SNDFILE *sf_open_read(const char *path, SF_INFO *info, snd_callbacks* cb, void* user)
|
||||
{
|
||||
lazyInit();
|
||||
|
||||
if (path == NULL || info == NULL) {
|
||||
#ifdef HAVE_STDERR
|
||||
ALOGE("path=%p info=%p\n", path, info);
|
||||
#endif
|
||||
return NULL;
|
||||
}
|
||||
|
||||
SNDFILE *handle = (SNDFILE *) malloc(sizeof(SNDFILE));
|
||||
handle->temp = NULL;
|
||||
|
||||
handle->info.format = SF_FORMAT_WAV;
|
||||
if (cb != NULL) {
|
||||
handle->callback = *cb;
|
||||
} else {
|
||||
handle->callback = __defaultCallback;
|
||||
}
|
||||
|
||||
void* stream = handle->callback.open(path, user);
|
||||
if (stream == NULL) {
|
||||
#ifdef HAVE_STDERR
|
||||
ALOGE("fopen %s failed errno %d\n", path, errno);
|
||||
#endif
|
||||
free(handle);
|
||||
return NULL;
|
||||
}
|
||||
handle->stream = stream;
|
||||
|
||||
// don't attempt to parse all valid forms, just the most common ones
|
||||
unsigned char wav[12];
|
||||
size_t actual;
|
||||
unsigned riffSize;
|
||||
size_t remaining;
|
||||
int hadFmt = 0;
|
||||
int hadData = 0;
|
||||
long dataTell = 0L;
|
||||
|
||||
actual = handle->callback.read(wav, sizeof(char), sizeof(wav), stream);
|
||||
if (actual < 12) {
|
||||
#ifdef HAVE_STDERR
|
||||
ALOGE("actual %zu < 44\n", actual);
|
||||
#endif
|
||||
goto close;
|
||||
}
|
||||
if (memcmp(wav, "RIFF", 4)) {
|
||||
#ifdef HAVE_STDERR
|
||||
ALOGE("wav != RIFF\n");
|
||||
#endif
|
||||
goto close;
|
||||
}
|
||||
riffSize = little4u(&wav[4]);
|
||||
if (riffSize < 4) {
|
||||
#ifdef HAVE_STDERR
|
||||
ALOGE("riffSize %u < 4\n", riffSize);
|
||||
#endif
|
||||
goto close;
|
||||
}
|
||||
if (memcmp(&wav[8], "WAVE", 4)) {
|
||||
#ifdef HAVE_STDERR
|
||||
ALOGE("missing WAVE\n");
|
||||
#endif
|
||||
goto close;
|
||||
}
|
||||
remaining = riffSize - 4;
|
||||
|
||||
while (remaining >= 8) {
|
||||
unsigned char chunk[8];
|
||||
actual = handle->callback.read(chunk, sizeof(char), sizeof(chunk), stream);
|
||||
if (actual != sizeof(chunk)) {
|
||||
#ifdef HAVE_STDERR
|
||||
ALOGE("actual %zu != %zu\n", actual, sizeof(chunk));
|
||||
#endif
|
||||
goto close;
|
||||
}
|
||||
remaining -= 8;
|
||||
unsigned chunkSize = little4u(&chunk[4]);
|
||||
if (chunkSize > remaining) {
|
||||
#ifdef HAVE_STDERR
|
||||
ALOGE("chunkSize %u > remaining %zu\n", chunkSize, remaining);
|
||||
#endif
|
||||
goto close;
|
||||
}
|
||||
if (!memcmp(&chunk[0], "fmt ", 4)) {
|
||||
if (hadFmt) {
|
||||
#ifdef HAVE_STDERR
|
||||
ALOGE("multiple fmt\n");
|
||||
#endif
|
||||
goto close;
|
||||
}
|
||||
if (chunkSize < 2) {
|
||||
#ifdef HAVE_STDERR
|
||||
ALOGE("chunkSize %u < 2\n", chunkSize);
|
||||
#endif
|
||||
goto close;
|
||||
}
|
||||
unsigned char fmt[40];
|
||||
actual = handle->callback.read(fmt, sizeof(char), 2, stream);
|
||||
if (actual != 2) {
|
||||
#ifdef HAVE_STDERR
|
||||
ALOGE("actual %zu != 2\n", actual);
|
||||
#endif
|
||||
goto close;
|
||||
}
|
||||
unsigned format = little2u(&fmt[0]);
|
||||
size_t minSize = 0;
|
||||
switch (format) {
|
||||
case WAVE_FORMAT_PCM:
|
||||
case WAVE_FORMAT_IEEE_FLOAT:
|
||||
minSize = 16;
|
||||
break;
|
||||
case WAVE_FORMAT_EXTENSIBLE:
|
||||
minSize = 40;
|
||||
break;
|
||||
default:
|
||||
#ifdef HAVE_STDERR
|
||||
ALOGE("unsupported format %u\n", format);
|
||||
#endif
|
||||
goto close;
|
||||
}
|
||||
if (chunkSize < minSize) {
|
||||
#ifdef HAVE_STDERR
|
||||
ALOGE("chunkSize %u < minSize %zu\n", chunkSize, minSize);
|
||||
#endif
|
||||
goto close;
|
||||
}
|
||||
actual = handle->callback.read(&fmt[2], sizeof(char), minSize - 2, stream);
|
||||
if (actual != minSize - 2) {
|
||||
#ifdef HAVE_STDERR
|
||||
ALOGE("actual %zu != %zu\n", actual, minSize - 16);
|
||||
#endif
|
||||
goto close;
|
||||
}
|
||||
if (chunkSize > minSize) {
|
||||
handle->callback.seek(stream, (long) (chunkSize - minSize), SEEK_CUR);
|
||||
}
|
||||
unsigned channels = little2u(&fmt[2]);
|
||||
// FIXME FCC_8
|
||||
if (channels != 1 && channels != 2 && channels != 4 && channels != 6 && channels != 8) {
|
||||
#ifdef HAVE_STDERR
|
||||
ALOGE("unsupported channels %u\n", channels);
|
||||
#endif
|
||||
goto close;
|
||||
}
|
||||
unsigned samplerate = little4u(&fmt[4]);
|
||||
if (samplerate == 0) {
|
||||
#ifdef HAVE_STDERR
|
||||
ALOGE("samplerate %u == 0\n", samplerate);
|
||||
#endif
|
||||
goto close;
|
||||
}
|
||||
// ignore byte rate
|
||||
// ignore block alignment
|
||||
unsigned bitsPerSample = little2u(&fmt[14]);
|
||||
if (bitsPerSample != 8 && bitsPerSample != 16 && bitsPerSample != 24 &&
|
||||
bitsPerSample != 32) {
|
||||
#ifdef HAVE_STDERR
|
||||
ALOGE("bitsPerSample %u != 8 or 16 or 24 or 32\n", bitsPerSample);
|
||||
#endif
|
||||
goto close;
|
||||
}
|
||||
unsigned bytesPerFrame = (bitsPerSample >> 3) * channels;
|
||||
handle->bytesPerFrame = bytesPerFrame;
|
||||
handle->info.samplerate = samplerate;
|
||||
handle->info.channels = channels;
|
||||
switch (bitsPerSample) {
|
||||
case 8:
|
||||
handle->info.format |= SF_FORMAT_PCM_U8;
|
||||
break;
|
||||
case 16:
|
||||
handle->info.format |= SF_FORMAT_PCM_16;
|
||||
break;
|
||||
case 24:
|
||||
handle->info.format |= SF_FORMAT_PCM_24;
|
||||
break;
|
||||
case 32:
|
||||
if (format == WAVE_FORMAT_IEEE_FLOAT)
|
||||
handle->info.format |= SF_FORMAT_FLOAT;
|
||||
else
|
||||
handle->info.format |= SF_FORMAT_PCM_32;
|
||||
break;
|
||||
}
|
||||
hadFmt = 1;
|
||||
} else if (!memcmp(&chunk[0], "data", 4)) {
|
||||
if (!hadFmt) {
|
||||
#ifdef HAVE_STDERR
|
||||
ALOGE("data not preceded by fmt\n");
|
||||
#endif
|
||||
goto close;
|
||||
}
|
||||
if (hadData) {
|
||||
#ifdef HAVE_STDERR
|
||||
ALOGE("multiple data\n");
|
||||
#endif
|
||||
goto close;
|
||||
}
|
||||
handle->remaining = chunkSize / handle->bytesPerFrame;
|
||||
handle->info.frames = handle->remaining;
|
||||
dataTell = handle->callback.tell(stream);
|
||||
if (chunkSize > 0) {
|
||||
handle->callback.seek(stream, (long) chunkSize, SEEK_CUR);
|
||||
}
|
||||
hadData = 1;
|
||||
} else if (!memcmp(&chunk[0], "fact", 4)) {
|
||||
// ignore fact
|
||||
if (chunkSize > 0) {
|
||||
handle->callback.seek(stream, (long) chunkSize, SEEK_CUR);
|
||||
}
|
||||
} else {
|
||||
// ignore unknown chunk
|
||||
#ifdef HAVE_STDERR
|
||||
ALOGE("ignoring unknown chunk %c%c%c%c\n",
|
||||
chunk[0], chunk[1], chunk[2], chunk[3]);
|
||||
#endif
|
||||
if (chunkSize > 0) {
|
||||
handle->callback.seek(stream, (long) chunkSize, SEEK_CUR);
|
||||
}
|
||||
}
|
||||
remaining -= chunkSize;
|
||||
}
|
||||
if (remaining > 0) {
|
||||
#ifdef HAVE_STDERR
|
||||
ALOGE("partial chunk at end of RIFF, remaining %zu\n", remaining);
|
||||
#endif
|
||||
goto close;
|
||||
}
|
||||
if (!hadData) {
|
||||
#ifdef HAVE_STDERR
|
||||
ALOGE("missing data\n");
|
||||
#endif
|
||||
goto close;
|
||||
}
|
||||
(void) handle->callback.seek(stream, dataTell, SEEK_SET);
|
||||
*info = handle->info;
|
||||
return handle;
|
||||
|
||||
close:
|
||||
free(handle);
|
||||
handle->callback.close(stream);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void sf_close(SNDFILE *handle)
|
||||
{
|
||||
if (handle == NULL)
|
||||
return;
|
||||
free(handle->temp);
|
||||
(void) handle->callback.close(handle->stream);
|
||||
free(handle);
|
||||
}
|
||||
|
||||
sf_count_t sf_readf_short(SNDFILE *handle, short *ptr, sf_count_t desiredFrames)
|
||||
{
|
||||
if (handle == NULL || ptr == NULL || !handle->remaining ||
|
||||
desiredFrames <= 0) {
|
||||
return 0;
|
||||
}
|
||||
if (handle->remaining < (size_t) desiredFrames) {
|
||||
desiredFrames = handle->remaining;
|
||||
}
|
||||
// does not check for numeric overflow
|
||||
size_t desiredBytes = desiredFrames * handle->bytesPerFrame;
|
||||
size_t actualBytes;
|
||||
void *temp = NULL;
|
||||
unsigned format = handle->info.format & SF_FORMAT_SUBMASK;
|
||||
if (format == SF_FORMAT_PCM_32 || format == SF_FORMAT_FLOAT || format == SF_FORMAT_PCM_24) {
|
||||
temp = malloc(desiredBytes);
|
||||
actualBytes = handle->callback.read(temp, sizeof(char), desiredBytes, handle->stream);
|
||||
} else {
|
||||
actualBytes = handle->callback.read(ptr, sizeof(char), desiredBytes, handle->stream);
|
||||
}
|
||||
size_t actualFrames = actualBytes / handle->bytesPerFrame;
|
||||
handle->remaining -= actualFrames;
|
||||
switch (format) {
|
||||
case SF_FORMAT_PCM_U8:
|
||||
memcpy_to_i16_from_u8(ptr, (unsigned char *) ptr, actualFrames * handle->info.channels);
|
||||
break;
|
||||
case SF_FORMAT_PCM_16:
|
||||
if (!isLittleEndian())
|
||||
my_swab(ptr, actualFrames * handle->info.channels);
|
||||
break;
|
||||
case SF_FORMAT_PCM_32:
|
||||
memcpy_to_i16_from_i32(ptr, (const int *) temp, actualFrames * handle->info.channels);
|
||||
free(temp);
|
||||
break;
|
||||
case SF_FORMAT_FLOAT:
|
||||
memcpy_to_i16_from_float(ptr, (const float *) temp, actualFrames * handle->info.channels);
|
||||
free(temp);
|
||||
break;
|
||||
case SF_FORMAT_PCM_24:
|
||||
memcpy_to_i16_from_p24(ptr, (const uint8_t *) temp, actualFrames * handle->info.channels);
|
||||
free(temp);
|
||||
break;
|
||||
default:
|
||||
memset(ptr, 0, actualFrames * handle->info.channels * sizeof(short));
|
||||
break;
|
||||
}
|
||||
return actualFrames;
|
||||
}
|
||||
|
||||
/*
|
||||
sf_count_t sf_readf_float(SNDFILE *handle, float *ptr, sf_count_t desiredFrames)
|
||||
{
|
||||
if (handle == NULL || ptr == NULL || !handle->remaining ||
|
||||
desiredFrames <= 0) {
|
||||
return 0;
|
||||
}
|
||||
if (handle->remaining < (size_t) desiredFrames) {
|
||||
desiredFrames = handle->remaining;
|
||||
}
|
||||
// does not check for numeric overflow
|
||||
size_t desiredBytes = desiredFrames * handle->bytesPerFrame;
|
||||
size_t actualBytes;
|
||||
void *temp = NULL;
|
||||
unsigned format = handle->info.format & SF_FORMAT_SUBMASK;
|
||||
if (format == SF_FORMAT_PCM_16 || format == SF_FORMAT_PCM_U8 || format == SF_FORMAT_PCM_24) {
|
||||
temp = malloc(desiredBytes);
|
||||
actualBytes = handle->callback.read(temp, sizeof(char), desiredBytes, handle->stream);
|
||||
} else {
|
||||
actualBytes = handle->callback.read(ptr, sizeof(char), desiredBytes, handle->stream);
|
||||
}
|
||||
size_t actualFrames = actualBytes / handle->bytesPerFrame;
|
||||
handle->remaining -= actualFrames;
|
||||
switch (format) {
|
||||
case SF_FORMAT_PCM_U8:
|
||||
#if 0
|
||||
// TODO - implement
|
||||
memcpy_to_float_from_u8(ptr, (const unsigned char *) temp,
|
||||
actualFrames * handle->info.channels);
|
||||
#endif
|
||||
free(temp);
|
||||
break;
|
||||
case SF_FORMAT_PCM_16:
|
||||
memcpy_to_float_from_i16(ptr, (const short *) temp, actualFrames * handle->info.channels);
|
||||
free(temp);
|
||||
break;
|
||||
case SF_FORMAT_PCM_32:
|
||||
memcpy_to_float_from_i32(ptr, (const int *) ptr, actualFrames * handle->info.channels);
|
||||
break;
|
||||
case SF_FORMAT_FLOAT:
|
||||
break;
|
||||
case SF_FORMAT_PCM_24:
|
||||
memcpy_to_float_from_p24(ptr, (const uint8_t *) temp, actualFrames * handle->info.channels);
|
||||
free(temp);
|
||||
break;
|
||||
default:
|
||||
memset(ptr, 0, actualFrames * handle->info.channels * sizeof(float));
|
||||
break;
|
||||
}
|
||||
return actualFrames;
|
||||
}
|
||||
|
||||
sf_count_t sf_readf_int(SNDFILE *handle, int *ptr, sf_count_t desiredFrames)
|
||||
{
|
||||
if (handle == NULL || ptr == NULL || !handle->remaining ||
|
||||
desiredFrames <= 0) {
|
||||
return 0;
|
||||
}
|
||||
if (handle->remaining < (size_t) desiredFrames) {
|
||||
desiredFrames = handle->remaining;
|
||||
}
|
||||
// does not check for numeric overflow
|
||||
size_t desiredBytes = desiredFrames * handle->bytesPerFrame;
|
||||
void *temp = NULL;
|
||||
unsigned format = handle->info.format & SF_FORMAT_SUBMASK;
|
||||
size_t actualBytes;
|
||||
if (format == SF_FORMAT_PCM_16 || format == SF_FORMAT_PCM_U8 || format == SF_FORMAT_PCM_24) {
|
||||
temp = malloc(desiredBytes);
|
||||
actualBytes = handle->callback.read(temp, sizeof(char), desiredBytes, handle->stream);
|
||||
} else {
|
||||
actualBytes = handle->callback.read(ptr, sizeof(char), desiredBytes, handle->stream);
|
||||
}
|
||||
size_t actualFrames = actualBytes / handle->bytesPerFrame;
|
||||
handle->remaining -= actualFrames;
|
||||
switch (format) {
|
||||
case SF_FORMAT_PCM_U8:
|
||||
#if 0
|
||||
// TODO - implement
|
||||
memcpy_to_i32_from_u8(ptr, (const unsigned char *) temp,
|
||||
actualFrames * handle->info.channels);
|
||||
#endif
|
||||
free(temp);
|
||||
break;
|
||||
case SF_FORMAT_PCM_16:
|
||||
memcpy_to_i32_from_i16(ptr, (const short *) temp, actualFrames * handle->info.channels);
|
||||
free(temp);
|
||||
break;
|
||||
case SF_FORMAT_PCM_32:
|
||||
break;
|
||||
case SF_FORMAT_FLOAT:
|
||||
memcpy_to_i32_from_float(ptr, (const float *) ptr, actualFrames * handle->info.channels);
|
||||
break;
|
||||
case SF_FORMAT_PCM_24:
|
||||
memcpy_to_i32_from_p24(ptr, (const uint8_t *) temp, actualFrames * handle->info.channels);
|
||||
free(temp);
|
||||
break;
|
||||
default:
|
||||
memset(ptr, 0, actualFrames * handle->info.channels * sizeof(int));
|
||||
break;
|
||||
}
|
||||
return actualFrames;
|
||||
}
|
||||
*/
|
||||
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
* Copyright (C) 2012 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
// This is a C library for reading and writing PCM .wav files. It is
|
||||
// influenced by other libraries such as libsndfile and audiofile, except is
|
||||
// much smaller and has an Apache 2.0 license.
|
||||
// The API should be familiar to clients of similar libraries, but there is
|
||||
// no guarantee that it will stay exactly source-code compatible with other libraries.
|
||||
|
||||
#include <stdio.h>
|
||||
#include <sys/cdefs.h>
|
||||
|
||||
__BEGIN_DECLS
|
||||
|
||||
// visible to clients
|
||||
typedef int sf_count_t;
|
||||
|
||||
typedef struct {
|
||||
sf_count_t frames;
|
||||
int samplerate;
|
||||
int channels;
|
||||
int format;
|
||||
} SF_INFO;
|
||||
|
||||
// opaque to clients
|
||||
typedef struct SNDFILE_ SNDFILE;
|
||||
|
||||
// Format
|
||||
#define SF_FORMAT_TYPEMASK 1
|
||||
#define SF_FORMAT_WAV 1
|
||||
#define SF_FORMAT_SUBMASK 14
|
||||
#define SF_FORMAT_PCM_16 2
|
||||
#define SF_FORMAT_PCM_U8 4
|
||||
#define SF_FORMAT_FLOAT 6
|
||||
#define SF_FORMAT_PCM_32 8
|
||||
#define SF_FORMAT_PCM_24 10
|
||||
|
||||
typedef struct {
|
||||
void* (*open)(const char* path, void* user);
|
||||
size_t (*read) (void* ptr, size_t size, size_t nmemb, void* datasource);
|
||||
int (*seek) (void* datasource, long offset, int whence);
|
||||
int (*close) (void* datasource);
|
||||
long (*tell) (void* datasource);
|
||||
} snd_callbacks;
|
||||
|
||||
// Open stream
|
||||
SNDFILE *sf_open_read(const char *path, SF_INFO *info, snd_callbacks* cb, void* user);
|
||||
|
||||
// Close stream
|
||||
void sf_close(SNDFILE *handle);
|
||||
|
||||
// Read interleaved frames and return actual number of frames read
|
||||
sf_count_t sf_readf_short(SNDFILE *handle, short *ptr, sf_count_t desired);
|
||||
/*
|
||||
sf_count_t sf_readf_float(SNDFILE *handle, float *ptr, sf_count_t desired);
|
||||
sf_count_t sf_readf_int(SNDFILE *handle, int *ptr, sf_count_t desired);
|
||||
*/
|
||||
|
||||
__END_DECLS
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2014-2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2014-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2014-2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2014-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -66,14 +66,57 @@ static ALvoid alBufferDataStaticProc(const ALint bid, ALenum format, ALvoid* da
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@interface NSTimerWrapper : NSObject
|
||||
{
|
||||
std::function<void()> _timeoutCallback;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation NSTimerWrapper
|
||||
|
||||
-(id) initWithTimeInterval:(double) seconds callback:(const std::function<void()>&) cb
|
||||
{
|
||||
if (self = [super init])
|
||||
{
|
||||
_timeoutCallback = cb;
|
||||
NSTimer* timer = [NSTimer timerWithTimeInterval:seconds target: self selector:@selector(onTimeoutCallback:) userInfo:nil repeats:NO];
|
||||
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
-(void) onTimeoutCallback: (NSTimer*) timer
|
||||
{
|
||||
if (_timeoutCallback != nullptr)
|
||||
{
|
||||
_timeoutCallback();
|
||||
_timeoutCallback = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
-(void) dealloc
|
||||
{
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
static void setTimeout(double seconds, const std::function<void()>& cb)
|
||||
{
|
||||
[[[NSTimerWrapper alloc] initWithTimeInterval:seconds callback:cb] autorelease];
|
||||
}
|
||||
|
||||
using namespace cocos2d;
|
||||
using namespace cocos2d::experimental;
|
||||
|
||||
AudioCache::AudioCache()
|
||||
: _totalFrames(0)
|
||||
, _framesRead(0)
|
||||
, _format(-1)
|
||||
: _format(-1)
|
||||
, _duration(0.0f)
|
||||
, _totalFrames(0)
|
||||
, _framesRead(0)
|
||||
, _alBufferId(INVALID_AL_BUFFER_ID)
|
||||
, _pcmData(nullptr)
|
||||
, _queBufferFrames(0)
|
||||
@@ -125,7 +168,17 @@ AudioCache::~AudioCache()
|
||||
ALOGW("AudioCache (%p), id=%u, buffer isn't ready, state=%d", this, _id, _state);
|
||||
}
|
||||
|
||||
free(_pcmData);
|
||||
// fixed #17494: CrashIfClientProvidedBogusAudioBufferList
|
||||
// We're using 'alBufferDataStaticProc' for speeding up
|
||||
// the performance of playing audio without preload, but we need to manage the memory by ourself carefully.
|
||||
// It's probably that '_pcmData' is freed before OpenAL finishes the audio render task,
|
||||
// then 'CrashIfClientProvidedBogusAudioBufferList' may be triggered.
|
||||
// 'cpp-tests/NewAudioEngineTest/AudioSwitchStateTest' can reproduce this issue without the following fix.
|
||||
// The workaround is delaying 200ms to free pcm data.
|
||||
char* data = _pcmData;
|
||||
setTimeout(0.2, [data](){
|
||||
free(data);
|
||||
});
|
||||
}
|
||||
|
||||
if (_queBufferFrames > 0)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -25,6 +25,8 @@
|
||||
#include "audio/apple/AudioDecoder.h"
|
||||
#include "audio/apple/AudioMacros.h"
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#define LOG_TAG "AudioDecoder"
|
||||
|
||||
namespace cocos2d { namespace experimental {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2014-2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2014-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2014-2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2014-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -79,8 +79,9 @@ void AudioEngineInterruptionListenerCallback(void* user_data, UInt32 interruptio
|
||||
if (self = [super init])
|
||||
{
|
||||
if ([[[UIDevice currentDevice] systemVersion] intValue] > 5) {
|
||||
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
|
||||
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:UIApplicationDidBecomeActiveNotification object:nil];
|
||||
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
|
||||
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:UIApplicationDidBecomeActiveNotification object:nil];
|
||||
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:UIApplicationWillResignActiveNotification object:nil];
|
||||
}
|
||||
// only enable it on iOS. Disable it on tvOS
|
||||
// AudioSessionInitialize removed from tvOS
|
||||
@@ -95,37 +96,83 @@ void AudioEngineInterruptionListenerCallback(void* user_data, UInt32 interruptio
|
||||
|
||||
-(void)handleInterruption:(NSNotification*)notification
|
||||
{
|
||||
static bool isAudioSessionInterrupted = false;
|
||||
static bool resumeOnBecomingActive = false;
|
||||
static bool pauseOnResignActive = false;
|
||||
|
||||
if ([notification.name isEqualToString:AVAudioSessionInterruptionNotification]) {
|
||||
if ([notification.name isEqualToString:AVAudioSessionInterruptionNotification])
|
||||
{
|
||||
NSInteger reason = [[[notification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey] integerValue];
|
||||
if (reason == AVAudioSessionInterruptionTypeBegan) {
|
||||
alcMakeContextCurrent(NULL);
|
||||
if (reason == AVAudioSessionInterruptionTypeBegan)
|
||||
{
|
||||
isAudioSessionInterrupted = true;
|
||||
|
||||
if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive)
|
||||
{
|
||||
ALOGD("AVAudioSessionInterruptionTypeBegan, application != UIApplicationStateActive, alcMakeContextCurrent(nullptr)");
|
||||
alcMakeContextCurrent(nullptr);
|
||||
}
|
||||
else
|
||||
{
|
||||
ALOGD("AVAudioSessionInterruptionTypeBegan, application == UIApplicationStateActive, pauseOnResignActive = true");
|
||||
pauseOnResignActive = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (reason == AVAudioSessionInterruptionTypeEnded) {
|
||||
if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
|
||||
if (reason == AVAudioSessionInterruptionTypeEnded)
|
||||
{
|
||||
isAudioSessionInterrupted = false;
|
||||
|
||||
if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive)
|
||||
{
|
||||
ALOGD("AVAudioSessionInterruptionTypeEnded, application == UIApplicationStateActive, alcMakeContextCurrent(s_ALContext)");
|
||||
NSError *error = nil;
|
||||
[[AVAudioSession sharedInstance] setActive:YES error:&error];
|
||||
alcMakeContextCurrent(s_ALContext);
|
||||
} else {
|
||||
if (Director::getInstance()->isPaused())
|
||||
{
|
||||
ALOGD("AVAudioSessionInterruptionTypeEnded, director was paused, try to resume it.");
|
||||
Director::getInstance()->resume();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ALOGD("AVAudioSessionInterruptionTypeEnded, application != UIApplicationStateActive, resumeOnBecomingActive = true");
|
||||
resumeOnBecomingActive = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ([notification.name isEqualToString:UIApplicationDidBecomeActiveNotification] && resumeOnBecomingActive) {
|
||||
resumeOnBecomingActive = false;
|
||||
NSError *error = nil;
|
||||
BOOL success = [[AVAudioSession sharedInstance]
|
||||
setCategory: AVAudioSessionCategoryAmbient
|
||||
error: &error];
|
||||
if (!success) {
|
||||
ALOGE("Fail to set audio session.");
|
||||
return;
|
||||
else if ([notification.name isEqualToString:UIApplicationWillResignActiveNotification])
|
||||
{
|
||||
ALOGD("UIApplicationWillResignActiveNotification");
|
||||
if (pauseOnResignActive)
|
||||
{
|
||||
pauseOnResignActive = false;
|
||||
ALOGD("UIApplicationWillResignActiveNotification, alcMakeContextCurrent(nullptr)");
|
||||
alcMakeContextCurrent(nullptr);
|
||||
}
|
||||
}
|
||||
else if ([notification.name isEqualToString:UIApplicationDidBecomeActiveNotification])
|
||||
{
|
||||
ALOGD("UIApplicationDidBecomeActiveNotification");
|
||||
if (resumeOnBecomingActive)
|
||||
{
|
||||
resumeOnBecomingActive = false;
|
||||
ALOGD("UIApplicationDidBecomeActiveNotification, alcMakeContextCurrent(s_ALContext)");
|
||||
NSError *error = nil;
|
||||
BOOL success = [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: &error];
|
||||
if (!success) {
|
||||
ALOGE("Fail to set audio session.");
|
||||
return;
|
||||
}
|
||||
[[AVAudioSession sharedInstance] setActive:YES error:&error];
|
||||
alcMakeContextCurrent(s_ALContext);
|
||||
}
|
||||
else if (isAudioSessionInterrupted)
|
||||
{
|
||||
ALOGD("Audio session is still interrupted, pause director!");
|
||||
Director::getInstance()->pause();
|
||||
}
|
||||
[[AVAudioSession sharedInstance] setActive:YES error:&error];
|
||||
alcMakeContextCurrent(s_ALContext);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,6 +180,7 @@ void AudioEngineInterruptionListenerCallback(void* user_data, UInt32 interruptio
|
||||
{
|
||||
[[NSNotificationCenter defaultCenter] removeObserver:self name:AVAudioSessionInterruptionNotification object:nil];
|
||||
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
|
||||
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
|
||||
|
||||
[super dealloc];
|
||||
}
|
||||
@@ -144,12 +192,18 @@ static id s_AudioEngineSessionHandler = nullptr;
|
||||
AudioEngineImpl::AudioEngineImpl()
|
||||
: _lazyInitLoop(true)
|
||||
, _currentAudioID(0)
|
||||
, _scheduler(nullptr)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
AudioEngineImpl::~AudioEngineImpl()
|
||||
{
|
||||
if (_scheduler != nullptr)
|
||||
{
|
||||
_scheduler->unschedule(CC_SCHEDULE_SELECTOR(AudioEngineImpl::update), this);
|
||||
}
|
||||
|
||||
if (s_ALContext) {
|
||||
alDeleteSources(MAX_AUDIOINSTANCES, _alSources);
|
||||
|
||||
@@ -540,37 +594,44 @@ void AudioEngineImpl::update(float dt)
|
||||
ALint sourceState;
|
||||
int audioID;
|
||||
AudioPlayer* player;
|
||||
ALuint alSource;
|
||||
|
||||
// ALOGV("AudioPlayer count: %d", (int)_audioPlayers.size());
|
||||
|
||||
for (auto it = _audioPlayers.begin(); it != _audioPlayers.end(); ) {
|
||||
audioID = it->first;
|
||||
player = it->second;
|
||||
alGetSourcei(player->_alSource, AL_SOURCE_STATE, &sourceState);
|
||||
alSource = player->_alSource;
|
||||
alGetSourcei(alSource, AL_SOURCE_STATE, &sourceState);
|
||||
|
||||
if (player->_removeByAudioEngine)
|
||||
{
|
||||
_alSourceUsed[player->_alSource] = false;
|
||||
|
||||
AudioEngine::remove(audioID);
|
||||
_threadMutex.lock();
|
||||
it = _audioPlayers.erase(it);
|
||||
_threadMutex.unlock();
|
||||
delete player;
|
||||
_alSourceUsed[alSource] = false;
|
||||
}
|
||||
else if (player->_ready && sourceState == AL_STOPPED) {
|
||||
|
||||
_alSourceUsed[player->_alSource] = false;
|
||||
std::string filePath;
|
||||
if (player->_finishCallbak) {
|
||||
auto& audioInfo = AudioEngine::_audioIDInfoMap[audioID];
|
||||
player->_finishCallbak(audioID, *audioInfo.filePath); //FIXME: callback will delay 50ms
|
||||
filePath = *audioInfo.filePath;
|
||||
}
|
||||
|
||||
AudioEngine::remove(audioID);
|
||||
delete player;
|
||||
_threadMutex.lock();
|
||||
it = _audioPlayers.erase(it);
|
||||
_threadMutex.unlock();
|
||||
|
||||
if (player->_finishCallbak) {
|
||||
player->_finishCallbak(audioID, filePath); //FIXME: callback will delay 50ms
|
||||
}
|
||||
|
||||
delete player;
|
||||
_alSourceUsed[alSource] = false;
|
||||
}
|
||||
else{
|
||||
++it;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2014-2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2014-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2014-2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2014-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -128,7 +128,7 @@ void AudioPlayer::destroy()
|
||||
ALOGVV("Before alSourceStop");
|
||||
alSourceStop(_alSource); CHECK_AL_ERROR_DEBUG();
|
||||
ALOGVV("Before alSourcei");
|
||||
alSourcei(_alSource, AL_BUFFER, NULL); CHECK_AL_ERROR_DEBUG();
|
||||
alSourcei(_alSource, AL_BUFFER, 0); CHECK_AL_ERROR_DEBUG();
|
||||
|
||||
_removeByAudioEngine = true;
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2014-2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2014-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -22,19 +22,17 @@
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
#include "platform/CCPlatformConfig.h"
|
||||
#pragma once
|
||||
|
||||
#ifndef __AUDIO_ENGINE_H_
|
||||
#define __AUDIO_ENGINE_H_
|
||||
#include "platform/CCPlatformConfig.h"
|
||||
#include "platform/CCPlatformMacros.h"
|
||||
#include "audio/include/Export.h"
|
||||
|
||||
#include <functional>
|
||||
#include <list>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "platform/CCPlatformMacros.h"
|
||||
#include "audio/include/Export.h"
|
||||
|
||||
#ifdef ERROR
|
||||
#undef ERROR
|
||||
#endif // ERROR
|
||||
@@ -45,7 +43,7 @@
|
||||
*/
|
||||
|
||||
NS_CC_BEGIN
|
||||
namespace experimental{
|
||||
namespace experimental {
|
||||
|
||||
/**
|
||||
* @class AudioProfile
|
||||
@@ -60,10 +58,10 @@ public:
|
||||
std::string name;
|
||||
//The maximum number of simultaneous audio instance.
|
||||
unsigned int maxInstances;
|
||||
|
||||
|
||||
/* Minimum delay in between sounds */
|
||||
double minDelay;
|
||||
|
||||
|
||||
/**
|
||||
* Default constructor
|
||||
*
|
||||
@@ -73,7 +71,7 @@ public:
|
||||
: maxInstances(0)
|
||||
, minDelay(0.0)
|
||||
{
|
||||
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
@@ -95,11 +93,11 @@ public:
|
||||
enum class AudioState
|
||||
{
|
||||
ERROR = -1,
|
||||
INITIALZING,
|
||||
INITIALIZING,
|
||||
PLAYING,
|
||||
PAUSED
|
||||
};
|
||||
|
||||
|
||||
static const int INVALID_AUDIO_ID;
|
||||
|
||||
static const float TIME_UNKNOWN;
|
||||
@@ -113,15 +111,15 @@ public:
|
||||
* @lua endToLua
|
||||
*/
|
||||
static void end();
|
||||
|
||||
/**
|
||||
|
||||
/**
|
||||
* Gets the default profile of audio instances.
|
||||
*
|
||||
* @return The default profile of audio instances.
|
||||
*/
|
||||
static AudioProfile* getDefaultProfile();
|
||||
|
||||
/**
|
||||
|
||||
/**
|
||||
* Play 2d sound.
|
||||
*
|
||||
* @param filePath The path of an audio file.
|
||||
@@ -133,8 +131,8 @@ public:
|
||||
* @see `AudioProfile`
|
||||
*/
|
||||
static int play2d(const std::string& filePath, bool loop = false, float volume = 1.0f, const AudioProfile *profile = nullptr);
|
||||
|
||||
/**
|
||||
|
||||
/**
|
||||
* Sets whether an audio instance loop or not.
|
||||
*
|
||||
* @param audioID An audioID returned by the play2d function.
|
||||
@@ -142,7 +140,7 @@ public:
|
||||
*/
|
||||
static void setLoop(int audioID, bool loop);
|
||||
|
||||
/**
|
||||
/**
|
||||
* Checks whether an audio instance is loop.
|
||||
*
|
||||
* @param audioID An audioID returned by the play2d function.
|
||||
@@ -150,7 +148,7 @@ public:
|
||||
*/
|
||||
static bool isLoop(int audioID);
|
||||
|
||||
/**
|
||||
/**
|
||||
* Sets volume for an audio instance.
|
||||
*
|
||||
* @param audioID An audioID returned by the play2d function.
|
||||
@@ -158,7 +156,7 @@ public:
|
||||
*/
|
||||
static void setVolume(int audioID, float volume);
|
||||
|
||||
/**
|
||||
/**
|
||||
* Gets the volume value of an audio instance.
|
||||
*
|
||||
* @param audioID An audioID returned by the play2d function.
|
||||
@@ -166,7 +164,7 @@ public:
|
||||
*/
|
||||
static float getVolume(int audioID);
|
||||
|
||||
/**
|
||||
/**
|
||||
* Pause an audio instance.
|
||||
*
|
||||
* @param audioID An audioID returned by the play2d function.
|
||||
@@ -176,7 +174,7 @@ public:
|
||||
/** Pause all playing audio instances. */
|
||||
static void pauseAll();
|
||||
|
||||
/**
|
||||
/**
|
||||
* Resume an audio instance.
|
||||
*
|
||||
* @param audioID An audioID returned by the play2d function.
|
||||
@@ -186,7 +184,7 @@ public:
|
||||
/** Resume all suspended audio instances. */
|
||||
static void resumeAll();
|
||||
|
||||
/**
|
||||
/**
|
||||
* Stop an audio instance.
|
||||
*
|
||||
* @param audioID An audioID returned by the play2d function.
|
||||
@@ -201,11 +199,11 @@ public:
|
||||
*
|
||||
* @param audioID An audioID returned by the play2d function.
|
||||
* @param sec The offset in seconds from the start to seek to.
|
||||
* @return
|
||||
* @return
|
||||
*/
|
||||
static bool setCurrentTime(int audioID, float sec);
|
||||
|
||||
/**
|
||||
/**
|
||||
* Gets the current playback position of an audio instance.
|
||||
*
|
||||
* @param audioID An audioID returned by the play2d function.
|
||||
@@ -213,7 +211,7 @@ public:
|
||||
*/
|
||||
static float getCurrentTime(int audioID);
|
||||
|
||||
/**
|
||||
/**
|
||||
* Gets the duration of an audio instance.
|
||||
*
|
||||
* @param audioID An audioID returned by the play2d function.
|
||||
@@ -221,7 +219,7 @@ public:
|
||||
*/
|
||||
static float getDuration(int audioID);
|
||||
|
||||
/**
|
||||
/**
|
||||
* Returns the state of an audio instance.
|
||||
*
|
||||
* @param audioID An audioID returned by the play2d function.
|
||||
@@ -229,27 +227,27 @@ public:
|
||||
*/
|
||||
static AudioState getState(int audioID);
|
||||
|
||||
/**
|
||||
/**
|
||||
* Register a callback to be invoked when an audio instance has completed playing.
|
||||
*
|
||||
* @param audioID An audioID returned by the play2d function.
|
||||
* @param callback
|
||||
*/
|
||||
static void setFinishCallback(int audioID, const std::function<void(int,const std::string&)>& callback);
|
||||
|
||||
|
||||
/**
|
||||
* Gets the maximum number of simultaneous audio instance of AudioEngine.
|
||||
*/
|
||||
static int getMaxAudioInstance() {return _maxInstances;}
|
||||
|
||||
|
||||
/**
|
||||
* Sets the maximum number of simultaneous audio instance for AudioEngine.
|
||||
*
|
||||
* @param maxInstances The maximum number of simultaneous audio instance.
|
||||
*/
|
||||
static bool setMaxAudioInstance(int maxInstances);
|
||||
|
||||
/**
|
||||
|
||||
/**
|
||||
* Uncache the audio data from internal buffer.
|
||||
* AudioEngine cache audio data on ios,mac, and win32 platform.
|
||||
*
|
||||
@@ -257,15 +255,15 @@ public:
|
||||
* @param filePath Audio file path.
|
||||
*/
|
||||
static void uncache(const std::string& filePath);
|
||||
|
||||
/**
|
||||
|
||||
/**
|
||||
* Uncache all audio data from internal buffer.
|
||||
*
|
||||
* @warning All audio will be stopped first.
|
||||
*/
|
||||
static void uncacheAll();
|
||||
|
||||
/**
|
||||
|
||||
/**
|
||||
* Gets the audio profile by id of audio instance.
|
||||
*
|
||||
* @param audioID An audioID returned by the play2d function.
|
||||
@@ -273,7 +271,7 @@ public:
|
||||
*/
|
||||
static AudioProfile* getProfile(int audioID);
|
||||
|
||||
/**
|
||||
/**
|
||||
* Gets an audio profile by name.
|
||||
*
|
||||
* @param profileName A name of audio profile.
|
||||
@@ -297,7 +295,7 @@ public:
|
||||
protected:
|
||||
static void addTask(const std::function<void()>& task);
|
||||
static void remove(int audioID);
|
||||
|
||||
|
||||
struct ProfileHelper
|
||||
{
|
||||
AudioProfile profile;
|
||||
@@ -312,51 +310,49 @@ protected:
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
struct AudioInfo
|
||||
{
|
||||
const std::string* filePath;
|
||||
ProfileHelper* profileHelper;
|
||||
|
||||
|
||||
float volume;
|
||||
bool loop;
|
||||
float duration;
|
||||
AudioState state;
|
||||
|
||||
AudioInfo()
|
||||
: profileHelper(nullptr)
|
||||
, duration(TIME_UNKNOWN)
|
||||
, state(AudioState::INITIALZING)
|
||||
{
|
||||
|
||||
}
|
||||
AudioInfo();
|
||||
~AudioInfo();
|
||||
private:
|
||||
AudioInfo(const AudioInfo& info);
|
||||
AudioInfo(AudioInfo&& info);
|
||||
AudioInfo& operator=(const AudioInfo& info);
|
||||
AudioInfo& operator=(AudioInfo&& info);
|
||||
};
|
||||
|
||||
//audioID,audioAttribute
|
||||
static std::unordered_map<int, AudioInfo> _audioIDInfoMap;
|
||||
|
||||
|
||||
//audio file path,audio IDs
|
||||
static std::unordered_map<std::string,std::list<int>> _audioPathIDMap;
|
||||
|
||||
|
||||
//profileName,ProfileHelper
|
||||
static std::unordered_map<std::string, ProfileHelper> _audioPathProfileHelperMap;
|
||||
|
||||
|
||||
static unsigned int _maxInstances;
|
||||
|
||||
|
||||
static ProfileHelper* _defaultProfileHelper;
|
||||
|
||||
|
||||
static AudioEngineImpl* _audioEngineImpl;
|
||||
|
||||
class AudioEngineThreadPool;
|
||||
static AudioEngineThreadPool* s_threadPool;
|
||||
|
||||
|
||||
friend class AudioEngineImpl;
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace experimental {
|
||||
NS_CC_END
|
||||
|
||||
// end group
|
||||
/// @}
|
||||
|
||||
#endif // __AUDIO_ENGINE_H_
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2010-2012 cocos2d-x.org
|
||||
Copyright (c) 2013-2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2013-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -33,7 +33,7 @@ THE SOFTWARE.
|
||||
#define EXPORT_DLL
|
||||
#else
|
||||
#if defined(_EXPORT_DLL_)
|
||||
#define EXPORT_DLL __declspec(dllexport)
|
||||
#define EXPORT_DLL __declspec(dllexport)
|
||||
#else /* use a DLL library */
|
||||
#define EXPORT_DLL __declspec(dllimport)
|
||||
#endif
|
||||
@@ -46,6 +46,6 @@ THE SOFTWARE.
|
||||
#else
|
||||
#define EXPORT_DLL
|
||||
#endif
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#endif // end of __EXPORT_COMMON__
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2010 Steve Oldmeadow
|
||||
Copyright (c) 2010-2012 cocos2d-x.org
|
||||
Copyright (c) 2013-2016 Chukong Technologies Inc.
|
||||
Copyright (c) 2013-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -62,6 +62,13 @@ public:
|
||||
*/
|
||||
static SimpleAudioEngine* getInstance();
|
||||
|
||||
/**
|
||||
* @deprecated Use `getInstance` instead.
|
||||
* @js NA
|
||||
* @lua NA
|
||||
*/
|
||||
CC_DEPRECATED_ATTRIBUTE static SimpleAudioEngine* sharedEngine() { return SimpleAudioEngine::getInstance(); }
|
||||
|
||||
/**
|
||||
* Release the shared Engine object.
|
||||
*
|
||||
@@ -78,10 +85,10 @@ public:
|
||||
* @lua preloadMusic
|
||||
*/
|
||||
virtual void preloadBackgroundMusic(const char* filePath);
|
||||
|
||||
|
||||
/**
|
||||
* Play background music.
|
||||
*
|
||||
*
|
||||
* @param filePath The path of the background music file,or the FileName of T_SoundResInfo.
|
||||
* @param loop Whether the background music loop or not.
|
||||
* @js playMusic
|
||||
@@ -137,7 +144,7 @@ public:
|
||||
*/
|
||||
virtual bool isBackgroundMusicPlaying();
|
||||
|
||||
//
|
||||
//
|
||||
// properties
|
||||
//
|
||||
|
||||
@@ -169,7 +176,7 @@ public:
|
||||
*/
|
||||
virtual void setEffectsVolume(float volume);
|
||||
|
||||
//
|
||||
//
|
||||
// for sound effects
|
||||
|
||||
/**
|
||||
@@ -181,7 +188,7 @@ public:
|
||||
* @param pan Stereo effect, in the range of [-1..1] where -1 enables only left channel.
|
||||
* @param gain Volume, in the range of [0..1]. The normal value is 1.
|
||||
* @return The sound id.
|
||||
*
|
||||
*
|
||||
* @note Full support is under development, now there are limitations:
|
||||
* - no pitch effect on Samsung Galaxy S2 with OpenSL backend enabled;
|
||||
* - no pitch/pan/gain on win32.
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
/*
|
||||
Copyright (c) 2010 Steve Oldmeadow
|
||||
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
@@ -18,7 +18,7 @@
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
|
||||
$Id$
|
||||
*/
|
||||
|
||||
@@ -54,14 +54,14 @@ typedef enum {
|
||||
/** Notifications */
|
||||
extern NSString * const kCDN_AudioManagerInitialised;
|
||||
|
||||
@interface CDAsynchInitialiser : NSOperation {}
|
||||
@interface CDAsynchInitialiser : NSOperation {}
|
||||
@end
|
||||
|
||||
/** CDAudioManager supports two long audio source channels called left and right*/
|
||||
typedef enum {
|
||||
kASC_Left = 0,
|
||||
kASC_Right = 1
|
||||
} tAudioSourceChannel;
|
||||
} tAudioSourceChannel;
|
||||
|
||||
typedef enum {
|
||||
kLAS_Init,
|
||||
@@ -94,19 +94,19 @@ typedef enum {
|
||||
NSString *audioSourceFilePath;
|
||||
NSInteger numberOfLoops;
|
||||
float volume;
|
||||
id<CDLongAudioSourceDelegate> delegate;
|
||||
id<CDLongAudioSourceDelegate> delegate;
|
||||
BOOL mute;
|
||||
BOOL enabled_;
|
||||
BOOL backgroundMusic;
|
||||
// whether background music is paused
|
||||
BOOL paused;
|
||||
BOOL stopped;
|
||||
@public
|
||||
@public
|
||||
BOOL systemPaused;//Used for auto resign handling
|
||||
NSTimeInterval systemPauseLocation;//Used for auto resign handling
|
||||
@protected
|
||||
tLongAudioSourceState state;
|
||||
}
|
||||
}
|
||||
@property (readonly) AVAudioPlayer *audioSourcePlayer;
|
||||
@property (readonly) NSString *audioSourceFilePath;
|
||||
@property (readwrite, nonatomic) NSInteger numberOfLoops;
|
||||
@@ -120,7 +120,7 @@ typedef enum {
|
||||
-(void) load:(NSString*) filePath;
|
||||
/** Plays the audio source */
|
||||
-(void) play;
|
||||
/** Stops playing the audio soruce */
|
||||
/** Stops playing the audio source */
|
||||
-(void) stop;
|
||||
/** Pauses the audio source */
|
||||
-(void) pause;
|
||||
@@ -133,15 +133,15 @@ typedef enum {
|
||||
|
||||
@end
|
||||
|
||||
/**
|
||||
/**
|
||||
CDAudioManager manages audio requirements for a game. It provides access to a CDSoundEngine object
|
||||
for playing sound effects. It provides access to two CDLongAudioSource object (left and right channel)
|
||||
for playing long duration audio such as background music and narration tracks. Additionally it manages
|
||||
the audio session to take care of things like audio session interruption and interacting with the audio
|
||||
of other apps that are running on the device.
|
||||
|
||||
|
||||
Requirements:
|
||||
- Firmware: OS 2.2 or greater
|
||||
- Firmware: OS 2.2 or greater
|
||||
- Files: CDAudioManager.*, CocosDenshion.*
|
||||
- Frameworks: OpenAL, AudioToolbox, AVFoundation
|
||||
@since v0.8
|
||||
@@ -167,7 +167,7 @@ typedef enum {
|
||||
BOOL _interrupted;
|
||||
BOOL _audioSessionActive;
|
||||
BOOL enabled_;
|
||||
|
||||
|
||||
//For handling resign/become active
|
||||
BOOL _isObservingAppEvents;
|
||||
tAudioManagerResignBehavior _resignBehavior;
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
/*
|
||||
Copyright (c) 2010 Steve Oldmeadow
|
||||
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
@@ -18,7 +18,7 @@
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
|
||||
$Id$
|
||||
*/
|
||||
|
||||
@@ -27,13 +27,13 @@
|
||||
|
||||
NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised";
|
||||
|
||||
//NSOperation object used to asynchronously initialise
|
||||
//NSOperation object used to asynchronously initialise
|
||||
@implementation CDAsynchInitialiser
|
||||
|
||||
-(void) main {
|
||||
[super main];
|
||||
[CDAudioManager sharedManager];
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@@ -58,10 +58,10 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised";
|
||||
[audioSourcePlayer release];
|
||||
[audioSourceFilePath release];
|
||||
[super dealloc];
|
||||
}
|
||||
}
|
||||
|
||||
-(void) load:(NSString*) filePath {
|
||||
//We have alread loaded a file previously, check if we are being asked to load the same file
|
||||
//We have already loaded a file previously, check if we are being asked to load the same file
|
||||
if (state == kLAS_Init || ![filePath isEqualToString:audioSourceFilePath]) {
|
||||
CDLOGINFO(@"Denshion::CDLongAudioSource - Loading new audio source %@",filePath);
|
||||
//New file
|
||||
@@ -79,10 +79,10 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised";
|
||||
if (delegate && [delegate respondsToSelector:@selector(cdAudioSourceFileDidChange:)]) {
|
||||
//Tell our delegate the file has changed
|
||||
[delegate cdAudioSourceFileDidChange:self];
|
||||
}
|
||||
}
|
||||
} else {
|
||||
CDLOG(@"Denshion::CDLongAudioSource - Error initialising audio player: %@",error);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
//Same file - just return it to a consistent state
|
||||
[self pause];
|
||||
@@ -91,7 +91,7 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised";
|
||||
audioSourcePlayer.volume = volume;
|
||||
audioSourcePlayer.numberOfLoops = numberOfLoops;
|
||||
state = kLAS_Loaded;
|
||||
}
|
||||
}
|
||||
|
||||
-(void) play {
|
||||
if (enabled_) {
|
||||
@@ -101,19 +101,19 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised";
|
||||
[audioSourcePlayer play];
|
||||
} else {
|
||||
CDLOGINFO(@"Denshion::CDLongAudioSource long audio source didn't play because it is disabled");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(void) stop {
|
||||
paused = NO;
|
||||
stopped = YES;
|
||||
[audioSourcePlayer stop];
|
||||
}
|
||||
}
|
||||
|
||||
-(void) pause {
|
||||
paused = YES;
|
||||
[audioSourcePlayer pause];
|
||||
}
|
||||
}
|
||||
|
||||
-(void) rewind {
|
||||
paused = NO;
|
||||
@@ -142,10 +142,10 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised";
|
||||
volume = newVolume;
|
||||
if (state != kLAS_Init && !mute) {
|
||||
audioSourcePlayer.volume = newVolume;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(float) volume
|
||||
-(float) volume
|
||||
{
|
||||
return volume;
|
||||
}
|
||||
@@ -154,9 +154,9 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised";
|
||||
-(BOOL) mute
|
||||
{
|
||||
return mute;
|
||||
}
|
||||
}
|
||||
|
||||
-(void) setMute:(BOOL) muteValue
|
||||
-(void) setMute:(BOOL) muteValue
|
||||
{
|
||||
if (mute != muteValue) {
|
||||
if (mute) {
|
||||
@@ -166,15 +166,15 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised";
|
||||
audioSourcePlayer.volume = 0.0f;
|
||||
}
|
||||
mute = muteValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(BOOL) enabled
|
||||
-(BOOL) enabled
|
||||
{
|
||||
return enabled_;
|
||||
}
|
||||
}
|
||||
|
||||
-(void) setEnabled:(BOOL)enabledValue
|
||||
-(void) setEnabled:(BOOL)enabledValue
|
||||
{
|
||||
if (enabledValue != enabled_) {
|
||||
enabled_ = enabledValue;
|
||||
@@ -182,25 +182,25 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised";
|
||||
//"Stop" the sounds
|
||||
[self pause];
|
||||
[self rewind];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(NSInteger) numberOfLoops {
|
||||
return numberOfLoops;
|
||||
}
|
||||
}
|
||||
|
||||
-(void) setNumberOfLoops:(NSInteger) loopCount
|
||||
{
|
||||
audioSourcePlayer.numberOfLoops = loopCount;
|
||||
numberOfLoops = loopCount;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
|
||||
CDLOGINFO(@"Denshion::CDLongAudioSource - audio player finished");
|
||||
#if TARGET_IPHONE_SIMULATOR
|
||||
#if TARGET_IPHONE_SIMULATOR
|
||||
CDLOGINFO(@"Denshion::CDLongAudioSource - workaround for OpenAL clobbered audio issue");
|
||||
//This is a workaround for an issue in all simulators (tested to 3.1.2). Problem is
|
||||
//This is a workaround for an issue in all simulators (tested to 3.1.2). Problem is
|
||||
//that OpenAL audio playback is clobbered when an AVAudioPlayer stops. Workaround
|
||||
//is to keep the player playing on an endless loop with 0 volume and then when
|
||||
//it is played again reset the volume and set loop count appropriately.
|
||||
@@ -208,11 +208,11 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised";
|
||||
player.numberOfLoops = -1;
|
||||
player.volume = 0;
|
||||
[player play];
|
||||
#endif
|
||||
#endif
|
||||
if (delegate && [delegate respondsToSelector:@selector(cdAudioSourceDidFinishPlaying:)]) {
|
||||
[delegate cdAudioSourceDidFinishPlaying:self];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(void)audioPlayerBeginInterruption:(AVAudioPlayer *)player {
|
||||
CDLOGINFO(@"Denshion::CDLongAudioSource - audio player interrupted");
|
||||
@@ -221,16 +221,16 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised";
|
||||
-(void)audioPlayerEndInterruption:(AVAudioPlayer *)player {
|
||||
CDLOGINFO(@"Denshion::CDLongAudioSource - audio player resumed");
|
||||
if (self.backgroundMusic) {
|
||||
//Check if background music can play as rules may have changed during
|
||||
//Check if background music can play as rules may have changed during
|
||||
//the interruption. This is to address a specific issue in 4.x when
|
||||
//fast task switching
|
||||
if([CDAudioManager sharedManager].willPlayBackgroundMusic) {
|
||||
[player play];
|
||||
}
|
||||
}
|
||||
} else {
|
||||
[player play];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@@ -255,26 +255,26 @@ static BOOL configured = FALSE;
|
||||
NSError *activationError = nil;
|
||||
if ([[AVAudioSession sharedInstance] setActive:active error:&activationError]) {
|
||||
_audioSessionActive = active;
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Audio session set active %i succeeded", active);
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Audio session set active %i succeeded", active);
|
||||
return YES;
|
||||
} else {
|
||||
//Failed
|
||||
CDLOG(@"Denshion::CDAudioManager - Audio session set active %i failed with error %@", active, activationError);
|
||||
CDLOG(@"Denshion::CDAudioManager - Audio session set active %i failed with error %@", active, activationError);
|
||||
return NO;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(BOOL) audioSessionSetCategory:(NSString*) category {
|
||||
NSError *categoryError = nil;
|
||||
if ([[AVAudioSession sharedInstance] setCategory:category error:&categoryError]) {
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Audio session set category %@ succeeded", category);
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Audio session set category %@ succeeded", category);
|
||||
return YES;
|
||||
} else {
|
||||
//Failed
|
||||
CDLOG(@"Denshion::CDAudioManager - Audio session set category %@ failed with error %@", category, categoryError);
|
||||
CDLOG(@"Denshion::CDAudioManager - Audio session set category %@ failed with error %@", category, categoryError);
|
||||
return NO;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Init
|
||||
+ (CDAudioManager *) sharedManager
|
||||
@@ -288,14 +288,14 @@ static BOOL configured = FALSE;
|
||||
sharedManager = [[CDAudioManager alloc] init:configuredMode];
|
||||
_sharedManagerState = kAMStateInitialised;//This is only really relevant when using asynchronous initialisation
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:kCDN_AudioManagerInitialised object:nil];
|
||||
}
|
||||
}
|
||||
}
|
||||
return sharedManager;
|
||||
}
|
||||
|
||||
+ (tAudioManagerState) sharedManagerState {
|
||||
return _sharedManagerState;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Call this to set up audio manager asynchronously. Initialisation is finished when sharedManagerState == kAMStateInitialised
|
||||
@@ -308,9 +308,9 @@ static BOOL configured = FALSE;
|
||||
CDAsynchInitialiser *initOp = [[[CDAsynchInitialiser alloc] init] autorelease];
|
||||
NSOperationQueue *opQ = [[[NSOperationQueue alloc] init] autorelease];
|
||||
[opQ addOperation:initOp];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+ (id) alloc
|
||||
{
|
||||
@@ -327,7 +327,7 @@ static BOOL configured = FALSE;
|
||||
+ (void) configure: (tAudioManagerMode) mode {
|
||||
configuredMode = mode;
|
||||
configured = TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
-(BOOL) isOtherAudioPlaying
|
||||
{
|
||||
@@ -346,7 +346,7 @@ static BOOL configured = FALSE;
|
||||
|
||||
_mode = mode;
|
||||
switch (_mode) {
|
||||
|
||||
|
||||
case kAMM_FxOnly:
|
||||
//Share audio with other app
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Audio will be shared");
|
||||
@@ -354,7 +354,7 @@ static BOOL configured = FALSE;
|
||||
_audioSessionCategory = AVAudioSessionCategoryAmbient;
|
||||
willPlayBackgroundMusic = NO;
|
||||
break;
|
||||
|
||||
|
||||
case kAMM_FxPlusMusic:
|
||||
//Use audio exclusively - if other audio is playing it will be stopped
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Audio will be exclusive");
|
||||
@@ -362,7 +362,7 @@ static BOOL configured = FALSE;
|
||||
_audioSessionCategory = AVAudioSessionCategorySoloAmbient;
|
||||
willPlayBackgroundMusic = YES;
|
||||
break;
|
||||
|
||||
|
||||
case kAMM_MediaPlayback:
|
||||
//Use audio exclusively, ignore mute switch and sleep
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Media playback mode, audio will be exclusive");
|
||||
@@ -370,7 +370,7 @@ static BOOL configured = FALSE;
|
||||
_audioSessionCategory = AVAudioSessionCategoryPlayback;
|
||||
willPlayBackgroundMusic = YES;
|
||||
break;
|
||||
|
||||
|
||||
case kAMM_PlayAndRecord:
|
||||
//Use audio exclusively, ignore mute switch and sleep, has inputs and outputs
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Play and record mode, audio will be exclusive");
|
||||
@@ -378,7 +378,7 @@ static BOOL configured = FALSE;
|
||||
_audioSessionCategory = AVAudioSessionCategoryPlayAndRecord;
|
||||
willPlayBackgroundMusic = YES;
|
||||
break;
|
||||
|
||||
|
||||
default:
|
||||
//kAudioManagerFxPlusMusicIfNoOtherAudio
|
||||
if ([self isOtherAudioPlaying]) {
|
||||
@@ -391,18 +391,18 @@ static BOOL configured = FALSE;
|
||||
//_audioSessionCategory = kAudioSessionCategory_SoloAmbientSound;
|
||||
_audioSessionCategory = AVAudioSessionCategorySoloAmbient;
|
||||
willPlayBackgroundMusic = YES;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
[self audioSessionSetCategory:_audioSessionCategory];
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is used to work around various bugs introduced in 4.x OS versions. In some circumstances the
|
||||
* audio session is interrupted but never resumed, this results in the loss of OpenAL audio when following
|
||||
* This method is used to work around various bugs introduced in 4.x OS versions. In some circumstances the
|
||||
* audio session is interrupted but never resumed, this results in the loss of OpenAL audio when following
|
||||
* standard practices. If we detect this situation then we will attempt to resume the audio session ourselves.
|
||||
* Known triggers: lock the device then unlock it (iOS 4.2 gm), playback a song using MPMediaPlayer (iOS 4.0)
|
||||
*/
|
||||
@@ -410,8 +410,8 @@ static BOOL configured = FALSE;
|
||||
if (_interrupted && alcGetCurrentContext() == NULL) {
|
||||
CDLOG(@"Denshion::CDAudioManager - bad OpenAL context detected, attempting to resume audio session");
|
||||
[self audioSessionResumed];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (id) init: (tAudioManagerMode) mode {
|
||||
if ((self = [super init])) {
|
||||
@@ -433,27 +433,27 @@ static BOOL configured = FALSE;
|
||||
_audioSessionActive = NO;
|
||||
[self setMode:mode];
|
||||
soundEngine = [[CDSoundEngine alloc] init];
|
||||
|
||||
|
||||
//Set up audioSource channels
|
||||
audioSourceChannels = [[NSMutableArray alloc] init];
|
||||
CDLongAudioSource *leftChannel = [[CDLongAudioSource alloc] init];
|
||||
leftChannel.backgroundMusic = YES;
|
||||
CDLongAudioSource *rightChannel = [[CDLongAudioSource alloc] init];
|
||||
rightChannel.backgroundMusic = NO;
|
||||
[audioSourceChannels insertObject:leftChannel atIndex:kASC_Left];
|
||||
[audioSourceChannels insertObject:leftChannel atIndex:kASC_Left];
|
||||
[audioSourceChannels insertObject:rightChannel atIndex:kASC_Right];
|
||||
[leftChannel release];
|
||||
[rightChannel release];
|
||||
//Used to support legacy APIs
|
||||
backgroundMusic = [self audioSourceForChannel:BACKGROUND_MUSIC_CHANNEL];
|
||||
backgroundMusic.delegate = self;
|
||||
|
||||
|
||||
//Add handler for bad al context messages, these are posted by the sound engine.
|
||||
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(badAlContextHandler) name:kCDN_BadAlContext object:nil];
|
||||
|
||||
}
|
||||
return self;
|
||||
}
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
-(void) dealloc {
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - deallocating");
|
||||
@@ -463,13 +463,13 @@ static BOOL configured = FALSE;
|
||||
[self audioSessionSetActive:NO];
|
||||
[audioSourceChannels release];
|
||||
[super dealloc];
|
||||
}
|
||||
}
|
||||
|
||||
/** Retrieves the audio source for the specified channel */
|
||||
-(CDLongAudioSource*) audioSourceForChannel:(tAudioSourceChannel) channel
|
||||
-(CDLongAudioSource*) audioSourceForChannel:(tAudioSourceChannel) channel
|
||||
{
|
||||
return (CDLongAudioSource*)[audioSourceChannels objectAtIndex:channel];
|
||||
}
|
||||
}
|
||||
|
||||
/** Loads the data from the specified file path to the channel's audio source */
|
||||
-(CDLongAudioSource*) audioSourceLoad:(NSString*) filePath channel:(tAudioSourceChannel) channel
|
||||
@@ -479,14 +479,14 @@ static BOOL configured = FALSE;
|
||||
[audioSource load:filePath];
|
||||
}
|
||||
return audioSource;
|
||||
}
|
||||
}
|
||||
|
||||
-(BOOL) isBackgroundMusicPlaying {
|
||||
return [self.backgroundMusic isPlaying];
|
||||
}
|
||||
}
|
||||
|
||||
//NB: originally I tried using a route change listener and intended to store the current route,
|
||||
//however, on a 3gs running 3.1.2 no route change is generated when the user switches the
|
||||
//however, on a 3gs running 3.1.2 no route change is generated when the user switches the
|
||||
//ringer mute switch to off (i.e. enables sound) therefore polling is the only reliable way to
|
||||
//determine ringer switch state
|
||||
-(BOOL) isDeviceMuted {
|
||||
@@ -494,36 +494,36 @@ static BOOL configured = FALSE;
|
||||
#if TARGET_IPHONE_SIMULATOR || defined(CC_TARGET_OS_TVOS)
|
||||
//Calling audio route stuff on the simulator causes problems
|
||||
return NO;
|
||||
#else
|
||||
#else
|
||||
CFStringRef newAudioRoute;
|
||||
UInt32 propertySize = sizeof (CFStringRef);
|
||||
|
||||
|
||||
AudioSessionGetProperty (
|
||||
kAudioSessionProperty_AudioRoute,
|
||||
&propertySize,
|
||||
&newAudioRoute
|
||||
);
|
||||
|
||||
|
||||
if (newAudioRoute == NULL) {
|
||||
//Don't expect this to happen but playing safe otherwise a null in the CFStringCompare will cause a crash
|
||||
return YES;
|
||||
} else {
|
||||
} else {
|
||||
CFComparisonResult newDeviceIsMuted = CFStringCompare (
|
||||
newAudioRoute,
|
||||
(CFStringRef) @"",
|
||||
0
|
||||
);
|
||||
|
||||
|
||||
return (newDeviceIsMuted == kCFCompareEqualTo);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark Audio Interrupt Protocol
|
||||
|
||||
-(BOOL) mute {
|
||||
return _mute;
|
||||
}
|
||||
}
|
||||
|
||||
-(void) setMute:(BOOL) muteValue {
|
||||
if (muteValue != _mute) {
|
||||
@@ -531,13 +531,13 @@ static BOOL configured = FALSE;
|
||||
[soundEngine setMute:muteValue];
|
||||
for( CDLongAudioSource *audioSource in audioSourceChannels) {
|
||||
audioSource.mute = muteValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(BOOL) enabled {
|
||||
return enabled_;
|
||||
}
|
||||
}
|
||||
|
||||
-(void) setEnabled:(BOOL) enabledValue {
|
||||
if (enabledValue != enabled_) {
|
||||
@@ -545,20 +545,20 @@ static BOOL configured = FALSE;
|
||||
[soundEngine setEnabled:enabled_];
|
||||
for( CDLongAudioSource *audioSource in audioSourceChannels) {
|
||||
audioSource.enabled = enabled_;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(CDLongAudioSource*) backgroundMusic
|
||||
{
|
||||
return backgroundMusic;
|
||||
}
|
||||
}
|
||||
|
||||
//Load background music ready for playing
|
||||
-(void) preloadBackgroundMusic:(NSString*) filePath
|
||||
{
|
||||
[self.backgroundMusic load:filePath];
|
||||
}
|
||||
[self.backgroundMusic load:filePath];
|
||||
}
|
||||
|
||||
-(void) playBackgroundMusic:(NSString*) filePath loop:(BOOL) loop
|
||||
{
|
||||
@@ -586,7 +586,7 @@ static BOOL configured = FALSE;
|
||||
-(void) pauseBackgroundMusic
|
||||
{
|
||||
[self.backgroundMusic pause];
|
||||
}
|
||||
}
|
||||
|
||||
-(void) resumeBackgroundMusic
|
||||
{
|
||||
@@ -594,35 +594,35 @@ static BOOL configured = FALSE;
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - resume bgm aborted because audio is not exclusive or sound is muted");
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (![self.backgroundMusic paused]) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
[self.backgroundMusic resume];
|
||||
}
|
||||
}
|
||||
|
||||
-(void) rewindBackgroundMusic
|
||||
{
|
||||
[self.backgroundMusic rewind];
|
||||
}
|
||||
}
|
||||
|
||||
-(void) setBackgroundMusicCompletionListener:(id) listener selector:(SEL) selector {
|
||||
backgroundMusicCompletionListener = listener;
|
||||
backgroundMusicCompletionSelector = selector;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Call this method to have the audio manager automatically handle application resign and
|
||||
* become active. Pass a tAudioManagerResignBehavior to indicate the desired behavior
|
||||
* for resigning and becoming active again.
|
||||
*
|
||||
* If autohandle is YES then the applicationWillResignActive and applicationDidBecomActive
|
||||
* If autohandle is YES then the applicationWillResignActive and applicationDidBecomActive
|
||||
* methods are automatically called, otherwise you must call them yourself at the appropriate time.
|
||||
*
|
||||
* Based on idea of Dominique Bongard
|
||||
*/
|
||||
-(void) setResignBehavior:(tAudioManagerResignBehavior) resignBehavior autoHandle:(BOOL) autoHandle {
|
||||
-(void) setResignBehavior:(tAudioManagerResignBehavior) resignBehavior autoHandle:(BOOL) autoHandle {
|
||||
|
||||
if (!_isObservingAppEvents && autoHandle) {
|
||||
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:@"UIApplicationWillResignActiveNotification" object:nil];
|
||||
@@ -631,18 +631,18 @@ static BOOL configured = FALSE;
|
||||
_isObservingAppEvents = TRUE;
|
||||
}
|
||||
_resignBehavior = resignBehavior;
|
||||
}
|
||||
}
|
||||
|
||||
- (void) applicationWillResignActive {
|
||||
_resigned = YES;
|
||||
|
||||
//Set the audio sesssion to one that allows sharing so that other audio won't be clobbered on resume
|
||||
|
||||
//Set the audio session to one that allows sharing so that other audio won't be clobbered on resume
|
||||
[self audioSessionSetCategory:AVAudioSessionCategoryAmbient];
|
||||
|
||||
|
||||
switch (_resignBehavior) {
|
||||
|
||||
|
||||
case kAMRBStopPlay:
|
||||
|
||||
|
||||
for( CDLongAudioSource *audioSource in audioSourceChannels) {
|
||||
if (!audioSource->systemPaused) {
|
||||
if (audioSource.isPlaying) {
|
||||
@@ -658,18 +658,18 @@ static BOOL configured = FALSE;
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
|
||||
case kAMRBStop:
|
||||
//Stop music regardless of whether it is playing or not because if it was paused
|
||||
//then the OS would resume it
|
||||
for( CDLongAudioSource *audioSource in audioSourceChannels) {
|
||||
[audioSource stop];
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
default:
|
||||
break;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - handled resign active");
|
||||
}
|
||||
|
||||
@@ -677,18 +677,18 @@ static BOOL configured = FALSE;
|
||||
- (void) applicationWillResignActive:(NSNotification *) notification
|
||||
{
|
||||
[self applicationWillResignActive];
|
||||
}
|
||||
}
|
||||
|
||||
- (void) applicationDidBecomeActive {
|
||||
|
||||
|
||||
if (_resigned) {
|
||||
_resigned = NO;
|
||||
//Reset the mode incase something changed with audio while we were inactive
|
||||
[self setMode:_mode];
|
||||
switch (_resignBehavior) {
|
||||
|
||||
|
||||
case kAMRBStopPlay:
|
||||
|
||||
|
||||
//Music had been stopped but stop maintains current time
|
||||
//so playing again will continue from where music was before resign active.
|
||||
//We check if music can be played because while we were inactive the user might have
|
||||
@@ -702,10 +702,10 @@ static BOOL configured = FALSE;
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
|
||||
default:
|
||||
break;
|
||||
|
||||
|
||||
}
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - audio manager handled become active");
|
||||
}
|
||||
@@ -717,7 +717,7 @@ static BOOL configured = FALSE;
|
||||
[self applicationDidBecomeActive];
|
||||
}
|
||||
|
||||
//Called when application terminates only if setResignBehavior has been called
|
||||
//Called when application terminates only if setResignBehavior has been called
|
||||
- (void) applicationWillTerminate:(NSNotification *) notification
|
||||
{
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - audio manager handling terminate");
|
||||
@@ -729,8 +729,8 @@ static BOOL configured = FALSE;
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - audio manager got told background music finished");
|
||||
if (backgroundMusicCompletionSelector != nil) {
|
||||
[backgroundMusicCompletionListener performSelector:backgroundMusicCompletionSelector];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(void) beginInterruption {
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - begin interruption");
|
||||
@@ -747,78 +747,78 @@ static BOOL configured = FALSE;
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - interruption ended with flags %i",flags);
|
||||
if (flags == AVAudioSessionInterruptionFlags_ShouldResume) {
|
||||
[self audioSessionResumed];
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
-(void)audioSessionInterrupted
|
||||
{
|
||||
-(void)audioSessionInterrupted
|
||||
{
|
||||
if (!_interrupted) {
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Audio session interrupted");
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Audio session interrupted");
|
||||
_interrupted = YES;
|
||||
|
||||
// Deactivate the current audio session
|
||||
// Deactivate the current audio session
|
||||
[self audioSessionSetActive:NO];
|
||||
|
||||
|
||||
if (alcGetCurrentContext() != NULL) {
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Setting OpenAL context to NULL");
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Setting OpenAL context to NULL");
|
||||
|
||||
ALenum error = AL_NO_ERROR;
|
||||
|
||||
// set the current context to NULL will 'shutdown' openAL
|
||||
alcMakeContextCurrent(NULL);
|
||||
|
||||
// set the current context to NULL will 'shutdown' openAL
|
||||
alcMakeContextCurrent(NULL);
|
||||
|
||||
if((error = alGetError()) != AL_NO_ERROR) {
|
||||
CDLOG(@"Denshion::CDAudioManager - Error making context current %x\n", error);
|
||||
}
|
||||
}
|
||||
#pragma unused(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(void)audioSessionResumed
|
||||
{
|
||||
-(void)audioSessionResumed
|
||||
{
|
||||
if (_interrupted) {
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Audio session resumed");
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Audio session resumed");
|
||||
_interrupted = NO;
|
||||
|
||||
|
||||
BOOL activationResult = NO;
|
||||
// Reactivate the current audio session
|
||||
activationResult = [self audioSessionSetActive:YES];
|
||||
|
||||
activationResult = [self audioSessionSetActive:YES];
|
||||
|
||||
//This code is to handle a problem with iOS 4.0 and 4.01 where reactivating the session can fail if
|
||||
//task switching is performed too rapidly. A test case that reliably reproduces the issue is to call the
|
||||
//iPhone and then hang up after two rings (timing may vary ;))
|
||||
//Basically we keep waiting and trying to let the OS catch up with itself but the number of tries is
|
||||
//limited.
|
||||
if (!activationResult) {
|
||||
CDLOG(@"Denshion::CDAudioManager - Failure reactivating audio session, will try wait-try cycle");
|
||||
CDLOG(@"Denshion::CDAudioManager - Failure reactivating audio session, will try wait-try cycle");
|
||||
int activateCount = 0;
|
||||
while (!activationResult && activateCount < 10) {
|
||||
[NSThread sleepForTimeInterval:0.5];
|
||||
activationResult = [self audioSessionSetActive:YES];
|
||||
activationResult = [self audioSessionSetActive:YES];
|
||||
activateCount++;
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Reactivation attempt %i status = %i",activateCount,activationResult);
|
||||
}
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Reactivation attempt %i status = %i",activateCount,activationResult);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (alcGetCurrentContext() == NULL) {
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Restoring OpenAL context");
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Restoring OpenAL context");
|
||||
ALenum error = AL_NO_ERROR;
|
||||
// Restore open al context
|
||||
alcMakeContextCurrent([soundEngine openALContext]);
|
||||
// Restore open al context
|
||||
alcMakeContextCurrent([soundEngine openALContext]);
|
||||
if((error = alGetError()) != AL_NO_ERROR) {
|
||||
CDLOG(@"Denshion::CDAudioManager - Error making context current%x\n", error);
|
||||
}
|
||||
}
|
||||
#pragma unused(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+(void) end {
|
||||
[sharedManager release];
|
||||
sharedManager = nil;
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@@ -827,7 +827,7 @@ static BOOL configured = FALSE;
|
||||
|
||||
-(void) _setTargetProperty:(float) newVal {
|
||||
((CDLongAudioSource*)target).volume = newVal;
|
||||
}
|
||||
}
|
||||
|
||||
-(float) _getTargetProperty {
|
||||
return ((CDLongAudioSource*)target).volume;
|
||||
@@ -840,7 +840,7 @@ static BOOL configured = FALSE;
|
||||
|
||||
-(Class) _allowableType {
|
||||
return [CDLongAudioSource class];
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
///////////////////////////////////////////////////////////////////////////////////////
|
||||
@@ -852,18 +852,18 @@ static BOOL configured = FALSE;
|
||||
loadedBuffers = [[NSMutableDictionary alloc] initWithCapacity:CD_BUFFERS_START];
|
||||
freedBuffers = [[NSMutableArray alloc] init];
|
||||
nextBufferId = 0;
|
||||
}
|
||||
}
|
||||
return self;
|
||||
}
|
||||
}
|
||||
|
||||
-(void) dealloc {
|
||||
[loadedBuffers release];
|
||||
[freedBuffers release];
|
||||
[super dealloc];
|
||||
}
|
||||
}
|
||||
|
||||
-(int) bufferForFile:(NSString*) filePath create:(BOOL) create {
|
||||
|
||||
|
||||
NSNumber* soundId = (NSNumber*)[loadedBuffers objectForKey:filePath];
|
||||
if(soundId == nil)
|
||||
{
|
||||
@@ -872,7 +872,7 @@ static BOOL configured = FALSE;
|
||||
//First try to get a buffer from the free buffers
|
||||
if ([freedBuffers count] > 0) {
|
||||
bufferId = [[[freedBuffers lastObject] retain] autorelease];
|
||||
[freedBuffers removeLastObject];
|
||||
[freedBuffers removeLastObject];
|
||||
CDLOGINFO(@"Denshion::CDBufferManager reusing buffer id %i",[bufferId intValue]);
|
||||
} else {
|
||||
bufferId = [[NSNumber alloc] initWithInt:nextBufferId];
|
||||
@@ -880,7 +880,7 @@ static BOOL configured = FALSE;
|
||||
CDLOGINFO(@"Denshion::CDBufferManager generating new buffer id %i",[bufferId intValue]);
|
||||
nextBufferId++;
|
||||
}
|
||||
|
||||
|
||||
if ([soundEngine loadBuffer:[bufferId intValue] filePath:filePath]) {
|
||||
//File successfully loaded
|
||||
CDLOGINFO(@"Denshion::CDBufferManager buffer loaded %@ %@",bufferId,filePath);
|
||||
@@ -890,15 +890,15 @@ static BOOL configured = FALSE;
|
||||
//File didn't load, put buffer id on free list
|
||||
[freedBuffers addObject:bufferId];
|
||||
return kCDNoBuffer;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
//No matching buffer was found
|
||||
return kCDNoBuffer;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return [soundId intValue];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(void) releaseBufferForFile:(NSString *) filePath {
|
||||
int bufferId = [self bufferForFile:filePath create:NO];
|
||||
@@ -908,7 +908,9 @@ static BOOL configured = FALSE;
|
||||
NSNumber *freedBufferId = [[NSNumber alloc] initWithInt:bufferId];
|
||||
[freedBufferId autorelease];
|
||||
[freedBuffers addObject:freedBufferId];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@end
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
/*
|
||||
Copyright (c) 2010 Steve Oldmeadow
|
||||
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
@@ -18,7 +18,7 @@
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
|
||||
$Id$
|
||||
*/
|
||||
#define COCOSDENSHION_VERSION "Aphex.rc"
|
||||
@@ -35,22 +35,22 @@
|
||||
*/
|
||||
//Number of buffers slots that will be initially created
|
||||
#define CD_BUFFERS_START 64
|
||||
//Number of buffers that will be added
|
||||
//Number of buffers that will be added
|
||||
#define CD_BUFFERS_INCREMENT 16
|
||||
|
||||
/**
|
||||
If enabled, OpenAL code will use static buffers. When static buffers are used the audio
|
||||
data is managed outside of OpenAL, this eliminates a memcpy operation which leads to
|
||||
data is managed outside of OpenAL, this eliminates a memcpy operation which leads to
|
||||
higher performance when loading sounds.
|
||||
|
||||
|
||||
However, the downside is that when the audio data is freed you must
|
||||
be certain that it is no longer being accessed otherwise your app will crash. Testing on OS 2.2.1
|
||||
and 3.1.2 has shown that this may occur if a buffer is being used by a source with state = AL_PLAYING
|
||||
when the buffer is deleted. If the data is freed too quickly after the source is stopped then
|
||||
a crash will occur. The implemented workaround is that when static buffers are used the unloadBuffer code will wait for
|
||||
any playing sources to finish playing before the associated buffer and data are deleted, however, this delay may negate any
|
||||
any playing sources to finish playing before the associated buffer and data are deleted, however, this delay may negate any
|
||||
performance gains that are achieved during loading.
|
||||
|
||||
|
||||
Performance tests on a 1st gen iPod running OS 2.2.1 loading the CocosDenshionDemo sounds were ~0.14 seconds without
|
||||
static buffers and ~0.12 seconds when using static buffers.
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
/*
|
||||
|
||||
|
||||
Disclaimer: IMPORTANT: This Apple software is supplied to you by
|
||||
Apple Inc. ("Apple") in consideration of your agreement to the
|
||||
following terms, and your use, installation, modification or
|
||||
redistribution of this Apple software constitutes acceptance of these
|
||||
terms. If you do not agree with these terms, please do not use,
|
||||
install, modify or redistribute this Apple software.
|
||||
|
||||
|
||||
In consideration of your agreement to abide by the following terms, and
|
||||
subject to these terms, Apple grants you a personal, non-exclusive
|
||||
license, under Apple's copyrights in this original Apple software (the
|
||||
@@ -22,13 +22,13 @@
|
||||
or implied, are granted by Apple herein, including but not limited to
|
||||
any patent rights that may be infringed by your derivative works or by
|
||||
other works in which the Apple Software may be incorporated.
|
||||
|
||||
|
||||
The Apple Software is provided by Apple on an "AS IS" basis. APPLE
|
||||
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
|
||||
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
|
||||
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
|
||||
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
|
||||
|
||||
|
||||
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
|
||||
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
@@ -37,9 +37,9 @@
|
||||
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
|
||||
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
Copyright (C) 2009 Apple Inc. All Rights Reserved.
|
||||
|
||||
|
||||
$Id$
|
||||
*/
|
||||
|
||||
@@ -55,8 +55,8 @@
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
#import <OpenAL/al.h>
|
||||
#import <OpenAL/alc.h>
|
||||
@@ -67,10 +67,11 @@ extern "C" {
|
||||
void* CDloadWaveAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate);
|
||||
void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate);
|
||||
void* CDGetOpenALAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate);
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
/*
|
||||
|
||||
|
||||
Disclaimer: IMPORTANT: This Apple software is supplied to you by
|
||||
Apple Inc. ("Apple") in consideration of your agreement to the
|
||||
following terms, and your use, installation, modification or
|
||||
redistribution of this Apple software constitutes acceptance of these
|
||||
terms. If you do not agree with these terms, please do not use,
|
||||
install, modify or redistribute this Apple software.
|
||||
|
||||
|
||||
In consideration of your agreement to abide by the following terms, and
|
||||
subject to these terms, Apple grants you a personal, non-exclusive
|
||||
license, under Apple's copyrights in this original Apple software (the
|
||||
@@ -22,13 +22,13 @@
|
||||
or implied, are granted by Apple herein, including but not limited to
|
||||
any patent rights that may be infringed by your derivative works or by
|
||||
other works in which the Apple Software may be incorporated.
|
||||
|
||||
|
||||
The Apple Software is provided by Apple on an "AS IS" basis. APPLE
|
||||
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
|
||||
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
|
||||
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
|
||||
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
|
||||
|
||||
|
||||
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
|
||||
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
@@ -37,9 +37,9 @@
|
||||
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
|
||||
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
Copyright (C) 2009 Apple Inc. All Rights Reserved.
|
||||
|
||||
|
||||
$Id: CDOpenALSupport.h 16 2010-03-11 06:22:10Z steveoldmeadow $
|
||||
*/
|
||||
|
||||
@@ -51,38 +51,38 @@
|
||||
//Taken from oalTouch MyOpenALSupport 1.1
|
||||
void* CDloadWaveAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate)
|
||||
{
|
||||
OSStatus err = noErr;
|
||||
OSStatus err = noErr;
|
||||
UInt64 fileDataSize = 0;
|
||||
AudioStreamBasicDescription theFileFormat;
|
||||
UInt32 thePropertySize = sizeof(theFileFormat);
|
||||
AudioFileID afid = 0;
|
||||
void* theData = NULL;
|
||||
|
||||
|
||||
// Open a file with ExtAudioFileOpen()
|
||||
err = AudioFileOpenURL(inFileURL, kAudioFileReadPermission, 0, &afid);
|
||||
if(err) { CDLOG(@"MyGetOpenALAudioData: AudioFileOpenURL FAILED, Error = %ld\n", err); goto Exit; }
|
||||
|
||||
|
||||
// Get the audio data format
|
||||
err = AudioFileGetProperty(afid, kAudioFilePropertyDataFormat, &thePropertySize, &theFileFormat);
|
||||
if(err) { CDLOG(@"MyGetOpenALAudioData: AudioFileGetProperty(kAudioFileProperty_DataFormat) FAILED, Error = %ld\n", err); goto Exit; }
|
||||
|
||||
if (theFileFormat.mChannelsPerFrame > 2) {
|
||||
|
||||
if (theFileFormat.mChannelsPerFrame > 2) {
|
||||
CDLOG(@"MyGetOpenALAudioData - Unsupported Format, channel count is greater than stereo\n"); goto Exit;
|
||||
}
|
||||
|
||||
if ((theFileFormat.mFormatID != kAudioFormatLinearPCM) || (!TestAudioFormatNativeEndian(theFileFormat))) {
|
||||
|
||||
if ((theFileFormat.mFormatID != kAudioFormatLinearPCM) || (!TestAudioFormatNativeEndian(theFileFormat))) {
|
||||
CDLOG(@"MyGetOpenALAudioData - Unsupported Format, must be little-endian PCM\n"); goto Exit;
|
||||
}
|
||||
|
||||
if ((theFileFormat.mBitsPerChannel != 8) && (theFileFormat.mBitsPerChannel != 16)) {
|
||||
|
||||
if ((theFileFormat.mBitsPerChannel != 8) && (theFileFormat.mBitsPerChannel != 16)) {
|
||||
CDLOG(@"MyGetOpenALAudioData - Unsupported Format, must be 8 or 16 bit PCM\n"); goto Exit;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
thePropertySize = sizeof(fileDataSize);
|
||||
err = AudioFileGetProperty(afid, kAudioFilePropertyAudioDataByteCount, &thePropertySize, &fileDataSize);
|
||||
if(err) { CDLOG(@"MyGetOpenALAudioData: AudioFileGetProperty(kAudioFilePropertyAudioDataByteCount) FAILED, Error = %ld\n", err); goto Exit; }
|
||||
|
||||
|
||||
// Read all the data into memory
|
||||
UInt32 dataSize = (UInt32)fileDataSize;
|
||||
theData = malloc(dataSize);
|
||||
@@ -95,22 +95,22 @@ void* CDloadWaveAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outD
|
||||
// success
|
||||
*outDataSize = (ALsizei)dataSize;
|
||||
//This fix was added by me, however, 8 bit sounds have a clipping sound at the end so aren't really usable (SO)
|
||||
if (theFileFormat.mBitsPerChannel == 16) {
|
||||
if (theFileFormat.mBitsPerChannel == 16) {
|
||||
*outDataFormat = (theFileFormat.mChannelsPerFrame > 1) ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16;
|
||||
} else {
|
||||
*outDataFormat = (theFileFormat.mChannelsPerFrame > 1) ? AL_FORMAT_STEREO8 : AL_FORMAT_MONO8;
|
||||
}
|
||||
*outDataFormat = (theFileFormat.mChannelsPerFrame > 1) ? AL_FORMAT_STEREO8 : AL_FORMAT_MONO8;
|
||||
}
|
||||
*outSampleRate = (ALsizei)theFileFormat.mSampleRate;
|
||||
}
|
||||
else
|
||||
{
|
||||
else
|
||||
{
|
||||
// failure
|
||||
free (theData);
|
||||
theData = NULL; // make sure to return NULL
|
||||
CDLOG(@"MyGetOpenALAudioData: ExtAudioFileRead FAILED, Error = %ld\n", err); goto Exit;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Exit:
|
||||
// Dispose the ExtAudioFileRef, it is no longer needed
|
||||
if (afid) AudioFileClose(afid);
|
||||
@@ -129,7 +129,7 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa
|
||||
void* theData = NULL;
|
||||
AudioStreamBasicDescription theOutputFormat;
|
||||
UInt32 dataSize = 0;
|
||||
|
||||
|
||||
// Open a file with ExtAudioFileOpen()
|
||||
status = ExtAudioFileOpenURL(inFileURL, &extRef);
|
||||
if (status != noErr)
|
||||
@@ -139,7 +139,7 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa
|
||||
}
|
||||
if (abort)
|
||||
goto Exit;
|
||||
|
||||
|
||||
// Get the audio data format
|
||||
status = ExtAudioFileGetProperty(extRef, kExtAudioFileProperty_FileDataFormat, &thePropertySize, &theFileFormat);
|
||||
if (status != noErr)
|
||||
@@ -149,7 +149,7 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa
|
||||
}
|
||||
if (abort)
|
||||
goto Exit;
|
||||
|
||||
|
||||
if (theFileFormat.mChannelsPerFrame > 2)
|
||||
{
|
||||
CDLOG(@"MyGetOpenALAudioData - Unsupported Format, channel count is greater than stereo\n");
|
||||
@@ -157,19 +157,19 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa
|
||||
}
|
||||
if (abort)
|
||||
goto Exit;
|
||||
|
||||
|
||||
// Set the client format to 16 bit signed integer (native-endian) data
|
||||
// Maintain the channel count and sample rate of the original source format
|
||||
theOutputFormat.mSampleRate = theFileFormat.mSampleRate;
|
||||
theOutputFormat.mChannelsPerFrame = theFileFormat.mChannelsPerFrame;
|
||||
|
||||
|
||||
theOutputFormat.mFormatID = kAudioFormatLinearPCM;
|
||||
theOutputFormat.mBytesPerPacket = 2 * theOutputFormat.mChannelsPerFrame;
|
||||
theOutputFormat.mFramesPerPacket = 1;
|
||||
theOutputFormat.mBytesPerFrame = 2 * theOutputFormat.mChannelsPerFrame;
|
||||
theOutputFormat.mBitsPerChannel = 16;
|
||||
theOutputFormat.mFormatFlags = kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked | kAudioFormatFlagIsSignedInteger;
|
||||
|
||||
|
||||
// Set the desired client (output) data format
|
||||
status = ExtAudioFileSetProperty(extRef, kExtAudioFileProperty_ClientDataFormat, sizeof(theOutputFormat), &theOutputFormat);
|
||||
if (status != noErr)
|
||||
@@ -179,7 +179,7 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa
|
||||
}
|
||||
if (abort)
|
||||
goto Exit;
|
||||
|
||||
|
||||
// Get the total frame count
|
||||
thePropertySize = sizeof(theFileLengthInFrames);
|
||||
status = ExtAudioFileGetProperty(extRef, kExtAudioFileProperty_FileLengthFrames, &thePropertySize, &theFileLengthInFrames);
|
||||
@@ -190,7 +190,7 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa
|
||||
}
|
||||
if (abort)
|
||||
goto Exit;
|
||||
|
||||
|
||||
// Read all the data into memory
|
||||
dataSize = (UInt32) theFileLengthInFrames * theOutputFormat.mBytesPerFrame;
|
||||
theData = malloc(dataSize);
|
||||
@@ -202,7 +202,7 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa
|
||||
theDataBuffer.mBuffers[0].mDataByteSize = dataSize;
|
||||
theDataBuffer.mBuffers[0].mNumberChannels = theOutputFormat.mChannelsPerFrame;
|
||||
theDataBuffer.mBuffers[0].mData = theData;
|
||||
|
||||
|
||||
// Read the data into an AudioBufferList
|
||||
status = ExtAudioFileRead(extRef, (UInt32*)&theFileLengthInFrames, &theDataBuffer);
|
||||
if(status == noErr)
|
||||
@@ -223,7 +223,7 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa
|
||||
}
|
||||
if (abort)
|
||||
goto Exit;
|
||||
|
||||
|
||||
Exit:
|
||||
// Dispose the ExtAudioFileRef, it is no longer needed
|
||||
if (extRef) ExtAudioFileDispose(extRef);
|
||||
@@ -231,18 +231,18 @@ Exit:
|
||||
}
|
||||
|
||||
void* CDGetOpenALAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate) {
|
||||
|
||||
|
||||
CFStringRef extension = CFURLCopyPathExtension(inFileURL);
|
||||
CFComparisonResult isWavFile = 0;
|
||||
if (extension != NULL) {
|
||||
isWavFile = CFStringCompare (extension,(CFStringRef)@"wav", kCFCompareCaseInsensitive);
|
||||
CFRelease(extension);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (isWavFile == kCFCompareEqualTo) {
|
||||
return CDloadWaveAudioData(inFileURL, outDataSize, outDataFormat, outSampleRate);
|
||||
return CDloadWaveAudioData(inFileURL, outDataSize, outDataFormat, outSampleRate);
|
||||
} else {
|
||||
return CDloadCafAudioData(inFileURL, outDataSize, outDataFormat, outSampleRate);
|
||||
return CDloadCafAudioData(inFileURL, outDataSize, outDataFormat, outSampleRate);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
/*
|
||||
Copyright (c) 2010 Steve Oldmeadow
|
||||
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
@@ -18,16 +18,16 @@
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
|
||||
$Id$
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
/**
|
||||
@file
|
||||
@b IMPORTANT
|
||||
There are 3 different ways of using CocosDenshion. Depending on which you choose you
|
||||
There are 3 different ways of using CocosDenshion. Depending on which you choose you
|
||||
will need to include different files and frameworks.
|
||||
|
||||
@par SimpleAudioEngine
|
||||
@@ -36,36 +36,36 @@ and some background music and have no interest in learning the lower level worki
|
||||
this is the interface to use.
|
||||
|
||||
Requirements:
|
||||
- Firmware: OS 2.2 or greater
|
||||
- Firmware: OS 2.2 or greater
|
||||
- Files: SimpleAudioEngine.*, CocosDenshion.*
|
||||
- Frameworks: OpenAL, AudioToolbox, AVFoundation
|
||||
|
||||
|
||||
@par CDAudioManager
|
||||
CDAudioManager is basically a thin wrapper around an AVAudioPlayer object used for playing
|
||||
background music and a CDSoundEngine object used for playing sound effects. It manages the
|
||||
audio session for you deals with audio session interruption. It is fairly low level and it
|
||||
is expected you have some understanding of the underlying technologies. For example, for
|
||||
is expected you have some understanding of the underlying technologies. For example, for
|
||||
many use cases regarding background music it is expected you will work directly with the
|
||||
backgroundMusic AVAudioPlayer which is exposed as a property.
|
||||
|
||||
|
||||
Requirements:
|
||||
- Firmware: OS 2.2 or greater
|
||||
- Firmware: OS 2.2 or greater
|
||||
- Files: CDAudioManager.*, CocosDenshion.*
|
||||
- Frameworks: OpenAL, AudioToolbox, AVFoundation
|
||||
|
||||
@par CDSoundEngine
|
||||
CDSoundEngine is a sound engine built upon OpenAL and derived from Apple's oalTouch
|
||||
CDSoundEngine is a sound engine built upon OpenAL and derived from Apple's oalTouch
|
||||
example. It can playback up to 32 sounds simultaneously with control over pitch, pan
|
||||
and gain. It can be set up to handle audio session interruption automatically. You
|
||||
and gain. It can be set up to handle audio session interruption automatically. You
|
||||
may decide to use CDSoundEngine directly instead of CDAudioManager or SimpleAudioEngine
|
||||
because you require OS 2.0 compatibility.
|
||||
|
||||
|
||||
Requirements:
|
||||
- Firmware: OS 2.0 or greater
|
||||
- Firmware: OS 2.0 or greater
|
||||
- Files: CocosDenshion.*
|
||||
- Frameworks: OpenAL, AudioToolbox
|
||||
|
||||
*/
|
||||
|
||||
*/
|
||||
|
||||
#import <OpenAL/al.h>
|
||||
#import <OpenAL/alc.h>
|
||||
@@ -136,13 +136,13 @@ typedef struct _bufferInfo {
|
||||
ALenum format;
|
||||
ALsizei sizeInBytes;
|
||||
ALsizei frequencyInHertz;
|
||||
} bufferInfo;
|
||||
} bufferInfo;
|
||||
|
||||
typedef struct _sourceInfo {
|
||||
bool usable;
|
||||
ALuint sourceId;
|
||||
ALuint attachedBufferId;
|
||||
} sourceInfo;
|
||||
} sourceInfo;
|
||||
|
||||
#pragma mark CDAudioTransportProtocol
|
||||
|
||||
@@ -176,7 +176,7 @@ typedef struct _sourceInfo {
|
||||
*/
|
||||
@interface CDUtilities : NSObject
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/** Fundamentally the same as the corresponding method is FileUtils but added to break binding to cocos2d */
|
||||
+(NSString*) fullPathFromRelativePath:(NSString*) relPath;
|
||||
@@ -187,22 +187,22 @@ typedef struct _sourceInfo {
|
||||
#pragma mark CDSoundEngine
|
||||
|
||||
/** CDSoundEngine is built upon OpenAL and works with SDK 2.0.
|
||||
CDSoundEngine is a sound engine built upon OpenAL and derived from Apple's oalTouch
|
||||
CDSoundEngine is a sound engine built upon OpenAL and derived from Apple's oalTouch
|
||||
example. It can playback up to 32 sounds simultaneously with control over pitch, pan
|
||||
and gain. It can be set up to handle audio session interruption automatically. You
|
||||
and gain. It can be set up to handle audio session interruption automatically. You
|
||||
may decide to use CDSoundEngine directly instead of CDAudioManager or SimpleAudioEngine
|
||||
because you require OS 2.0 compatibility.
|
||||
|
||||
|
||||
Requirements:
|
||||
- Firmware: OS 2.0 or greater
|
||||
- Firmware: OS 2.0 or greater
|
||||
- Files: CocosDenshion.*
|
||||
- Frameworks: OpenAL, AudioToolbox
|
||||
|
||||
|
||||
@since v0.8
|
||||
*/
|
||||
@class CDSoundSource;
|
||||
@interface CDSoundEngine : NSObject <CDAudioInterruptProtocol> {
|
||||
|
||||
|
||||
bufferInfo *_buffers;
|
||||
sourceInfo *_sources;
|
||||
sourceGroup *_sourceGroups;
|
||||
@@ -219,11 +219,11 @@ typedef struct _sourceInfo {
|
||||
BOOL functioning_;
|
||||
float asynchLoadProgress_;
|
||||
BOOL getGainWorks_;
|
||||
|
||||
|
||||
//For managing dynamic allocation of sources and buffers
|
||||
int sourceTotal_;
|
||||
int bufferTotal;
|
||||
|
||||
|
||||
}
|
||||
|
||||
@property (readwrite, nonatomic) ALfloat masterGain;
|
||||
@@ -288,10 +288,10 @@ typedef struct _sourceInfo {
|
||||
|
||||
#pragma mark CDSoundSource
|
||||
/** CDSoundSource is a wrapper around an OpenAL sound source.
|
||||
It allows you to manipulate properties such as pitch, gain, pan and looping while the
|
||||
It allows you to manipulate properties such as pitch, gain, pan and looping while the
|
||||
sound is playing. CDSoundSource is based on the old CDSourceWrapper class but with much
|
||||
added functionality.
|
||||
|
||||
|
||||
@since v1.0
|
||||
*/
|
||||
@interface CDSoundSource : NSObject <CDAudioTransportProtocol, CDAudioInterruptProtocol> {
|
||||
@@ -324,7 +324,7 @@ typedef struct _sourceInfo {
|
||||
#pragma mark CDAudioInterruptTargetGroup
|
||||
|
||||
/** Container for objects that implement audio interrupt protocol i.e. they can be muted and enabled.
|
||||
Setting mute and enabled for the group propagates to all children.
|
||||
Setting mute and enabled for the group propagates to all children.
|
||||
Designed to be used with your CDSoundSource objects to get them to comply with global enabled and mute settings
|
||||
if that is what you want to do.*/
|
||||
@interface CDAudioInterruptTargetGroup : NSObject <CDAudioInterruptProtocol> {
|
||||
@@ -343,7 +343,7 @@ typedef struct _sourceInfo {
|
||||
@interface CDAsynchBufferLoader : NSOperation {
|
||||
NSArray *_loadRequests;
|
||||
CDSoundEngine *_soundEngine;
|
||||
}
|
||||
}
|
||||
|
||||
-(id) init:(NSArray *)loadRequests soundEngine:(CDSoundEngine *) theSoundEngine;
|
||||
|
||||
@@ -401,7 +401,7 @@ typedef enum {
|
||||
float endValue;
|
||||
id target;
|
||||
BOOL stopTargetWhenComplete;
|
||||
|
||||
|
||||
}
|
||||
@property (readwrite, nonatomic) BOOL stopTargetWhenComplete;
|
||||
@property (readwrite, nonatomic) float startValue;
|
||||
@@ -443,3 +443,6 @@ typedef enum {
|
||||
@interface CDSoundEngineFader : CDPropertyModifier{}
|
||||
@end
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -28,121 +28,183 @@ THE SOFTWARE.
|
||||
|
||||
USING_NS_CC;
|
||||
|
||||
static bool __isAudioPreloadOrPlayed = false;
|
||||
|
||||
static void static_end()
|
||||
{
|
||||
[SimpleAudioEngine end];
|
||||
if (__isAudioPreloadOrPlayed)
|
||||
{
|
||||
[SimpleAudioEngine end];
|
||||
}
|
||||
|
||||
__isAudioPreloadOrPlayed = false;
|
||||
}
|
||||
|
||||
static void static_preloadBackgroundMusic(const char* pszFilePath)
|
||||
{
|
||||
__isAudioPreloadOrPlayed = true;
|
||||
[[SimpleAudioEngine sharedEngine] preloadBackgroundMusic: [NSString stringWithUTF8String: pszFilePath]];
|
||||
}
|
||||
|
||||
static void static_playBackgroundMusic(const char* pszFilePath, bool bLoop)
|
||||
{
|
||||
__isAudioPreloadOrPlayed = true;
|
||||
[[SimpleAudioEngine sharedEngine] playBackgroundMusic: [NSString stringWithUTF8String: pszFilePath] loop: bLoop];
|
||||
}
|
||||
|
||||
static void static_stopBackgroundMusic()
|
||||
{
|
||||
if (!__isAudioPreloadOrPlayed)
|
||||
return;
|
||||
|
||||
[[SimpleAudioEngine sharedEngine] stopBackgroundMusic];
|
||||
}
|
||||
|
||||
static void static_pauseBackgroundMusic()
|
||||
{
|
||||
if (!__isAudioPreloadOrPlayed)
|
||||
return;
|
||||
|
||||
[[SimpleAudioEngine sharedEngine] pauseBackgroundMusic];
|
||||
}
|
||||
|
||||
static void static_resumeBackgroundMusic()
|
||||
{
|
||||
if (!__isAudioPreloadOrPlayed)
|
||||
return;
|
||||
|
||||
[[SimpleAudioEngine sharedEngine] resumeBackgroundMusic];
|
||||
}
|
||||
}
|
||||
|
||||
static void static_rewindBackgroundMusic()
|
||||
{
|
||||
if (!__isAudioPreloadOrPlayed)
|
||||
return;
|
||||
|
||||
[[SimpleAudioEngine sharedEngine] rewindBackgroundMusic];
|
||||
}
|
||||
|
||||
static bool static_willPlayBackgroundMusic()
|
||||
{
|
||||
if (!__isAudioPreloadOrPlayed)
|
||||
return false;
|
||||
|
||||
return [[SimpleAudioEngine sharedEngine] willPlayBackgroundMusic];
|
||||
}
|
||||
|
||||
static bool static_isBackgroundMusicPlaying()
|
||||
{
|
||||
if (!__isAudioPreloadOrPlayed)
|
||||
return false;
|
||||
|
||||
return [[SimpleAudioEngine sharedEngine] isBackgroundMusicPlaying];
|
||||
}
|
||||
|
||||
static float static_getBackgroundMusicVolume()
|
||||
{
|
||||
if (!__isAudioPreloadOrPlayed)
|
||||
return 0.0f;
|
||||
|
||||
return [[SimpleAudioEngine sharedEngine] backgroundMusicVolume];
|
||||
}
|
||||
|
||||
static void static_setBackgroundMusicVolume(float volume)
|
||||
{
|
||||
if (!__isAudioPreloadOrPlayed)
|
||||
return;
|
||||
|
||||
volume = MAX( MIN(volume, 1.0), 0 );
|
||||
[SimpleAudioEngine sharedEngine].backgroundMusicVolume = volume;
|
||||
}
|
||||
|
||||
|
||||
static float static_getEffectsVolume()
|
||||
{
|
||||
if (!__isAudioPreloadOrPlayed)
|
||||
return 0.0f;
|
||||
|
||||
return [[SimpleAudioEngine sharedEngine] effectsVolume];
|
||||
}
|
||||
|
||||
|
||||
static void static_setEffectsVolume(float volume)
|
||||
{
|
||||
if (!__isAudioPreloadOrPlayed)
|
||||
return;
|
||||
|
||||
volume = MAX( MIN(volume, 1.0), 0 );
|
||||
[SimpleAudioEngine sharedEngine].effectsVolume = volume;
|
||||
}
|
||||
|
||||
static unsigned int static_playEffect(const char* pszFilePath, bool bLoop, Float32 pszPitch, Float32 pszPan, Float32 pszGain)
|
||||
{
|
||||
__isAudioPreloadOrPlayed = true;
|
||||
return [[SimpleAudioEngine sharedEngine] playEffect:[NSString stringWithUTF8String: pszFilePath] loop:bLoop pitch:pszPitch pan: pszPan gain:pszGain];
|
||||
}
|
||||
|
||||
|
||||
static void static_stopEffect(int nSoundId)
|
||||
{
|
||||
if (!__isAudioPreloadOrPlayed)
|
||||
return;
|
||||
|
||||
[[SimpleAudioEngine sharedEngine] stopEffect: nSoundId];
|
||||
}
|
||||
|
||||
|
||||
static void static_preloadEffect(const char* pszFilePath)
|
||||
{
|
||||
__isAudioPreloadOrPlayed = true;
|
||||
[[SimpleAudioEngine sharedEngine] preloadEffect: [NSString stringWithUTF8String: pszFilePath]];
|
||||
}
|
||||
|
||||
|
||||
static void static_unloadEffect(const char* pszFilePath)
|
||||
{
|
||||
if (!__isAudioPreloadOrPlayed)
|
||||
return;
|
||||
|
||||
[[SimpleAudioEngine sharedEngine] unloadEffect: [NSString stringWithUTF8String: pszFilePath]];
|
||||
}
|
||||
|
||||
static void static_pauseEffect(unsigned int uSoundId)
|
||||
{
|
||||
if (!__isAudioPreloadOrPlayed)
|
||||
return;
|
||||
|
||||
[[SimpleAudioEngine sharedEngine] pauseEffect: uSoundId];
|
||||
}
|
||||
|
||||
static void static_pauseAllEffects()
|
||||
{
|
||||
if (!__isAudioPreloadOrPlayed)
|
||||
return;
|
||||
|
||||
[[SimpleAudioEngine sharedEngine] pauseAllEffects];
|
||||
}
|
||||
|
||||
static void static_resumeEffect(unsigned int uSoundId)
|
||||
{
|
||||
if (!__isAudioPreloadOrPlayed)
|
||||
return;
|
||||
|
||||
[[SimpleAudioEngine sharedEngine] resumeEffect: uSoundId];
|
||||
}
|
||||
|
||||
static void static_resumeAllEffects()
|
||||
{
|
||||
if (!__isAudioPreloadOrPlayed)
|
||||
return;
|
||||
|
||||
[[SimpleAudioEngine sharedEngine] resumeAllEffects];
|
||||
}
|
||||
|
||||
static void static_stopAllEffects()
|
||||
{
|
||||
if (!__isAudioPreloadOrPlayed)
|
||||
return;
|
||||
|
||||
[[SimpleAudioEngine sharedEngine] stopAllEffects];
|
||||
}
|
||||
|
||||
namespace CocosDenshion {
|
||||
|
||||
static SimpleAudioEngine *s_pEngine;
|
||||
static SimpleAudioEngine *s_pEngine = nullptr;
|
||||
|
||||
SimpleAudioEngine::SimpleAudioEngine()
|
||||
{
|
||||
@@ -160,7 +222,7 @@ SimpleAudioEngine* SimpleAudioEngine::getInstance()
|
||||
{
|
||||
s_pEngine = new (std::nothrow) SimpleAudioEngine();
|
||||
}
|
||||
|
||||
|
||||
return s_pEngine;
|
||||
}
|
||||
|
||||
@@ -171,7 +233,7 @@ void SimpleAudioEngine::end()
|
||||
delete s_pEngine;
|
||||
s_pEngine = nullptr;
|
||||
}
|
||||
|
||||
|
||||
static_end();
|
||||
}
|
||||
|
||||
@@ -202,7 +264,7 @@ void SimpleAudioEngine::pauseBackgroundMusic()
|
||||
void SimpleAudioEngine::resumeBackgroundMusic()
|
||||
{
|
||||
static_resumeBackgroundMusic();
|
||||
}
|
||||
}
|
||||
|
||||
void SimpleAudioEngine::rewindBackgroundMusic()
|
||||
{
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
/*
|
||||
Copyright (c) 2010 Steve Oldmeadow
|
||||
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
@@ -18,7 +18,7 @@
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
|
||||
$Id$
|
||||
*/
|
||||
|
||||
@@ -30,15 +30,15 @@
|
||||
This is recommended for basic audio requirements. If you just want to play some sound fx
|
||||
and some background music and have no interest in learning the lower level workings then
|
||||
this is the interface to use.
|
||||
|
||||
|
||||
Requirements:
|
||||
- Firmware: OS 2.2 or greater
|
||||
- Firmware: OS 2.2 or greater
|
||||
- Files: SimpleAudioEngine.*, CocosDenshion.*
|
||||
- Frameworks: OpenAL, AudioToolbox, AVFoundation
|
||||
@since v0.8
|
||||
*/
|
||||
@interface SimpleAudioEngine : NSObject <CDAudioInterruptProtocol> {
|
||||
|
||||
|
||||
BOOL mute_;
|
||||
BOOL enabled_;
|
||||
}
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
/*
|
||||
Copyright (c) 2010 Steve Oldmeadow
|
||||
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
@@ -18,7 +18,7 @@
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
|
||||
$Id$
|
||||
*/
|
||||
|
||||
@@ -71,14 +71,14 @@ static CDBufferManager *bufferManager = nil;
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
+(void) end
|
||||
+(void) end
|
||||
{
|
||||
am = nil;
|
||||
[CDAudioManager end];
|
||||
[bufferManager release];
|
||||
[sharedEngine release];
|
||||
sharedEngine = nil;
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark SimpleAudioEngine - background music
|
||||
|
||||
@@ -103,11 +103,11 @@ static CDBufferManager *bufferManager = nil;
|
||||
|
||||
-(void) pauseBackgroundMusic {
|
||||
[am pauseBackgroundMusic];
|
||||
}
|
||||
}
|
||||
|
||||
-(void) resumeBackgroundMusic {
|
||||
[am resumeBackgroundMusic];
|
||||
}
|
||||
}
|
||||
|
||||
-(void) rewindBackgroundMusic {
|
||||
[am rewindBackgroundMusic];
|
||||
@@ -115,7 +115,7 @@ static CDBufferManager *bufferManager = nil;
|
||||
|
||||
-(BOOL) isBackgroundMusicPlaying {
|
||||
return [am isBackgroundMusicPlaying];
|
||||
}
|
||||
}
|
||||
|
||||
-(BOOL) willPlayBackgroundMusic {
|
||||
return [am willPlayBackgroundMusic];
|
||||
@@ -135,12 +135,12 @@ static CDBufferManager *bufferManager = nil;
|
||||
return [soundEngine playSound:soundId sourceGroupId:0 pitch:pitch pan:pan gain:gain loop:loop];
|
||||
} else {
|
||||
return CD_MUTE;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(void) stopEffect:(ALuint) soundId {
|
||||
[soundEngine stopSound:soundId];
|
||||
}
|
||||
}
|
||||
|
||||
-(void) pauseEffect:(ALuint) soundId {
|
||||
[soundEngine pauseSound: soundId];
|
||||
@@ -187,7 +187,7 @@ static CDBufferManager *bufferManager = nil;
|
||||
if (mute_ != muteValue) {
|
||||
mute_ = muteValue;
|
||||
am.mute = mute_;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(BOOL) enabled
|
||||
@@ -200,7 +200,7 @@ static CDBufferManager *bufferManager = nil;
|
||||
if (enabled_ != enabledValue) {
|
||||
enabled_ = enabledValue;
|
||||
am.enabled = enabled_;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -208,23 +208,23 @@ static CDBufferManager *bufferManager = nil;
|
||||
-(float) backgroundMusicVolume
|
||||
{
|
||||
return am.backgroundMusic.volume;
|
||||
}
|
||||
}
|
||||
|
||||
-(void) setBackgroundMusicVolume:(float) volume
|
||||
{
|
||||
am.backgroundMusic.volume = volume;
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark SimpleAudioEngine - EffectsVolume
|
||||
-(float) effectsVolume
|
||||
{
|
||||
return am.soundEngine.masterGain;
|
||||
}
|
||||
}
|
||||
|
||||
-(void) setEffectsVolume:(float) volume
|
||||
{
|
||||
am.soundEngine.masterGain = volume;
|
||||
}
|
||||
}
|
||||
|
||||
-(CDSoundSource *) soundSourceForFile:(NSString*) filePath {
|
||||
int soundId = [bufferManager bufferForFile:filePath create:YES];
|
||||
@@ -234,7 +234,7 @@ static CDBufferManager *bufferManager = nil;
|
||||
return result;
|
||||
} else {
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
/*
|
||||
Copyright (c) 2010 Steve Oldmeadow
|
||||
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
@@ -18,7 +18,7 @@
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
|
||||
$Id$
|
||||
*/
|
||||
|
||||
@@ -54,14 +54,14 @@ typedef enum {
|
||||
/** Notifications */
|
||||
extern NSString * const kCDN_AudioManagerInitialised;
|
||||
|
||||
@interface CDAsynchInitialiser : NSOperation {}
|
||||
@interface CDAsynchInitialiser : NSOperation {}
|
||||
@end
|
||||
|
||||
/** CDAudioManager supports two long audio source channels called left and right*/
|
||||
typedef enum {
|
||||
kASC_Left = 0,
|
||||
kASC_Right = 1
|
||||
} tAudioSourceChannel;
|
||||
} tAudioSourceChannel;
|
||||
|
||||
typedef enum {
|
||||
kLAS_Init,
|
||||
@@ -94,18 +94,18 @@ typedef enum {
|
||||
NSString *audioSourceFilePath;
|
||||
NSInteger numberOfLoops;
|
||||
float volume;
|
||||
id<CDLongAudioSourceDelegate> delegate;
|
||||
id<CDLongAudioSourceDelegate> delegate;
|
||||
BOOL mute;
|
||||
BOOL enabled_;
|
||||
BOOL backgroundMusic;
|
||||
// whether background music is paused
|
||||
BOOL paused;
|
||||
@public
|
||||
@public
|
||||
BOOL systemPaused;//Used for auto resign handling
|
||||
NSTimeInterval systemPauseLocation;//Used for auto resign handling
|
||||
@protected
|
||||
tLongAudioSourceState state;
|
||||
}
|
||||
}
|
||||
@property (readonly) CCAudioPlayer *audioSourcePlayer;
|
||||
@property (readonly) NSString *audioSourceFilePath;
|
||||
@property (readwrite, nonatomic) NSInteger numberOfLoops;
|
||||
@@ -119,7 +119,7 @@ typedef enum {
|
||||
-(void) load:(NSString*) filePath;
|
||||
/** Plays the audio source */
|
||||
-(void) play;
|
||||
/** Stops playing the audio soruce */
|
||||
/** Stops playing the audio source */
|
||||
-(void) stop;
|
||||
/** Pauses the audio source */
|
||||
-(void) pause;
|
||||
@@ -132,15 +132,15 @@ typedef enum {
|
||||
|
||||
@end
|
||||
|
||||
/**
|
||||
/**
|
||||
CDAudioManager manages audio requirements for a game. It provides access to a CDSoundEngine object
|
||||
for playing sound effects. It provides access to two CDLongAudioSource object (left and right channel)
|
||||
for playing long duration audio such as background music and narration tracks. Additionally it manages
|
||||
the audio session to take care of things like audio session interruption and interacting with the audio
|
||||
of other apps that are running on the device.
|
||||
|
||||
|
||||
Requirements:
|
||||
- Firmware: OS 2.2 or greater
|
||||
- Firmware: OS 2.2 or greater
|
||||
- Files: CDAudioManager.*, CocosDenshion.*
|
||||
- Frameworks: OpenAL, AudioToolbox, AVFoundation
|
||||
@since v0.8
|
||||
@@ -160,7 +160,7 @@ typedef enum {
|
||||
BOOL _interrupted;
|
||||
BOOL _audioSessionActive;
|
||||
BOOL enabled_;
|
||||
|
||||
|
||||
//For handling resign/become active
|
||||
BOOL _isObservingAppEvents;
|
||||
tAudioManagerResignBehavior _resignBehavior;
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
/*
|
||||
Copyright (c) 2010 Steve Oldmeadow
|
||||
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
@@ -18,7 +18,7 @@
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
|
||||
$Id$
|
||||
*/
|
||||
|
||||
@@ -27,13 +27,13 @@
|
||||
|
||||
NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised";
|
||||
|
||||
//NSOperation object used to asynchronously initialise
|
||||
//NSOperation object used to asynchronously initialise
|
||||
@implementation CDAsynchInitialiser
|
||||
|
||||
-(void) main {
|
||||
[super main];
|
||||
[CDAudioManager sharedManager];
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@@ -57,10 +57,10 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised";
|
||||
[audioSourcePlayer release];
|
||||
[audioSourceFilePath release];
|
||||
[super dealloc];
|
||||
}
|
||||
}
|
||||
|
||||
-(void) load:(NSString*) filePath {
|
||||
//We have alread loaded a file previously, check if we are being asked to load the same file
|
||||
//We have already loaded a file previously, check if we are being asked to load the same file
|
||||
if (state == kLAS_Init || ![filePath isEqualToString:audioSourceFilePath]) {
|
||||
CDLOGINFO(@"Denshion::CDLongAudioSource - Loading new audio source %@",filePath);
|
||||
//New file
|
||||
@@ -78,10 +78,10 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised";
|
||||
if (delegate && [delegate respondsToSelector:@selector(cdAudioSourceFileDidChange:)]) {
|
||||
//Tell our delegate the file has changed
|
||||
[delegate cdAudioSourceFileDidChange:self];
|
||||
}
|
||||
}
|
||||
} else {
|
||||
CDLOG(@"Denshion::CDLongAudioSource - Error initialising audio player: %@",error);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
//Same file - just return it to a consistent state
|
||||
[self pause];
|
||||
@@ -90,7 +90,7 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised";
|
||||
audioSourcePlayer.volume = volume;
|
||||
audioSourcePlayer.numberOfLoops = numberOfLoops;
|
||||
state = kLAS_Loaded;
|
||||
}
|
||||
}
|
||||
|
||||
-(void) play {
|
||||
if (enabled_) {
|
||||
@@ -99,18 +99,18 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised";
|
||||
[audioSourcePlayer play];
|
||||
} else {
|
||||
CDLOGINFO(@"Denshion::CDLongAudioSource long audio source didn't play because it is disabled");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(void) stop {
|
||||
paused = NO;
|
||||
[audioSourcePlayer stop];
|
||||
}
|
||||
}
|
||||
|
||||
-(void) pause {
|
||||
paused = YES;
|
||||
[audioSourcePlayer pause];
|
||||
}
|
||||
}
|
||||
|
||||
-(void) rewind {
|
||||
paused = NO;
|
||||
@@ -121,7 +121,7 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised";
|
||||
-(void) resume {
|
||||
paused = NO;
|
||||
[audioSourcePlayer resume];
|
||||
}
|
||||
}
|
||||
|
||||
-(BOOL) isPlaying {
|
||||
if (state != kLAS_Init) {
|
||||
@@ -136,10 +136,10 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised";
|
||||
volume = newVolume;
|
||||
if (state != kLAS_Init && !mute) {
|
||||
audioSourcePlayer.volume = newVolume;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(float) volume
|
||||
-(float) volume
|
||||
{
|
||||
return volume;
|
||||
}
|
||||
@@ -148,9 +148,9 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised";
|
||||
-(BOOL) mute
|
||||
{
|
||||
return mute;
|
||||
}
|
||||
}
|
||||
|
||||
-(void) setMute:(BOOL) muteValue
|
||||
-(void) setMute:(BOOL) muteValue
|
||||
{
|
||||
if (mute != muteValue) {
|
||||
if (mute) {
|
||||
@@ -160,15 +160,15 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised";
|
||||
audioSourcePlayer.volume = 0.0f;
|
||||
}
|
||||
mute = muteValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(BOOL) enabled
|
||||
-(BOOL) enabled
|
||||
{
|
||||
return enabled_;
|
||||
}
|
||||
}
|
||||
|
||||
-(void) setEnabled:(BOOL)enabledValue
|
||||
-(void) setEnabled:(BOOL)enabledValue
|
||||
{
|
||||
if (enabledValue != enabled_) {
|
||||
enabled_ = enabledValue;
|
||||
@@ -176,25 +176,25 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised";
|
||||
//"Stop" the sounds
|
||||
[self pause];
|
||||
[self rewind];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(NSInteger) numberOfLoops {
|
||||
return numberOfLoops;
|
||||
}
|
||||
}
|
||||
|
||||
-(void) setNumberOfLoops:(NSInteger) loopCount
|
||||
{
|
||||
audioSourcePlayer.numberOfLoops = loopCount;
|
||||
numberOfLoops = loopCount;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)audioPlayerDidFinishPlaying:(CCAudioPlayer *)player successfully:(BOOL)flag {
|
||||
CDLOGINFO(@"Denshion::CDLongAudioSource - audio player finished");
|
||||
#if TARGET_IPHONE_SIMULATOR
|
||||
#if TARGET_IPHONE_SIMULATOR
|
||||
CDLOGINFO(@"Denshion::CDLongAudioSource - workaround for OpenAL clobbered audio issue");
|
||||
//This is a workaround for an issue in all simulators (tested to 3.1.2). Problem is
|
||||
//This is a workaround for an issue in all simulators (tested to 3.1.2). Problem is
|
||||
//that OpenAL audio playback is clobbered when an CCAudioPlayer stops. Workaround
|
||||
//is to keep the player playing on an endless loop with 0 volume and then when
|
||||
//it is played again reset the volume and set loop count appropriately.
|
||||
@@ -202,11 +202,11 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised";
|
||||
player.numberOfLoops = -1;
|
||||
player.volume = 0;
|
||||
[player play];
|
||||
#endif
|
||||
#endif
|
||||
if (delegate && [delegate respondsToSelector:@selector(cdAudioSourceDidFinishPlaying:)]) {
|
||||
[delegate cdAudioSourceDidFinishPlaying:self];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(void)audioPlayerBeginInterruption:(CCAudioPlayer *)player {
|
||||
CDLOGINFO(@"Denshion::CDLongAudioSource - audio player interrupted");
|
||||
@@ -215,16 +215,16 @@ NSString * const kCDN_AudioManagerInitialised = @"kCDN_AudioManagerInitialised";
|
||||
-(void)audioPlayerEndInterruption:(CCAudioPlayer *)player {
|
||||
CDLOGINFO(@"Denshion::CDLongAudioSource - audio player resumed");
|
||||
if (self.backgroundMusic) {
|
||||
//Check if background music can play as rules may have changed during
|
||||
//Check if background music can play as rules may have changed during
|
||||
//the interruption. This is to address a specific issue in 4.x when
|
||||
//fast task switching
|
||||
if([CDAudioManager sharedManager].willPlayBackgroundMusic) {
|
||||
[player play];
|
||||
}
|
||||
}
|
||||
} else {
|
||||
[player play];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@@ -249,26 +249,26 @@ static BOOL configured = FALSE;
|
||||
NSError *activationError = nil;
|
||||
if ([[AVAudioSession sharedInstance] setActive:active error:&activationError]) {
|
||||
_audioSessionActive = active;
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Audio session set active %i succeeded", active);
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Audio session set active %i succeeded", active);
|
||||
return YES;
|
||||
} else {
|
||||
//Failed
|
||||
CDLOG(@"Denshion::CDAudioManager - Audio session set active %i failed with error %@", active, activationError);
|
||||
CDLOG(@"Denshion::CDAudioManager - Audio session set active %i failed with error %@", active, activationError);
|
||||
return NO;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(BOOL) audioSessionSetCategory:(NSString*) category {
|
||||
NSError *categoryError = nil;
|
||||
if ([[AVAudioSession sharedInstance] setCategory:category error:&categoryError]) {
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Audio session set category %@ succeeded", category);
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Audio session set category %@ succeeded", category);
|
||||
return YES;
|
||||
} else {
|
||||
//Failed
|
||||
CDLOG(@"Denshion::CDAudioManager - Audio session set category %@ failed with error %@", category, categoryError);
|
||||
CDLOG(@"Denshion::CDAudioManager - Audio session set category %@ failed with error %@", category, categoryError);
|
||||
return NO;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Init
|
||||
+ (CDAudioManager *) sharedManager
|
||||
@@ -282,14 +282,14 @@ static BOOL configured = FALSE;
|
||||
sharedManager = [[CDAudioManager alloc] init:configuredMode];
|
||||
_sharedManagerState = kAMStateInitialised;//This is only really relevant when using asynchronous initialisation
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:kCDN_AudioManagerInitialised object:nil];
|
||||
}
|
||||
}
|
||||
}
|
||||
return sharedManager;
|
||||
}
|
||||
|
||||
+ (tAudioManagerState) sharedManagerState {
|
||||
return _sharedManagerState;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Call this to set up audio manager asynchronously. Initialisation is finished when sharedManagerState == kAMStateInitialised
|
||||
@@ -302,9 +302,9 @@ static BOOL configured = FALSE;
|
||||
CDAsynchInitialiser *initOp = [[[CDAsynchInitialiser alloc] init] autorelease];
|
||||
NSOperationQueue *opQ = [[[NSOperationQueue alloc] init] autorelease];
|
||||
[opQ addOperation:initOp];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+ (id) alloc
|
||||
{
|
||||
@@ -321,7 +321,7 @@ static BOOL configured = FALSE;
|
||||
+ (void) configure: (tAudioManagerMode) mode {
|
||||
configuredMode = mode;
|
||||
configured = TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
-(BOOL) isOtherAudioPlaying {
|
||||
UInt32 isPlaying = 0;
|
||||
@@ -334,7 +334,7 @@ static BOOL configured = FALSE;
|
||||
|
||||
_mode = mode;
|
||||
switch (_mode) {
|
||||
|
||||
|
||||
case kAMM_FxOnly:
|
||||
//Share audio with other app
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Audio will be shared");
|
||||
@@ -342,7 +342,7 @@ static BOOL configured = FALSE;
|
||||
_audioSessionCategory = AVAudioSessionCategoryAmbient;
|
||||
willPlayBackgroundMusic = NO;
|
||||
break;
|
||||
|
||||
|
||||
case kAMM_FxPlusMusic:
|
||||
//Use audio exclusively - if other audio is playing it will be stopped
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Audio will be exclusive");
|
||||
@@ -350,7 +350,7 @@ static BOOL configured = FALSE;
|
||||
_audioSessionCategory = AVAudioSessionCategorySoloAmbient;
|
||||
willPlayBackgroundMusic = YES;
|
||||
break;
|
||||
|
||||
|
||||
case kAMM_MediaPlayback:
|
||||
//Use audio exclusively, ignore mute switch and sleep
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Media playback mode, audio will be exclusive");
|
||||
@@ -358,7 +358,7 @@ static BOOL configured = FALSE;
|
||||
_audioSessionCategory = AVAudioSessionCategoryPlayback;
|
||||
willPlayBackgroundMusic = YES;
|
||||
break;
|
||||
|
||||
|
||||
case kAMM_PlayAndRecord:
|
||||
//Use audio exclusively, ignore mute switch and sleep, has inputs and outputs
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Play and record mode, audio will be exclusive");
|
||||
@@ -366,7 +366,7 @@ static BOOL configured = FALSE;
|
||||
_audioSessionCategory = AVAudioSessionCategoryPlayAndRecord;
|
||||
willPlayBackgroundMusic = YES;
|
||||
break;
|
||||
|
||||
|
||||
default:
|
||||
//kAudioManagerFxPlusMusicIfNoOtherAudio
|
||||
if ([self isOtherAudioPlaying]) {
|
||||
@@ -379,18 +379,18 @@ static BOOL configured = FALSE;
|
||||
//_audioSessionCategory = kAudioSessionCategory_SoloAmbientSound;
|
||||
_audioSessionCategory = AVAudioSessionCategorySoloAmbient;
|
||||
willPlayBackgroundMusic = YES;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
[self audioSessionSetCategory:_audioSessionCategory];
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is used to work around various bugs introduced in 4.x OS versions. In some circumstances the
|
||||
* audio session is interrupted but never resumed, this results in the loss of OpenAL audio when following
|
||||
* This method is used to work around various bugs introduced in 4.x OS versions. In some circumstances the
|
||||
* audio session is interrupted but never resumed, this results in the loss of OpenAL audio when following
|
||||
* standard practices. If we detect this situation then we will attempt to resume the audio session ourselves.
|
||||
* Known triggers: lock the device then unlock it (iOS 4.2 gm), playback a song using MPMediaPlayer (iOS 4.0)
|
||||
*/
|
||||
@@ -398,16 +398,16 @@ static BOOL configured = FALSE;
|
||||
if (_interrupted && alcGetCurrentContext() == NULL) {
|
||||
CDLOG(@"Denshion::CDAudioManager - bad OpenAL context detected, attempting to resume audio session");
|
||||
[self audioSessionResumed];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (id) init: (tAudioManagerMode) mode {
|
||||
if ((self = [super init])) {
|
||||
|
||||
//Initialise the audio session
|
||||
|
||||
//Initialise the audio session
|
||||
AVAudioSession* session = [AVAudioSession sharedInstance];
|
||||
session.delegate = self;
|
||||
|
||||
|
||||
_mode = mode;
|
||||
backgroundMusicCompletionSelector = nil;
|
||||
_isObservingAppEvents = FALSE;
|
||||
@@ -418,27 +418,27 @@ static BOOL configured = FALSE;
|
||||
_audioSessionActive = NO;
|
||||
[self setMode:mode];
|
||||
soundEngine = [[CDSoundEngine alloc] init];
|
||||
|
||||
|
||||
//Set up audioSource channels
|
||||
audioSourceChannels = [[NSMutableArray alloc] init];
|
||||
CDLongAudioSource *leftChannel = [[CDLongAudioSource alloc] init];
|
||||
leftChannel.backgroundMusic = YES;
|
||||
CDLongAudioSource *rightChannel = [[CDLongAudioSource alloc] init];
|
||||
rightChannel.backgroundMusic = NO;
|
||||
[audioSourceChannels insertObject:leftChannel atIndex:kASC_Left];
|
||||
[audioSourceChannels insertObject:leftChannel atIndex:kASC_Left];
|
||||
[audioSourceChannels insertObject:rightChannel atIndex:kASC_Right];
|
||||
[leftChannel release];
|
||||
[rightChannel release];
|
||||
//Used to support legacy APIs
|
||||
backgroundMusic = [self audioSourceForChannel:BACKGROUND_MUSIC_CHANNEL];
|
||||
backgroundMusic.delegate = self;
|
||||
|
||||
|
||||
//Add handler for bad al context messages, these are posted by the sound engine.
|
||||
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(badAlContextHandler) name:kCDN_BadAlContext object:nil];
|
||||
|
||||
}
|
||||
return self;
|
||||
}
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
-(void) dealloc {
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - deallocating");
|
||||
@@ -448,13 +448,13 @@ static BOOL configured = FALSE;
|
||||
[self audioSessionSetActive:NO];
|
||||
[audioSourceChannels release];
|
||||
[super dealloc];
|
||||
}
|
||||
}
|
||||
|
||||
/** Retrieves the audio source for the specified channel */
|
||||
-(CDLongAudioSource*) audioSourceForChannel:(tAudioSourceChannel) channel
|
||||
-(CDLongAudioSource*) audioSourceForChannel:(tAudioSourceChannel) channel
|
||||
{
|
||||
return (CDLongAudioSource*)[audioSourceChannels objectAtIndex:channel];
|
||||
}
|
||||
}
|
||||
|
||||
/** Loads the data from the specified file path to the channel's audio source */
|
||||
-(CDLongAudioSource*) audioSourceLoad:(NSString*) filePath channel:(tAudioSourceChannel) channel
|
||||
@@ -464,14 +464,14 @@ static BOOL configured = FALSE;
|
||||
[audioSource load:filePath];
|
||||
}
|
||||
return audioSource;
|
||||
}
|
||||
}
|
||||
|
||||
-(BOOL) isBackgroundMusicPlaying {
|
||||
return [self.backgroundMusic isPlaying];
|
||||
}
|
||||
}
|
||||
|
||||
//NB: originally I tried using a route change listener and intended to store the current route,
|
||||
//however, on a 3gs running 3.1.2 no route change is generated when the user switches the
|
||||
//however, on a 3gs running 3.1.2 no route change is generated when the user switches the
|
||||
//ringer mute switch to off (i.e. enables sound) therefore polling is the only reliable way to
|
||||
//determine ringer switch state
|
||||
-(BOOL) isDeviceMuted {
|
||||
@@ -479,36 +479,36 @@ static BOOL configured = FALSE;
|
||||
#if TARGET_IPHONE_SIMULATOR
|
||||
//Calling audio route stuff on the simulator causes problems
|
||||
return NO;
|
||||
#else
|
||||
#else
|
||||
CFStringRef newAudioRoute;
|
||||
UInt32 propertySize = sizeof (CFStringRef);
|
||||
|
||||
|
||||
AudioSessionGetProperty (
|
||||
kAudioSessionProperty_AudioRoute,
|
||||
&propertySize,
|
||||
&newAudioRoute
|
||||
);
|
||||
|
||||
|
||||
if (newAudioRoute == NULL) {
|
||||
//Don't expect this to happen but playing safe otherwise a null in the CFStringCompare will cause a crash
|
||||
return YES;
|
||||
} else {
|
||||
} else {
|
||||
CFComparisonResult newDeviceIsMuted = CFStringCompare (
|
||||
newAudioRoute,
|
||||
(CFStringRef) @"",
|
||||
0
|
||||
);
|
||||
|
||||
|
||||
return (newDeviceIsMuted == kCFCompareEqualTo);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark Audio Interrupt Protocol
|
||||
|
||||
-(BOOL) mute {
|
||||
return _mute;
|
||||
}
|
||||
}
|
||||
|
||||
-(void) setMute:(BOOL) muteValue {
|
||||
if (muteValue != _mute) {
|
||||
@@ -516,13 +516,13 @@ static BOOL configured = FALSE;
|
||||
[soundEngine setMute:muteValue];
|
||||
for( CDLongAudioSource *audioSource in audioSourceChannels) {
|
||||
audioSource.mute = muteValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(BOOL) enabled {
|
||||
return enabled_;
|
||||
}
|
||||
}
|
||||
|
||||
-(void) setEnabled:(BOOL) enabledValue {
|
||||
if (enabledValue != enabled_) {
|
||||
@@ -530,20 +530,20 @@ static BOOL configured = FALSE;
|
||||
[soundEngine setEnabled:enabled_];
|
||||
for( CDLongAudioSource *audioSource in audioSourceChannels) {
|
||||
audioSource.enabled = enabled_;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(CDLongAudioSource*) backgroundMusic
|
||||
{
|
||||
return backgroundMusic;
|
||||
}
|
||||
}
|
||||
|
||||
//Load background music ready for playing
|
||||
-(void) preloadBackgroundMusic:(NSString*) filePath
|
||||
{
|
||||
[self.backgroundMusic load:filePath];
|
||||
}
|
||||
[self.backgroundMusic load:filePath];
|
||||
}
|
||||
|
||||
-(void) playBackgroundMusic:(NSString*) filePath loop:(BOOL) loop
|
||||
{
|
||||
@@ -571,7 +571,7 @@ static BOOL configured = FALSE;
|
||||
-(void) pauseBackgroundMusic
|
||||
{
|
||||
[self.backgroundMusic pause];
|
||||
}
|
||||
}
|
||||
|
||||
-(void) resumeBackgroundMusic
|
||||
{
|
||||
@@ -579,35 +579,35 @@ static BOOL configured = FALSE;
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - resume bgm aborted because audio is not exclusive or sound is muted");
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (![self.backgroundMusic paused]) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
[self.backgroundMusic resume];
|
||||
}
|
||||
}
|
||||
|
||||
-(void) rewindBackgroundMusic
|
||||
{
|
||||
[self.backgroundMusic rewind];
|
||||
}
|
||||
}
|
||||
|
||||
-(void) setBackgroundMusicCompletionListener:(id) listener selector:(SEL) selector {
|
||||
backgroundMusicCompletionListener = listener;
|
||||
backgroundMusicCompletionSelector = selector;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Call this method to have the audio manager automatically handle application resign and
|
||||
* become active. Pass a tAudioManagerResignBehavior to indicate the desired behavior
|
||||
* for resigning and becoming active again.
|
||||
*
|
||||
* If autohandle is YES then the applicationWillResignActive and applicationDidBecomActive
|
||||
* If autohandle is YES then the applicationWillResignActive and applicationDidBecomActive
|
||||
* methods are automatically called, otherwise you must call them yourself at the appropriate time.
|
||||
*
|
||||
* Based on idea of Dominique Bongard
|
||||
*/
|
||||
-(void) setResignBehavior:(tAudioManagerResignBehavior) resignBehavior autoHandle:(BOOL) autoHandle {
|
||||
-(void) setResignBehavior:(tAudioManagerResignBehavior) resignBehavior autoHandle:(BOOL) autoHandle {
|
||||
|
||||
if (!_isObservingAppEvents && autoHandle) {
|
||||
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:@"UIApplicationWillResignActiveNotification" object:nil];
|
||||
@@ -616,18 +616,18 @@ static BOOL configured = FALSE;
|
||||
_isObservingAppEvents = TRUE;
|
||||
}
|
||||
_resignBehavior = resignBehavior;
|
||||
}
|
||||
}
|
||||
|
||||
- (void) applicationWillResignActive {
|
||||
_resigned = YES;
|
||||
|
||||
//Set the audio sesssion to one that allows sharing so that other audio won't be clobbered on resume
|
||||
|
||||
//Set the audio session to one that allows sharing so that other audio won't be clobbered on resume
|
||||
[self audioSessionSetCategory:AVAudioSessionCategoryAmbient];
|
||||
|
||||
|
||||
switch (_resignBehavior) {
|
||||
|
||||
|
||||
case kAMRBStopPlay:
|
||||
|
||||
|
||||
for( CDLongAudioSource *audioSource in audioSourceChannels) {
|
||||
if (audioSource.isPlaying) {
|
||||
audioSource->systemPaused = YES;
|
||||
@@ -641,18 +641,18 @@ static BOOL configured = FALSE;
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
|
||||
case kAMRBStop:
|
||||
//Stop music regardless of whether it is playing or not because if it was paused
|
||||
//then the OS would resume it
|
||||
for( CDLongAudioSource *audioSource in audioSourceChannels) {
|
||||
[audioSource stop];
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
default:
|
||||
break;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - handled resign active");
|
||||
}
|
||||
|
||||
@@ -660,18 +660,18 @@ static BOOL configured = FALSE;
|
||||
- (void) applicationWillResignActive:(NSNotification *) notification
|
||||
{
|
||||
[self applicationWillResignActive];
|
||||
}
|
||||
}
|
||||
|
||||
- (void) applicationDidBecomeActive {
|
||||
|
||||
|
||||
if (_resigned) {
|
||||
_resigned = NO;
|
||||
//Reset the mode incase something changed with audio while we were inactive
|
||||
[self setMode:_mode];
|
||||
switch (_resignBehavior) {
|
||||
|
||||
|
||||
case kAMRBStopPlay:
|
||||
|
||||
|
||||
//Music had been stopped but stop maintains current time
|
||||
//so playing again will continue from where music was before resign active.
|
||||
//We check if music can be played because while we were inactive the user might have
|
||||
@@ -685,10 +685,10 @@ static BOOL configured = FALSE;
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
|
||||
default:
|
||||
break;
|
||||
|
||||
|
||||
}
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - audio manager handled become active");
|
||||
}
|
||||
@@ -700,7 +700,7 @@ static BOOL configured = FALSE;
|
||||
[self applicationDidBecomeActive];
|
||||
}
|
||||
|
||||
//Called when application terminates only if setResignBehavior has been called
|
||||
//Called when application terminates only if setResignBehavior has been called
|
||||
- (void) applicationWillTerminate:(NSNotification *) notification
|
||||
{
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - audio manager handling terminate");
|
||||
@@ -712,8 +712,8 @@ static BOOL configured = FALSE;
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - audio manager got told background music finished");
|
||||
if (backgroundMusicCompletionSelector != nil) {
|
||||
[backgroundMusicCompletionListener performSelector:backgroundMusicCompletionSelector];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(void) beginInterruption {
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - begin interruption");
|
||||
@@ -730,78 +730,78 @@ static BOOL configured = FALSE;
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - interruption ended with flags %i",flags);
|
||||
if (flags == AVAudioSessionInterruptionFlags_ShouldResume) {
|
||||
[self audioSessionResumed];
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
-(void)audioSessionInterrupted
|
||||
{
|
||||
-(void)audioSessionInterrupted
|
||||
{
|
||||
if (!_interrupted) {
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Audio session interrupted");
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Audio session interrupted");
|
||||
_interrupted = YES;
|
||||
|
||||
// Deactivate the current audio session
|
||||
// Deactivate the current audio session
|
||||
[self audioSessionSetActive:NO];
|
||||
|
||||
|
||||
if (alcGetCurrentContext() != NULL) {
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Setting OpenAL context to NULL");
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Setting OpenAL context to NULL");
|
||||
|
||||
ALenum error = AL_NO_ERROR;
|
||||
|
||||
// set the current context to NULL will 'shutdown' openAL
|
||||
alcMakeContextCurrent(NULL);
|
||||
|
||||
// set the current context to NULL will 'shutdown' openAL
|
||||
alcMakeContextCurrent(NULL);
|
||||
|
||||
if((error = alGetError()) != AL_NO_ERROR) {
|
||||
CDLOG(@"Denshion::CDAudioManager - Error making context current %x\n", error);
|
||||
}
|
||||
}
|
||||
#pragma unused(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(void)audioSessionResumed
|
||||
{
|
||||
-(void)audioSessionResumed
|
||||
{
|
||||
if (_interrupted) {
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Audio session resumed");
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Audio session resumed");
|
||||
_interrupted = NO;
|
||||
|
||||
|
||||
BOOL activationResult = NO;
|
||||
// Reactivate the current audio session
|
||||
activationResult = [self audioSessionSetActive:YES];
|
||||
|
||||
activationResult = [self audioSessionSetActive:YES];
|
||||
|
||||
//This code is to handle a problem with iOS 4.0 and 4.01 where reactivating the session can fail if
|
||||
//task switching is performed too rapidly. A test case that reliably reproduces the issue is to call the
|
||||
//iPhone and then hang up after two rings (timing may vary ;))
|
||||
//Basically we keep waiting and trying to let the OS catch up with itself but the number of tries is
|
||||
//limited.
|
||||
if (!activationResult) {
|
||||
CDLOG(@"Denshion::CDAudioManager - Failure reactivating audio session, will try wait-try cycle");
|
||||
CDLOG(@"Denshion::CDAudioManager - Failure reactivating audio session, will try wait-try cycle");
|
||||
int activateCount = 0;
|
||||
while (!activationResult && activateCount < 10) {
|
||||
[NSThread sleepForTimeInterval:0.5];
|
||||
activationResult = [self audioSessionSetActive:YES];
|
||||
activationResult = [self audioSessionSetActive:YES];
|
||||
activateCount++;
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Reactivation attempt %i status = %i",activateCount,activationResult);
|
||||
}
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Reactivation attempt %i status = %i",activateCount,activationResult);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (alcGetCurrentContext() == NULL) {
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Restoring OpenAL context");
|
||||
CDLOGINFO(@"Denshion::CDAudioManager - Restoring OpenAL context");
|
||||
ALenum error = AL_NO_ERROR;
|
||||
// Restore open al context
|
||||
alcMakeContextCurrent([soundEngine openALContext]);
|
||||
// Restore open al context
|
||||
alcMakeContextCurrent([soundEngine openALContext]);
|
||||
if((error = alGetError()) != AL_NO_ERROR) {
|
||||
CDLOG(@"Denshion::CDAudioManager - Error making context current%x\n", error);
|
||||
}
|
||||
}
|
||||
#pragma unused(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+(void) end {
|
||||
[sharedManager release];
|
||||
sharedManager = nil;
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@@ -810,7 +810,7 @@ static BOOL configured = FALSE;
|
||||
|
||||
-(void) _setTargetProperty:(float) newVal {
|
||||
((CDLongAudioSource*)target).volume = newVal;
|
||||
}
|
||||
}
|
||||
|
||||
-(float) _getTargetProperty {
|
||||
return ((CDLongAudioSource*)target).volume;
|
||||
@@ -823,7 +823,7 @@ static BOOL configured = FALSE;
|
||||
|
||||
-(Class) _allowableType {
|
||||
return [CDLongAudioSource class];
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
///////////////////////////////////////////////////////////////////////////////////////
|
||||
@@ -835,18 +835,18 @@ static BOOL configured = FALSE;
|
||||
loadedBuffers = [[NSMutableDictionary alloc] initWithCapacity:CD_BUFFERS_START];
|
||||
freedBuffers = [[NSMutableArray alloc] init];
|
||||
nextBufferId = 0;
|
||||
}
|
||||
}
|
||||
return self;
|
||||
}
|
||||
}
|
||||
|
||||
-(void) dealloc {
|
||||
[loadedBuffers release];
|
||||
[freedBuffers release];
|
||||
[super dealloc];
|
||||
}
|
||||
}
|
||||
|
||||
-(int) bufferForFile:(NSString*) filePath create:(BOOL) create {
|
||||
|
||||
|
||||
NSNumber* soundId = (NSNumber*)[loadedBuffers objectForKey:filePath];
|
||||
if(soundId == nil)
|
||||
{
|
||||
@@ -855,7 +855,7 @@ static BOOL configured = FALSE;
|
||||
//First try to get a buffer from the free buffers
|
||||
if ([freedBuffers count] > 0) {
|
||||
bufferId = [[[freedBuffers lastObject] retain] autorelease];
|
||||
[freedBuffers removeLastObject];
|
||||
[freedBuffers removeLastObject];
|
||||
CDLOGINFO(@"Denshion::CDBufferManager reusing buffer id %i",[bufferId intValue]);
|
||||
} else {
|
||||
bufferId = [[NSNumber alloc] initWithInt:nextBufferId];
|
||||
@@ -863,7 +863,7 @@ static BOOL configured = FALSE;
|
||||
CDLOGINFO(@"Denshion::CDBufferManager generating new buffer id %i",[bufferId intValue]);
|
||||
nextBufferId++;
|
||||
}
|
||||
|
||||
|
||||
if ([soundEngine loadBuffer:[bufferId intValue] filePath:filePath]) {
|
||||
//File successfully loaded
|
||||
CDLOGINFO(@"Denshion::CDBufferManager buffer loaded %@ %@",bufferId,filePath);
|
||||
@@ -873,15 +873,15 @@ static BOOL configured = FALSE;
|
||||
//File didn't load, put buffer id on free list
|
||||
[freedBuffers addObject:bufferId];
|
||||
return kCDNoBuffer;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
//No matching buffer was found
|
||||
return kCDNoBuffer;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return [soundId intValue];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(void) releaseBufferForFile:(NSString *) filePath {
|
||||
int bufferId = [self bufferForFile:filePath create:NO];
|
||||
@@ -891,7 +891,9 @@ static BOOL configured = FALSE;
|
||||
NSNumber *freedBufferId = [[NSNumber alloc] initWithInt:bufferId];
|
||||
[freedBufferId autorelease];
|
||||
[freedBuffers addObject:freedBufferId];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@end
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
/*
|
||||
Copyright (c) 2010 Steve Oldmeadow
|
||||
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
@@ -18,7 +18,7 @@
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
|
||||
$Id$
|
||||
*/
|
||||
#define COCOSDENSHION_VERSION "Aphex.rc"
|
||||
@@ -35,25 +35,26 @@
|
||||
*/
|
||||
//Number of buffers slots that will be initially created
|
||||
#define CD_BUFFERS_START 64
|
||||
//Number of buffers that will be added
|
||||
//Number of buffers that will be added
|
||||
#define CD_BUFFERS_INCREMENT 16
|
||||
|
||||
/**
|
||||
If enabled, OpenAL code will use static buffers. When static buffers are used the audio
|
||||
data is managed outside of OpenAL, this eliminates a memcpy operation which leads to
|
||||
data is managed outside of OpenAL, this eliminates a memcpy operation which leads to
|
||||
higher performance when loading sounds.
|
||||
|
||||
|
||||
However, the downside is that when the audio data is freed you must
|
||||
be certain that it is no longer being accessed otherwise your app will crash. Testing on OS 2.2.1
|
||||
and 3.1.2 has shown that this may occur if a buffer is being used by a source with state = AL_PLAYING
|
||||
when the buffer is deleted. If the data is freed too quickly after the source is stopped then
|
||||
a crash will occur. The implemented workaround is that when static buffers are used the unloadBuffer code will wait for
|
||||
any playing sources to finish playing before the associated buffer and data are deleted, however, this delay may negate any
|
||||
any playing sources to finish playing before the associated buffer and data are deleted, however, this delay may negate any
|
||||
performance gains that are achieved during loading.
|
||||
|
||||
|
||||
Performance tests on a 1st gen iPod running OS 2.2.1 loading the CocosDenshionDemo sounds were ~0.14 seconds without
|
||||
static buffers and ~0.12 seconds when using static buffers.
|
||||
|
||||
*/
|
||||
//#define CD_USE_STATIC_BUFFERS 1
|
||||
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
/*
|
||||
|
||||
|
||||
Disclaimer: IMPORTANT: This Apple software is supplied to you by
|
||||
Apple Inc. ("Apple") in consideration of your agreement to the
|
||||
following terms, and your use, installation, modification or
|
||||
redistribution of this Apple software constitutes acceptance of these
|
||||
terms. If you do not agree with these terms, please do not use,
|
||||
install, modify or redistribute this Apple software.
|
||||
|
||||
|
||||
In consideration of your agreement to abide by the following terms, and
|
||||
subject to these terms, Apple grants you a personal, non-exclusive
|
||||
license, under Apple's copyrights in this original Apple software (the
|
||||
@@ -22,13 +22,13 @@
|
||||
or implied, are granted by Apple herein, including but not limited to
|
||||
any patent rights that may be infringed by your derivative works or by
|
||||
other works in which the Apple Software may be incorporated.
|
||||
|
||||
|
||||
The Apple Software is provided by Apple on an "AS IS" basis. APPLE
|
||||
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
|
||||
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
|
||||
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
|
||||
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
|
||||
|
||||
|
||||
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
|
||||
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
@@ -37,9 +37,9 @@
|
||||
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
|
||||
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
Copyright (C) 2009 Apple Inc. All Rights Reserved.
|
||||
|
||||
|
||||
$Id$
|
||||
*/
|
||||
|
||||
@@ -55,8 +55,8 @@
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
#import <OpenAL/al.h>
|
||||
#import <OpenAL/alc.h>
|
||||
@@ -67,10 +67,11 @@ extern "C" {
|
||||
void* CDloadWaveAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate);
|
||||
void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate);
|
||||
void* CDGetOpenALAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate);
|
||||
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
/*
|
||||
|
||||
|
||||
Disclaimer: IMPORTANT: This Apple software is supplied to you by
|
||||
Apple Inc. ("Apple") in consideration of your agreement to the
|
||||
following terms, and your use, installation, modification or
|
||||
redistribution of this Apple software constitutes acceptance of these
|
||||
terms. If you do not agree with these terms, please do not use,
|
||||
install, modify or redistribute this Apple software.
|
||||
|
||||
|
||||
In consideration of your agreement to abide by the following terms, and
|
||||
subject to these terms, Apple grants you a personal, non-exclusive
|
||||
license, under Apple's copyrights in this original Apple software (the
|
||||
@@ -22,13 +22,13 @@
|
||||
or implied, are granted by Apple herein, including but not limited to
|
||||
any patent rights that may be infringed by your derivative works or by
|
||||
other works in which the Apple Software may be incorporated.
|
||||
|
||||
|
||||
The Apple Software is provided by Apple on an "AS IS" basis. APPLE
|
||||
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
|
||||
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
|
||||
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
|
||||
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
|
||||
|
||||
|
||||
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
|
||||
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
@@ -37,9 +37,9 @@
|
||||
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
|
||||
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
Copyright (C) 2009 Apple Inc. All Rights Reserved.
|
||||
|
||||
|
||||
$Id: CDOpenALSupport.h 16 2010-03-11 06:22:10Z steveoldmeadow $
|
||||
*/
|
||||
|
||||
@@ -51,38 +51,38 @@
|
||||
//Taken from oalTouch MyOpenALSupport 1.1
|
||||
void* CDloadWaveAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate)
|
||||
{
|
||||
OSStatus err = noErr;
|
||||
OSStatus err = noErr;
|
||||
UInt64 fileDataSize = 0;
|
||||
AudioStreamBasicDescription theFileFormat;
|
||||
UInt32 thePropertySize = sizeof(theFileFormat);
|
||||
AudioFileID afid = 0;
|
||||
void* theData = NULL;
|
||||
|
||||
|
||||
// Open a file with ExtAudioFileOpen()
|
||||
err = AudioFileOpenURL(inFileURL, kAudioFileReadPermission, 0, &afid);
|
||||
if(err) { CDLOG(@"MyGetOpenALAudioData: AudioFileOpenURL FAILED, Error = %ld\n", err); goto Exit; }
|
||||
|
||||
|
||||
// Get the audio data format
|
||||
err = AudioFileGetProperty(afid, kAudioFilePropertyDataFormat, &thePropertySize, &theFileFormat);
|
||||
if(err) { CDLOG(@"MyGetOpenALAudioData: AudioFileGetProperty(kAudioFileProperty_DataFormat) FAILED, Error = %ld\n", err); goto Exit; }
|
||||
|
||||
if (theFileFormat.mChannelsPerFrame > 2) {
|
||||
|
||||
if (theFileFormat.mChannelsPerFrame > 2) {
|
||||
CDLOG(@"MyGetOpenALAudioData - Unsupported Format, channel count is greater than stereo\n"); goto Exit;
|
||||
}
|
||||
|
||||
if ((theFileFormat.mFormatID != kAudioFormatLinearPCM) || (!TestAudioFormatNativeEndian(theFileFormat))) {
|
||||
|
||||
if ((theFileFormat.mFormatID != kAudioFormatLinearPCM) || (!TestAudioFormatNativeEndian(theFileFormat))) {
|
||||
CDLOG(@"MyGetOpenALAudioData - Unsupported Format, must be little-endian PCM\n"); goto Exit;
|
||||
}
|
||||
|
||||
if ((theFileFormat.mBitsPerChannel != 8) && (theFileFormat.mBitsPerChannel != 16)) {
|
||||
|
||||
if ((theFileFormat.mBitsPerChannel != 8) && (theFileFormat.mBitsPerChannel != 16)) {
|
||||
CDLOG(@"MyGetOpenALAudioData - Unsupported Format, must be 8 or 16 bit PCM\n"); goto Exit;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
thePropertySize = sizeof(fileDataSize);
|
||||
err = AudioFileGetProperty(afid, kAudioFilePropertyAudioDataByteCount, &thePropertySize, &fileDataSize);
|
||||
if(err) { CDLOG(@"MyGetOpenALAudioData: AudioFileGetProperty(kAudioFilePropertyAudioDataByteCount) FAILED, Error = %ld\n", err); goto Exit; }
|
||||
|
||||
|
||||
// Read all the data into memory
|
||||
UInt32 dataSize = (UInt32)fileDataSize;
|
||||
theData = malloc(dataSize);
|
||||
@@ -95,22 +95,22 @@ void* CDloadWaveAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outD
|
||||
// success
|
||||
*outDataSize = (ALsizei)dataSize;
|
||||
//This fix was added by me, however, 8 bit sounds have a clipping sound at the end so aren't really usable (SO)
|
||||
if (theFileFormat.mBitsPerChannel == 16) {
|
||||
if (theFileFormat.mBitsPerChannel == 16) {
|
||||
*outDataFormat = (theFileFormat.mChannelsPerFrame > 1) ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16;
|
||||
} else {
|
||||
*outDataFormat = (theFileFormat.mChannelsPerFrame > 1) ? AL_FORMAT_STEREO8 : AL_FORMAT_MONO8;
|
||||
}
|
||||
*outDataFormat = (theFileFormat.mChannelsPerFrame > 1) ? AL_FORMAT_STEREO8 : AL_FORMAT_MONO8;
|
||||
}
|
||||
*outSampleRate = (ALsizei)theFileFormat.mSampleRate;
|
||||
}
|
||||
else
|
||||
{
|
||||
else
|
||||
{
|
||||
// failure
|
||||
free (theData);
|
||||
theData = NULL; // make sure to return NULL
|
||||
CDLOG(@"MyGetOpenALAudioData: ExtAudioFileRead FAILED, Error = %ld\n", err); goto Exit;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Exit:
|
||||
// Dispose the ExtAudioFileRef, it is no longer needed
|
||||
if (afid) AudioFileClose(afid);
|
||||
@@ -129,7 +129,7 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa
|
||||
void* theData = NULL;
|
||||
AudioStreamBasicDescription theOutputFormat;
|
||||
UInt32 dataSize = 0;
|
||||
|
||||
|
||||
// Open a file with ExtAudioFileOpen()
|
||||
status = ExtAudioFileOpenURL(inFileURL, &extRef);
|
||||
if (status != noErr)
|
||||
@@ -139,7 +139,7 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa
|
||||
}
|
||||
if (abort)
|
||||
goto Exit;
|
||||
|
||||
|
||||
// Get the audio data format
|
||||
status = ExtAudioFileGetProperty(extRef, kExtAudioFileProperty_FileDataFormat, &thePropertySize, &theFileFormat);
|
||||
if (status != noErr)
|
||||
@@ -149,7 +149,7 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa
|
||||
}
|
||||
if (abort)
|
||||
goto Exit;
|
||||
|
||||
|
||||
if (theFileFormat.mChannelsPerFrame > 2)
|
||||
{
|
||||
CDLOG(@"MyGetOpenALAudioData - Unsupported Format, channel count is greater than stereo\n");
|
||||
@@ -157,19 +157,19 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa
|
||||
}
|
||||
if (abort)
|
||||
goto Exit;
|
||||
|
||||
|
||||
// Set the client format to 16 bit signed integer (native-endian) data
|
||||
// Maintain the channel count and sample rate of the original source format
|
||||
theOutputFormat.mSampleRate = theFileFormat.mSampleRate;
|
||||
theOutputFormat.mChannelsPerFrame = theFileFormat.mChannelsPerFrame;
|
||||
|
||||
|
||||
theOutputFormat.mFormatID = kAudioFormatLinearPCM;
|
||||
theOutputFormat.mBytesPerPacket = 2 * theOutputFormat.mChannelsPerFrame;
|
||||
theOutputFormat.mFramesPerPacket = 1;
|
||||
theOutputFormat.mBytesPerFrame = 2 * theOutputFormat.mChannelsPerFrame;
|
||||
theOutputFormat.mBitsPerChannel = 16;
|
||||
theOutputFormat.mFormatFlags = kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked | kAudioFormatFlagIsSignedInteger;
|
||||
|
||||
|
||||
// Set the desired client (output) data format
|
||||
status = ExtAudioFileSetProperty(extRef, kExtAudioFileProperty_ClientDataFormat, sizeof(theOutputFormat), &theOutputFormat);
|
||||
if (status != noErr)
|
||||
@@ -179,7 +179,7 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa
|
||||
}
|
||||
if (abort)
|
||||
goto Exit;
|
||||
|
||||
|
||||
// Get the total frame count
|
||||
thePropertySize = sizeof(theFileLengthInFrames);
|
||||
status = ExtAudioFileGetProperty(extRef, kExtAudioFileProperty_FileLengthFrames, &thePropertySize, &theFileLengthInFrames);
|
||||
@@ -190,7 +190,7 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa
|
||||
}
|
||||
if (abort)
|
||||
goto Exit;
|
||||
|
||||
|
||||
// Read all the data into memory
|
||||
dataSize = (UInt32) theFileLengthInFrames * theOutputFormat.mBytesPerFrame;
|
||||
theData = malloc(dataSize);
|
||||
@@ -202,7 +202,7 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa
|
||||
theDataBuffer.mBuffers[0].mDataByteSize = dataSize;
|
||||
theDataBuffer.mBuffers[0].mNumberChannels = theOutputFormat.mChannelsPerFrame;
|
||||
theDataBuffer.mBuffers[0].mData = theData;
|
||||
|
||||
|
||||
// Read the data into an AudioBufferList
|
||||
status = ExtAudioFileRead(extRef, (UInt32*)&theFileLengthInFrames, &theDataBuffer);
|
||||
if(status == noErr)
|
||||
@@ -223,7 +223,7 @@ void* CDloadCafAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDa
|
||||
}
|
||||
if (abort)
|
||||
goto Exit;
|
||||
|
||||
|
||||
Exit:
|
||||
// Dispose the ExtAudioFileRef, it is no longer needed
|
||||
if (extRef) ExtAudioFileDispose(extRef);
|
||||
@@ -231,18 +231,18 @@ Exit:
|
||||
}
|
||||
|
||||
void* CDGetOpenALAudioData(CFURLRef inFileURL, ALsizei *outDataSize, ALenum *outDataFormat, ALsizei* outSampleRate) {
|
||||
|
||||
|
||||
CFStringRef extension = CFURLCopyPathExtension(inFileURL);
|
||||
CFComparisonResult isWavFile = 0;
|
||||
if (extension != NULL) {
|
||||
isWavFile = CFStringCompare (extension,(CFStringRef)@"wav", kCFCompareCaseInsensitive);
|
||||
CFRelease(extension);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (isWavFile == kCFCompareEqualTo) {
|
||||
return CDloadWaveAudioData(inFileURL, outDataSize, outDataFormat, outSampleRate);
|
||||
return CDloadWaveAudioData(inFileURL, outDataSize, outDataFormat, outSampleRate);
|
||||
} else {
|
||||
return CDloadCafAudioData(inFileURL, outDataSize, outDataFormat, outSampleRate);
|
||||
return CDloadCafAudioData(inFileURL, outDataSize, outDataFormat, outSampleRate);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
/*
|
||||
Copyright (c) 2010 Steve Oldmeadow
|
||||
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
@@ -18,14 +18,14 @@
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
|
||||
$Id$
|
||||
*/
|
||||
|
||||
/**
|
||||
A set of proxy classes to allow iOS audio code to run on MacOS X. CCAudioPlayer is implemented using NSSound.
|
||||
AVAudioSession is a "do nothing" class as it isn't really relevant on MacOS X.
|
||||
|
||||
|
||||
Limitations:
|
||||
CCAudioPlayer numberOfLoops not correctly supported. Looping is either on or off, can not specify a specific number of loops.
|
||||
CCAudioPlayer panning not supported.
|
||||
@@ -41,14 +41,14 @@
|
||||
#import <AppKit/NSSound.h>
|
||||
|
||||
enum AudioSessionProperties {
|
||||
kAudioSessionProperty_OtherAudioIsPlaying,
|
||||
kAudioSessionProperty_AudioRoute
|
||||
kAudioSessionProperty_OtherAudioIsPlaying,
|
||||
kAudioSessionProperty_AudioRoute
|
||||
};
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
extern OSStatus AudioSessionGetProperty(UInt32 inID, UInt32 *ioDataSize, void *outData);
|
||||
#endif
|
||||
|
||||
extern OSStatus AudioSessionGetProperty(UInt32 inID, UInt32 *ioDataSize, void *outData);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
@@ -61,21 +61,21 @@ extern OSStatus AudioSessionGetProperty(UInt32 inID, UInt32 *ioDataSize, void *o
|
||||
|
||||
/* This class is available with iPhone 2.2 or later */
|
||||
@interface CCAudioPlayer : NSObject <NSSoundDelegate> {
|
||||
|
||||
// properties
|
||||
id<AVAudioPlayerDelegate> delegate;
|
||||
NSUInteger numberOfChannels;
|
||||
BOOL playing;
|
||||
NSTimeInterval duration;
|
||||
NSURL *url;
|
||||
NSData *data;
|
||||
float pan;
|
||||
float volume;
|
||||
NSTimeInterval currentTime;
|
||||
NSTimeInterval deviceCurrentTime;
|
||||
NSInteger numberOfLoops;
|
||||
BOOL meteringEnabled;
|
||||
|
||||
|
||||
// properties
|
||||
id<AVAudioPlayerDelegate> delegate;
|
||||
NSUInteger numberOfChannels;
|
||||
BOOL playing;
|
||||
NSTimeInterval duration;
|
||||
NSURL *url;
|
||||
NSData *data;
|
||||
float pan;
|
||||
float volume;
|
||||
NSTimeInterval currentTime;
|
||||
NSTimeInterval deviceCurrentTime;
|
||||
NSInteger numberOfLoops;
|
||||
BOOL meteringEnabled;
|
||||
|
||||
|
||||
@private
|
||||
NSSound* _player;
|
||||
@@ -91,11 +91,11 @@ extern OSStatus AudioSessionGetProperty(UInt32 inID, UInt32 *ioDataSize, void *o
|
||||
|
||||
/* transport control */
|
||||
/* methods that return BOOL return YES on success and NO on failure. */
|
||||
- (BOOL)prepareToPlay; /* get ready to play the sound. happens automatically on play. */
|
||||
- (BOOL)play; /* sound is played asynchronously. */
|
||||
- (BOOL)prepareToPlay; /* get ready to play the sound. happens automatically on play. */
|
||||
- (BOOL)play; /* sound is played asynchronously. */
|
||||
- (BOOL)playAtTime:(NSTimeInterval) time; /* play a sound some time in the future. time should be greater than deviceCurrentTime. */
|
||||
- (void)pause; /* pauses playback, but remains ready to play. */
|
||||
- (void)stop; /* stops playback. no longer ready to play. */
|
||||
- (void)pause; /* pauses playback, but remains ready to play. */
|
||||
- (void)stop; /* stops playback. no longer ready to play. */
|
||||
- (BOOL) resume;
|
||||
|
||||
/* properties */
|
||||
@@ -105,7 +105,7 @@ extern OSStatus AudioSessionGetProperty(UInt32 inID, UInt32 *ioDataSize, void *o
|
||||
@property(readonly) NSUInteger numberOfChannels;
|
||||
@property(readonly) NSTimeInterval duration; /* the duration of the sound. */
|
||||
|
||||
@property(assign) id<AVAudioPlayerDelegate> delegate; /* the delegate will be sent playerDidFinishPlaying */
|
||||
@property(assign) id<AVAudioPlayerDelegate> delegate; /* the delegate will be sent playerDidFinishPlaying */
|
||||
|
||||
/* one of these three properties will be non-nil based on the init... method used */
|
||||
@property(readonly) NSURL *url; /* returns nil if object was not created with a URL */
|
||||
@@ -113,14 +113,14 @@ extern OSStatus AudioSessionGetProperty(UInt32 inID, UInt32 *ioDataSize, void *o
|
||||
@property float pan; /* set panning. -1.0 is left, 0.0 is center, 1.0 is right. */
|
||||
@property float volume; /* The volume for the sound. The nominal range is from 0.0 to 1.0. */
|
||||
|
||||
/* If the sound is playing, currentTime is the offset into the sound of the current playback position.
|
||||
/* If the sound is playing, currentTime is the offset into the sound of the current playback position.
|
||||
If the sound is not playing, currentTime is the offset into the sound where playing would start. */
|
||||
@property NSTimeInterval currentTime;
|
||||
|
||||
/* returns the current time associated with the output device */
|
||||
@property(readonly) NSTimeInterval deviceCurrentTime;
|
||||
@property(readonly) NSTimeInterval deviceCurrentTime;
|
||||
|
||||
/* "numberOfLoops" is the number of times that the sound will return to the beginning upon reaching the end.
|
||||
/* "numberOfLoops" is the number of times that the sound will return to the beginning upon reaching the end.
|
||||
A value of zero means to play the sound just once.
|
||||
A value of one will result in playing the sound twice, and so on..
|
||||
Any negative number will loop indefinitely until stopped.
|
||||
@@ -139,7 +139,7 @@ extern OSStatus AudioSessionGetProperty(UInt32 inID, UInt32 *ioDataSize, void *o
|
||||
|
||||
/* A protocol for delegates of CCAudioPlayer */
|
||||
@protocol AVAudioPlayerDelegate <NSObject>
|
||||
@optional
|
||||
@optional
|
||||
/* audioPlayerDidFinishPlaying:successfully: is called when a sound has finished playing. This method is NOT called if the player is stopped due to an interruption. */
|
||||
- (void)audioPlayerDidFinishPlaying:(CCAudioPlayer *)player successfully:(BOOL)flag;
|
||||
|
||||
@@ -175,25 +175,25 @@ extern NSString *const AVAudioSessionCategoryPlayAndRecord;
|
||||
extern NSString *const AVAudioSessionCategoryAudioProcessing;
|
||||
|
||||
enum {
|
||||
AVAudioSessionInterruptionFlags_ShouldResume = 1
|
||||
AVAudioSessionInterruptionFlags_ShouldResume = 1
|
||||
};
|
||||
|
||||
enum {
|
||||
AVAudioSessionSetActiveFlags_NotifyOthersOnDeactivation = 1
|
||||
enum {
|
||||
AVAudioSessionSetActiveFlags_NotifyOthersOnDeactivation = 1
|
||||
};
|
||||
|
||||
@interface AVAudioSession : NSObject {
|
||||
|
||||
// properties
|
||||
NSString* category;
|
||||
double preferredHardwareSampleRate;
|
||||
NSTimeInterval preferredIOBufferDuration;
|
||||
|
||||
BOOL inputIsAvailable;
|
||||
double currentHardwareSampleRate;
|
||||
NSInteger currentHardwareInputNumberOfChannels;
|
||||
NSInteger currentHardwareOutputNumberOfChannels;
|
||||
id<AVAudioSessionDelegate> delegate;
|
||||
|
||||
// properties
|
||||
NSString* category;
|
||||
double preferredHardwareSampleRate;
|
||||
NSTimeInterval preferredIOBufferDuration;
|
||||
|
||||
BOOL inputIsAvailable;
|
||||
double currentHardwareSampleRate;
|
||||
NSInteger currentHardwareInputNumberOfChannels;
|
||||
NSInteger currentHardwareOutputNumberOfChannels;
|
||||
id<AVAudioSessionDelegate> delegate;
|
||||
|
||||
@private
|
||||
__strong void *_impl;
|
||||
@@ -225,7 +225,7 @@ enum {
|
||||
|
||||
/* A protocol for delegates of AVAudioSession */
|
||||
@protocol AVAudioSessionDelegate <NSObject>
|
||||
@optional
|
||||
@optional
|
||||
|
||||
- (void)beginInterruption;
|
||||
|
||||
@@ -237,4 +237,3 @@ enum {
|
||||
@end
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
/*
|
||||
Copyright (c) 2010 Steve Oldmeadow
|
||||
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
@@ -18,7 +18,7 @@
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
|
||||
$Id$
|
||||
*/
|
||||
|
||||
@@ -40,7 +40,7 @@ NSString *const AVAudioSessionCategoryAudioProcessing = @"AVAudioSessionCategory
|
||||
OSStatus AudioSessionGetProperty(UInt32 inID, UInt32 *ioDataSize, void *outData) {
|
||||
//TODO: set outData appropriately
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
@implementation CCAudioPlayer
|
||||
|
||||
@@ -52,18 +52,18 @@ OSStatus AudioSessionGetProperty(UInt32 inID, UInt32 *ioDataSize, void *outData)
|
||||
if (_player != nil) {
|
||||
_player.delegate = self;
|
||||
CDLOG(@"Denshion::CDXMacOSXSupport - NSSound allocated for %@", theUrl);
|
||||
}
|
||||
}
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (id)initWithData:(NSData *)theData error:(NSError **)outError {
|
||||
- (id)initWithData:(NSData *)theData error:(NSError **)outError {
|
||||
if ((self = [super init])) {
|
||||
_player = [[NSSound alloc] initWithData:theData];
|
||||
if (_player != nil) {
|
||||
_player.delegate = self;
|
||||
CDLOG(@"Denshion::CDXMacOSXSupport - NSSound allocated for %@", theData);
|
||||
}
|
||||
}
|
||||
}
|
||||
return self;
|
||||
}
|
||||
@@ -72,21 +72,21 @@ OSStatus AudioSessionGetProperty(UInt32 inID, UInt32 *ioDataSize, void *outData)
|
||||
-(void) dealloc {
|
||||
[_player release];
|
||||
[super dealloc];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)sound:(NSSound *)sound didFinishPlaying:(BOOL)finished {
|
||||
if (self.delegate && [self.delegate respondsToSelector:@selector(audioPlayerDidFinishPlaying:successfully:)]) {
|
||||
[self.delegate audioPlayerDidFinishPlaying:self successfully:finished];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
- (BOOL)play {
|
||||
BOOL result;
|
||||
result = [_player play];
|
||||
if (!result) {
|
||||
//May be paused, try resuming instead
|
||||
//May be paused, try resuming instead
|
||||
result = [_player resume];
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -98,15 +98,15 @@ OSStatus AudioSessionGetProperty(UInt32 inID, UInt32 *ioDataSize, void *outData)
|
||||
|
||||
-(void) pause {
|
||||
[_player pause];
|
||||
}
|
||||
}
|
||||
|
||||
-(void) stop {
|
||||
[_player stop];
|
||||
}
|
||||
}
|
||||
|
||||
-(BOOL) isPlaying {
|
||||
return [_player isPlaying];
|
||||
}
|
||||
}
|
||||
|
||||
-(void) setVolume:(float) vol {
|
||||
[_player setVolume:vol];
|
||||
@@ -114,23 +114,23 @@ OSStatus AudioSessionGetProperty(UInt32 inID, UInt32 *ioDataSize, void *outData)
|
||||
|
||||
-(float) volume {
|
||||
return [_player volume];
|
||||
}
|
||||
}
|
||||
|
||||
-(void) setNumberOfLoops:(NSInteger) nOfLoops {
|
||||
if (nOfLoops < 0) {
|
||||
[_player setLoops:YES];
|
||||
} else {
|
||||
[_player setLoops:NO];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(NSInteger) numberOfLoops {
|
||||
if (_player.loops) {
|
||||
return -1;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(void) setCurrentTime:(NSTimeInterval) aCurrentTime {
|
||||
[_player setCurrentTime:aCurrentTime];
|
||||
@@ -147,17 +147,17 @@ OSStatus AudioSessionGetProperty(UInt32 inID, UInt32 *ioDataSize, void *outData)
|
||||
#pragma mark unsupported
|
||||
- (BOOL)prepareToPlay {
|
||||
return YES;
|
||||
}
|
||||
}
|
||||
-(BOOL)playAtTime:(NSTimeInterval)time {
|
||||
return YES;
|
||||
}
|
||||
}
|
||||
-(void) setMeteringEnabled:(BOOL) enabled {
|
||||
}
|
||||
}
|
||||
-(BOOL) isMeteringEnabled {
|
||||
return NO;
|
||||
}
|
||||
}
|
||||
- (void)updateMeters{}
|
||||
- (float)peakPowerForChannel:(NSUInteger)channelNumber{return 0.0f;}
|
||||
- (float)peakPowerForChannel:(NSUInteger)channelNumber{return 0.0f;}
|
||||
- (float)averagePowerForChannel:(NSUInteger)channelNumber{return 0.0f;}
|
||||
@end
|
||||
|
||||
@@ -170,7 +170,7 @@ OSStatus AudioSessionGetProperty(UInt32 inID, UInt32 *ioDataSize, void *outData)
|
||||
|
||||
+ (id)sharedInstance {
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
|
||||
- (BOOL)setActive:(BOOL)beActive error:(NSError**)outError {return YES;}
|
||||
- (BOOL)setActive:(BOOL)beActive withFlags:(NSInteger)flags error:(NSError**)outError {return YES;}
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
/*
|
||||
Copyright (c) 2010 Steve Oldmeadow
|
||||
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
@@ -18,16 +18,16 @@
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
|
||||
$Id$
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/**
|
||||
/**
|
||||
@file
|
||||
@b IMPORTANT
|
||||
There are 3 different ways of using CocosDenshion. Depending on which you choose you
|
||||
There are 3 different ways of using CocosDenshion. Depending on which you choose you
|
||||
will need to include different files and frameworks.
|
||||
|
||||
@par SimpleAudioEngine
|
||||
@@ -36,36 +36,36 @@ and some background music and have no interest in learning the lower level worki
|
||||
this is the interface to use.
|
||||
|
||||
Requirements:
|
||||
- Firmware: OS 2.2 or greater
|
||||
- Firmware: OS 2.2 or greater
|
||||
- Files: SimpleAudioEngine.*, CocosDenshion.*
|
||||
- Frameworks: OpenAL, AudioToolbox, AVFoundation
|
||||
|
||||
|
||||
@par CDAudioManager
|
||||
CDAudioManager is basically a thin wrapper around an CCAudioPlayer object used for playing
|
||||
background music and a CDSoundEngine object used for playing sound effects. It manages the
|
||||
audio session for you deals with audio session interruption. It is fairly low level and it
|
||||
is expected you have some understanding of the underlying technologies. For example, for
|
||||
is expected you have some understanding of the underlying technologies. For example, for
|
||||
many use cases regarding background music it is expected you will work directly with the
|
||||
backgroundMusic CCAudioPlayer which is exposed as a property.
|
||||
|
||||
|
||||
Requirements:
|
||||
- Firmware: OS 2.2 or greater
|
||||
- Firmware: OS 2.2 or greater
|
||||
- Files: CDAudioManager.*, CocosDenshion.*
|
||||
- Frameworks: OpenAL, AudioToolbox, AVFoundation
|
||||
|
||||
@par CDSoundEngine
|
||||
CDSoundEngine is a sound engine built upon OpenAL and derived from Apple's oalTouch
|
||||
CDSoundEngine is a sound engine built upon OpenAL and derived from Apple's oalTouch
|
||||
example. It can playback up to 32 sounds simultaneously with control over pitch, pan
|
||||
and gain. It can be set up to handle audio session interruption automatically. You
|
||||
and gain. It can be set up to handle audio session interruption automatically. You
|
||||
may decide to use CDSoundEngine directly instead of CDAudioManager or SimpleAudioEngine
|
||||
because you require OS 2.0 compatibility.
|
||||
|
||||
|
||||
Requirements:
|
||||
- Firmware: OS 2.0 or greater
|
||||
- Firmware: OS 2.0 or greater
|
||||
- Files: CocosDenshion.*
|
||||
- Frameworks: OpenAL, AudioToolbox
|
||||
|
||||
*/
|
||||
|
||||
*/
|
||||
|
||||
#import <OpenAL/al.h>
|
||||
#import <OpenAL/alc.h>
|
||||
@@ -136,13 +136,13 @@ typedef struct _bufferInfo {
|
||||
ALenum format;
|
||||
ALsizei sizeInBytes;
|
||||
ALsizei frequencyInHertz;
|
||||
} bufferInfo;
|
||||
} bufferInfo;
|
||||
|
||||
typedef struct _sourceInfo {
|
||||
bool usable;
|
||||
ALuint sourceId;
|
||||
ALuint attachedBufferId;
|
||||
} sourceInfo;
|
||||
} sourceInfo;
|
||||
|
||||
#pragma mark CDAudioTransportProtocol
|
||||
|
||||
@@ -176,7 +176,7 @@ typedef struct _sourceInfo {
|
||||
*/
|
||||
@interface CDUtilities : NSObject
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/** Fundamentally the same as the corresponding method is FileUtils but added to break binding to cocos2d */
|
||||
+(NSString*) fullPathFromRelativePath:(NSString*) relPath;
|
||||
@@ -187,22 +187,22 @@ typedef struct _sourceInfo {
|
||||
#pragma mark CDSoundEngine
|
||||
|
||||
/** CDSoundEngine is built upon OpenAL and works with SDK 2.0.
|
||||
CDSoundEngine is a sound engine built upon OpenAL and derived from Apple's oalTouch
|
||||
CDSoundEngine is a sound engine built upon OpenAL and derived from Apple's oalTouch
|
||||
example. It can playback up to 32 sounds simultaneously with control over pitch, pan
|
||||
and gain. It can be set up to handle audio session interruption automatically. You
|
||||
and gain. It can be set up to handle audio session interruption automatically. You
|
||||
may decide to use CDSoundEngine directly instead of CDAudioManager or SimpleAudioEngine
|
||||
because you require OS 2.0 compatibility.
|
||||
|
||||
|
||||
Requirements:
|
||||
- Firmware: OS 2.0 or greater
|
||||
- Firmware: OS 2.0 or greater
|
||||
- Files: CocosDenshion.*
|
||||
- Frameworks: OpenAL, AudioToolbox
|
||||
|
||||
|
||||
@since v0.8
|
||||
*/
|
||||
@class CDSoundSource;
|
||||
@interface CDSoundEngine : NSObject <CDAudioInterruptProtocol> {
|
||||
|
||||
|
||||
bufferInfo *_buffers;
|
||||
sourceInfo *_sources;
|
||||
sourceGroup *_sourceGroups;
|
||||
@@ -219,11 +219,11 @@ typedef struct _sourceInfo {
|
||||
BOOL functioning_;
|
||||
float asynchLoadProgress_;
|
||||
BOOL getGainWorks_;
|
||||
|
||||
|
||||
//For managing dynamic allocation of sources and buffers
|
||||
int sourceTotal_;
|
||||
int bufferTotal;
|
||||
|
||||
|
||||
}
|
||||
|
||||
@property (readwrite, nonatomic) ALfloat masterGain;
|
||||
@@ -288,10 +288,10 @@ typedef struct _sourceInfo {
|
||||
|
||||
#pragma mark CDSoundSource
|
||||
/** CDSoundSource is a wrapper around an OpenAL sound source.
|
||||
It allows you to manipulate properties such as pitch, gain, pan and looping while the
|
||||
It allows you to manipulate properties such as pitch, gain, pan and looping while the
|
||||
sound is playing. CDSoundSource is based on the old CDSourceWrapper class but with much
|
||||
added functionality.
|
||||
|
||||
|
||||
@since v1.0
|
||||
*/
|
||||
@interface CDSoundSource : NSObject <CDAudioTransportProtocol, CDAudioInterruptProtocol> {
|
||||
@@ -324,7 +324,7 @@ typedef struct _sourceInfo {
|
||||
#pragma mark CDAudioInterruptTargetGroup
|
||||
|
||||
/** Container for objects that implement audio interrupt protocol i.e. they can be muted and enabled.
|
||||
Setting mute and enabled for the group propagates to all children.
|
||||
Setting mute and enabled for the group propagates to all children.
|
||||
Designed to be used with your CDSoundSource objects to get them to comply with global enabled and mute settings
|
||||
if that is what you want to do.*/
|
||||
@interface CDAudioInterruptTargetGroup : NSObject <CDAudioInterruptProtocol> {
|
||||
@@ -343,7 +343,7 @@ typedef struct _sourceInfo {
|
||||
@interface CDAsynchBufferLoader : NSOperation {
|
||||
NSArray *_loadRequests;
|
||||
CDSoundEngine *_soundEngine;
|
||||
}
|
||||
}
|
||||
|
||||
-(id) init:(NSArray *)loadRequests soundEngine:(CDSoundEngine *) theSoundEngine;
|
||||
|
||||
@@ -401,7 +401,7 @@ typedef enum {
|
||||
float endValue;
|
||||
id target;
|
||||
BOOL stopTargetWhenComplete;
|
||||
|
||||
|
||||
}
|
||||
@property (readwrite, nonatomic) BOOL stopTargetWhenComplete;
|
||||
@property (readwrite, nonatomic) float startValue;
|
||||
@@ -443,3 +443,6 @@ typedef enum {
|
||||
@interface CDSoundEngineFader : CDPropertyModifier{}
|
||||
@end
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -57,7 +57,7 @@ static void static_pauseBackgroundMusic()
|
||||
static void static_resumeBackgroundMusic()
|
||||
{
|
||||
[[SimpleAudioEngine sharedEngine] resumeBackgroundMusic];
|
||||
}
|
||||
}
|
||||
|
||||
static void static_rewindBackgroundMusic()
|
||||
{
|
||||
@@ -84,12 +84,12 @@ static void static_setBackgroundMusicVolume(float volume)
|
||||
volume = MAX( MIN(volume, 1.0), 0 );
|
||||
[SimpleAudioEngine sharedEngine].backgroundMusicVolume = volume;
|
||||
}
|
||||
|
||||
|
||||
static float static_getEffectsVolume()
|
||||
{
|
||||
return [[SimpleAudioEngine sharedEngine] effectsVolume];
|
||||
}
|
||||
|
||||
|
||||
static void static_setEffectsVolume(float volume)
|
||||
{
|
||||
volume = MAX( MIN(volume, 1.0), 0 );
|
||||
@@ -100,17 +100,17 @@ static unsigned int static_playEffect(const char* pszFilePath, bool bLoop, Float
|
||||
{
|
||||
return [[SimpleAudioEngine sharedEngine] playEffect:[NSString stringWithUTF8String: pszFilePath] loop:bLoop pitch:pszPitch pan: pszPan gain:pszGain ];
|
||||
}
|
||||
|
||||
|
||||
static void static_stopEffect(int nSoundId)
|
||||
{
|
||||
[[SimpleAudioEngine sharedEngine] stopEffect: nSoundId];
|
||||
}
|
||||
|
||||
|
||||
static void static_preloadEffect(const char* pszFilePath)
|
||||
{
|
||||
[[SimpleAudioEngine sharedEngine] preloadEffect: [NSString stringWithUTF8String: pszFilePath]];
|
||||
}
|
||||
|
||||
|
||||
static void static_unloadEffect(const char* pszFilePath)
|
||||
{
|
||||
[[SimpleAudioEngine sharedEngine] unloadEffect: [NSString stringWithUTF8String: pszFilePath]];
|
||||
@@ -161,7 +161,7 @@ SimpleAudioEngine* SimpleAudioEngine::getInstance()
|
||||
{
|
||||
s_pEngine = new (std::nothrow) SimpleAudioEngine();
|
||||
}
|
||||
|
||||
|
||||
return s_pEngine;
|
||||
}
|
||||
|
||||
@@ -172,7 +172,7 @@ void SimpleAudioEngine::end()
|
||||
delete s_pEngine;
|
||||
s_pEngine = nullptr;
|
||||
}
|
||||
|
||||
|
||||
static_end();
|
||||
}
|
||||
|
||||
@@ -203,7 +203,7 @@ void SimpleAudioEngine::pauseBackgroundMusic()
|
||||
void SimpleAudioEngine::resumeBackgroundMusic()
|
||||
{
|
||||
static_resumeBackgroundMusic();
|
||||
}
|
||||
}
|
||||
|
||||
void SimpleAudioEngine::rewindBackgroundMusic()
|
||||
{
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
/*
|
||||
Copyright (c) 2010 Steve Oldmeadow
|
||||
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
@@ -18,7 +18,7 @@
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
|
||||
$Id$
|
||||
*/
|
||||
|
||||
@@ -30,15 +30,15 @@
|
||||
This is recommended for basic audio requirements. If you just want to play some sound fx
|
||||
and some background music and have no interest in learning the lower level workings then
|
||||
this is the interface to use.
|
||||
|
||||
|
||||
Requirements:
|
||||
- Firmware: OS 2.2 or greater
|
||||
- Firmware: OS 2.2 or greater
|
||||
- Files: SimpleAudioEngine.*, CocosDenshion.*
|
||||
- Frameworks: OpenAL, AudioToolbox, AVFoundation
|
||||
@since v0.8
|
||||
*/
|
||||
@interface SimpleAudioEngine : NSObject <CDAudioInterruptProtocol> {
|
||||
|
||||
|
||||
BOOL mute_;
|
||||
BOOL enabled_;
|
||||
}
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
/*
|
||||
Copyright (c) 2010 Steve Oldmeadow
|
||||
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
@@ -18,7 +18,7 @@
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
|
||||
$Id$
|
||||
*/
|
||||
|
||||
@@ -71,14 +71,14 @@ static CDBufferManager *bufferManager = nil;
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
+(void) end
|
||||
+(void) end
|
||||
{
|
||||
am = nil;
|
||||
[CDAudioManager end];
|
||||
[bufferManager release];
|
||||
[sharedEngine release];
|
||||
sharedEngine = nil;
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark SimpleAudioEngine - background music
|
||||
|
||||
@@ -103,11 +103,11 @@ static CDBufferManager *bufferManager = nil;
|
||||
|
||||
-(void) pauseBackgroundMusic {
|
||||
[am pauseBackgroundMusic];
|
||||
}
|
||||
}
|
||||
|
||||
-(void) resumeBackgroundMusic {
|
||||
[am resumeBackgroundMusic];
|
||||
}
|
||||
}
|
||||
|
||||
-(void) rewindBackgroundMusic {
|
||||
[am rewindBackgroundMusic];
|
||||
@@ -115,7 +115,7 @@ static CDBufferManager *bufferManager = nil;
|
||||
|
||||
-(BOOL) isBackgroundMusicPlaying {
|
||||
return [am isBackgroundMusicPlaying];
|
||||
}
|
||||
}
|
||||
|
||||
-(BOOL) willPlayBackgroundMusic {
|
||||
return [am willPlayBackgroundMusic];
|
||||
@@ -135,12 +135,12 @@ static CDBufferManager *bufferManager = nil;
|
||||
return [soundEngine playSound:soundId sourceGroupId:0 pitch:pitch pan:pan gain:gain loop:loop];
|
||||
} else {
|
||||
return CD_MUTE;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(void) stopEffect:(ALuint) soundId {
|
||||
[soundEngine stopSound:soundId];
|
||||
}
|
||||
}
|
||||
|
||||
-(void) pauseEffect:(ALuint) soundId {
|
||||
[soundEngine pauseSound: soundId];
|
||||
@@ -187,7 +187,7 @@ static CDBufferManager *bufferManager = nil;
|
||||
if (mute_ != muteValue) {
|
||||
mute_ = muteValue;
|
||||
am.mute = mute_;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-(BOOL) enabled
|
||||
@@ -200,7 +200,7 @@ static CDBufferManager *bufferManager = nil;
|
||||
if (enabled_ != enabledValue) {
|
||||
enabled_ = enabledValue;
|
||||
am.enabled = enabled_;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -208,23 +208,23 @@ static CDBufferManager *bufferManager = nil;
|
||||
-(float) backgroundMusicVolume
|
||||
{
|
||||
return am.backgroundMusic.volume;
|
||||
}
|
||||
}
|
||||
|
||||
-(void) setBackgroundMusicVolume:(float) volume
|
||||
{
|
||||
am.backgroundMusic.volume = volume;
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark SimpleAudioEngine - EffectsVolume
|
||||
-(float) effectsVolume
|
||||
{
|
||||
return am.soundEngine.masterGain;
|
||||
}
|
||||
}
|
||||
|
||||
-(void) setEffectsVolume:(float) volume
|
||||
{
|
||||
am.soundEngine.masterGain = volume;
|
||||
}
|
||||
}
|
||||
|
||||
-(CDSoundSource *) soundSourceForFile:(NSString*) filePath {
|
||||
int soundId = [bufferManager bufferForFile:filePath create:YES];
|
||||
@@ -234,7 +234,7 @@ static CDBufferManager *bufferManager = nil;
|
||||
return result;
|
||||
} else {
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2014 Chukong Technologies Inc.
|
||||
Copyright (c) 2014-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -30,350 +30,350 @@
|
||||
|
||||
#include "audio/win32/AudioCache.h"
|
||||
#include <thread>
|
||||
#include <algorithm>
|
||||
#include "vorbis/codec.h"
|
||||
#include "vorbis/vorbisfile.h"
|
||||
#include "platform/CCFileUtils.h"
|
||||
#include "mpg123/mpg123.h"
|
||||
#include "base/CCDirector.h"
|
||||
#include "base/CCScheduler.h"
|
||||
|
||||
#include <windows.h>
|
||||
#include "audio/win32/AudioDecoderManager.h"
|
||||
#include "audio/win32/AudioDecoder.h"
|
||||
|
||||
#define PCMDATA_CACHEMAXSIZE 2621440
|
||||
#define VERY_VERY_VERBOSE_LOGGING
|
||||
#ifdef VERY_VERY_VERBOSE_LOGGING
|
||||
#define ALOGVV ALOGV
|
||||
#else
|
||||
#define ALOGVV(...) do{} while(false)
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
unsigned int __idIndex = 0;
|
||||
}
|
||||
|
||||
#define INVALID_AL_BUFFER_ID 0xFFFFFFFF
|
||||
#define PCMDATA_CACHEMAXSIZE 1048576
|
||||
|
||||
using namespace cocos2d;
|
||||
using namespace cocos2d::experimental;
|
||||
|
||||
//FIXME: Move _winLog, winLog to a separated file
|
||||
static void _winLog(const char *format, va_list args)
|
||||
{
|
||||
static const int MAX_LOG_LENGTH = 16 * 1024;
|
||||
int bufferSize = MAX_LOG_LENGTH;
|
||||
char* buf = nullptr;
|
||||
|
||||
do
|
||||
{
|
||||
buf = new (std::nothrow) char[bufferSize];
|
||||
if (buf == nullptr)
|
||||
return; // not enough memory
|
||||
|
||||
int ret = vsnprintf(buf, bufferSize - 3, format, args);
|
||||
if (ret < 0)
|
||||
{
|
||||
bufferSize *= 2;
|
||||
|
||||
delete[] buf;
|
||||
}
|
||||
else
|
||||
break;
|
||||
|
||||
} while (true);
|
||||
|
||||
strcat(buf, "\n");
|
||||
|
||||
int pos = 0;
|
||||
int len = strlen(buf);
|
||||
char tempBuf[MAX_LOG_LENGTH + 1] = { 0 };
|
||||
WCHAR wszBuf[MAX_LOG_LENGTH + 1] = { 0 };
|
||||
|
||||
do
|
||||
{
|
||||
std::copy(buf + pos, buf + pos + MAX_LOG_LENGTH, tempBuf);
|
||||
|
||||
tempBuf[MAX_LOG_LENGTH] = 0;
|
||||
|
||||
MultiByteToWideChar(CP_UTF8, 0, tempBuf, -1, wszBuf, sizeof(wszBuf));
|
||||
OutputDebugStringW(wszBuf);
|
||||
|
||||
pos += MAX_LOG_LENGTH;
|
||||
|
||||
} while (pos < len);
|
||||
|
||||
delete[] buf;
|
||||
}
|
||||
|
||||
void audioLog(const char * format, ...)
|
||||
{
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
_winLog(format, args);
|
||||
va_end(args);
|
||||
}
|
||||
|
||||
AudioCache::AudioCache()
|
||||
: _pcmData(nullptr)
|
||||
, _pcmDataSize(0)
|
||||
, _bytesOfRead(0)
|
||||
, _alBufferReady(false)
|
||||
, _loadFail(false)
|
||||
, _fileFormat(FileFormat::UNKNOWN)
|
||||
: _totalFrames(0)
|
||||
, _framesRead(0)
|
||||
, _format(-1)
|
||||
, _duration(0.0f)
|
||||
, _alBufferId(INVALID_AL_BUFFER_ID)
|
||||
, _pcmData(nullptr)
|
||||
, _queBufferFrames(0)
|
||||
, _queBufferBytes(0)
|
||||
, _mp3Encoding(0)
|
||||
, _state(State::INITIAL)
|
||||
, _isDestroyed(std::make_shared<bool>(false))
|
||||
, _id(++__idIndex)
|
||||
, _isLoadingFinished(false)
|
||||
, _isSkipReadDataTask(false)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
AudioCache::AudioCache(const AudioCache& cache)
|
||||
{
|
||||
_pcmData = cache._pcmData;
|
||||
_pcmDataSize = cache._pcmDataSize;
|
||||
_bytesOfRead = cache._bytesOfRead;
|
||||
_alBufferReady = cache._alBufferReady;
|
||||
_fileFormat = cache._fileFormat;
|
||||
_queBufferFrames = cache._queBufferFrames;
|
||||
_queBufferBytes = cache._queBufferBytes;
|
||||
_mp3Encoding = cache._mp3Encoding;
|
||||
ALOGVV("AudioCache() %p, id=%u", this, _id);
|
||||
for (int i = 0; i < QUEUEBUFFER_NUM; ++i)
|
||||
{
|
||||
_queBuffers[i] = nullptr;
|
||||
_queBufferSize[i] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
AudioCache::~AudioCache()
|
||||
{
|
||||
if(_pcmData){
|
||||
if (_alBufferReady){
|
||||
alDeleteBuffers(1, &_alBufferId);
|
||||
ALOGVV("~AudioCache() %p, id=%u, begin", this, _id);
|
||||
*_isDestroyed = true;
|
||||
while (!_isLoadingFinished)
|
||||
{
|
||||
if (_isSkipReadDataTask)
|
||||
{
|
||||
ALOGV("id=%u, Skip read data task, don't continue to wait!", _id);
|
||||
break;
|
||||
}
|
||||
ALOGVV("id=%u, waiting readData thread to finish ...", _id);
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(5));
|
||||
}
|
||||
//wait for the 'readDataTask' task to exit
|
||||
_readDataTaskMutex.lock();
|
||||
_readDataTaskMutex.unlock();
|
||||
|
||||
if (_pcmData)
|
||||
{
|
||||
if (_state == State::READY)
|
||||
{
|
||||
if (_alBufferId != INVALID_AL_BUFFER_ID && alIsBuffer(_alBufferId))
|
||||
{
|
||||
ALOGV("~AudioCache(id=%u), delete buffer: %u", _id, _alBufferId);
|
||||
alDeleteBuffers(1, &_alBufferId);
|
||||
_alBufferId = INVALID_AL_BUFFER_ID;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ALOGW("AudioCache (%p), id=%u, buffer isn't ready, state=%d", this, _id, _state);
|
||||
}
|
||||
//wait for the 'readDataTask' task to exit
|
||||
_readDataTaskMutex.lock();
|
||||
_readDataTaskMutex.unlock();
|
||||
|
||||
free(_pcmData);
|
||||
}
|
||||
|
||||
if (_queBufferFrames > 0) {
|
||||
for (int index = 0; index < QUEUEBUFFER_NUM; ++index) {
|
||||
if (_queBufferFrames > 0)
|
||||
{
|
||||
for (int index = 0; index < QUEUEBUFFER_NUM; ++index)
|
||||
{
|
||||
free(_queBuffers[index]);
|
||||
}
|
||||
}
|
||||
ALOGVV("~AudioCache() %p, id=%u, end", this, _id);
|
||||
}
|
||||
|
||||
void AudioCache::readDataTask()
|
||||
void AudioCache::readDataTask(unsigned int selfId)
|
||||
{
|
||||
//Note: It's in sub thread
|
||||
ALOGVV("readDataTask begin, cache id=%u", selfId);
|
||||
|
||||
_readDataTaskMutex.lock();
|
||||
_state = State::LOADING;
|
||||
|
||||
OggVorbis_File* vf = nullptr;
|
||||
mpg123_handle* mpg123handle = nullptr;
|
||||
long totalFrames = 0;
|
||||
|
||||
switch (_fileFormat)
|
||||
{
|
||||
case FileFormat::OGG:
|
||||
{
|
||||
vf = new OggVorbis_File;
|
||||
int openCode;
|
||||
if (openCode = ov_fopen(FileUtils::getInstance()->getSuitableFOpen(_fileFullPath).c_str(), vf)){
|
||||
ALOGE("Input does not appear to be an Ogg bitstream: %s. Code: 0x%x\n", _fileFullPath.c_str(), openCode);
|
||||
goto ExitThread;
|
||||
}
|
||||
|
||||
auto vi = ov_info(vf,-1);
|
||||
totalFrames = (long)ov_pcm_total(vf,-1);
|
||||
_bytesPerFrame = vi->channels * 2;
|
||||
_alBufferFormat = (vi->channels > 1) ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16;
|
||||
_sampleRate = vi->rate;
|
||||
_pcmDataSize = totalFrames * _bytesPerFrame;
|
||||
_duration = 1.0f * totalFrames / _sampleRate;
|
||||
}
|
||||
break;
|
||||
case FileFormat::MP3:
|
||||
{
|
||||
long rate = 0;
|
||||
int error = MPG123_OK;
|
||||
mpg123handle = mpg123_new(nullptr, &error);
|
||||
if (!mpg123handle){
|
||||
ALOGE("Basic setup goes wrong: %s", mpg123_plain_strerror(error));
|
||||
goto ExitThread;
|
||||
}
|
||||
|
||||
if (mpg123_open(mpg123handle,_fileFullPath.c_str()) != MPG123_OK ||
|
||||
mpg123_getformat(mpg123handle, &rate, &_channels, &_mp3Encoding) != MPG123_OK) {
|
||||
ALOGE("Trouble with mpg123: %s\n", mpg123_strerror(mpg123handle) );
|
||||
goto ExitThread;
|
||||
}
|
||||
|
||||
if (_mp3Encoding == MPG123_ENC_SIGNED_16){
|
||||
_bytesPerFrame = 2 * _channels;
|
||||
}
|
||||
else if (_mp3Encoding == MPG123_ENC_FLOAT_32){
|
||||
_bytesPerFrame = 4 * _channels;
|
||||
}
|
||||
else{
|
||||
log("Bad encoding: 0x%x!\n", _mp3Encoding);
|
||||
goto ExitThread;
|
||||
}
|
||||
|
||||
_alBufferFormat = (_channels > 1) ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16;
|
||||
_sampleRate = rate;
|
||||
|
||||
/* Ensure that this output format will not change (it could, when we allow it). */
|
||||
mpg123_format_none(mpg123handle);
|
||||
mpg123_format(mpg123handle, rate, _channels, _mp3Encoding);
|
||||
/* Ensure that we can get accurate length by call mpg123_length */
|
||||
mpg123_scan(mpg123handle);
|
||||
|
||||
auto framesLength = mpg123_length(mpg123handle);
|
||||
totalFrames = framesLength;
|
||||
_pcmDataSize = totalFrames * _bytesPerFrame;
|
||||
_duration = 1.0f * totalFrames / _sampleRate;
|
||||
}
|
||||
break;
|
||||
case FileFormat::UNKNOWN:
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (_pcmDataSize <= PCMDATA_CACHEMAXSIZE)
|
||||
AudioDecoder* decoder = AudioDecoderManager::createDecoder(_fileFullPath.c_str());
|
||||
do
|
||||
{
|
||||
_pcmData = malloc(_pcmDataSize);
|
||||
auto alError = alGetError();
|
||||
alGenBuffers(1, &_alBufferId);
|
||||
alError = alGetError();
|
||||
if (alError != AL_NO_ERROR) {
|
||||
log("%s: attaching audio to buffer fail: %x\n", __FUNCTION__, alError);
|
||||
goto ExitThread;
|
||||
}
|
||||
if (decoder == nullptr || !decoder->open(_fileFullPath.c_str()))
|
||||
break;
|
||||
|
||||
switch (_fileFormat)
|
||||
const uint32_t originalTotalFrames = decoder->getTotalFrames();
|
||||
const uint32_t bytesPerFrame = decoder->getBytesPerFrame();
|
||||
const uint32_t sampleRate = decoder->getSampleRate();
|
||||
const uint32_t channelCount = decoder->getChannelCount();
|
||||
|
||||
uint32_t totalFrames = originalTotalFrames;
|
||||
uint32_t dataSize = totalFrames * bytesPerFrame;
|
||||
uint32_t remainingFrames = totalFrames;
|
||||
uint32_t adjustFrames = 0;
|
||||
|
||||
_format = channelCount > 1 ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16;
|
||||
_sampleRate = (ALsizei)sampleRate;
|
||||
_duration = 1.0f * totalFrames / sampleRate;
|
||||
_totalFrames = totalFrames;
|
||||
|
||||
if (dataSize <= PCMDATA_CACHEMAXSIZE)
|
||||
{
|
||||
case FileFormat::OGG:
|
||||
uint32_t framesRead = 0;
|
||||
const uint32_t framesToReadOnce = std::min(totalFrames, static_cast<uint32_t>(sampleRate * QUEUEBUFFER_TIME_STEP * QUEUEBUFFER_NUM));
|
||||
|
||||
std::vector<char> adjustFrameBuf;
|
||||
|
||||
if (decoder->seek(totalFrames))
|
||||
{
|
||||
int current_section;
|
||||
unsigned int currPos = 0;
|
||||
long readRet = 0;
|
||||
char* tmpBuf = (char*)malloc(framesToReadOnce * bytesPerFrame);
|
||||
adjustFrameBuf.reserve(framesToReadOnce * bytesPerFrame);
|
||||
|
||||
// Adjust total frames by setting position to the end of frames and try to read more data.
|
||||
// This is a workaround for https://github.com/cocos2d/cocos2d-x/issues/16938
|
||||
do
|
||||
{
|
||||
readRet = ov_read(vf,(char*)_pcmData + _bytesOfRead,4096,0,2,1,¤t_section);
|
||||
if (readRet > 0){
|
||||
_bytesOfRead += readRet;
|
||||
framesRead = decoder->read(framesToReadOnce, tmpBuf);
|
||||
if (framesRead > 0)
|
||||
{
|
||||
adjustFrames += framesRead;
|
||||
adjustFrameBuf.insert(adjustFrameBuf.end(), tmpBuf, tmpBuf + framesRead * bytesPerFrame);
|
||||
}
|
||||
} while (_bytesOfRead < _pcmDataSize);
|
||||
|
||||
_alBufferReady = true;
|
||||
_bytesOfRead = _pcmDataSize;
|
||||
break;
|
||||
} while (framesRead > 0);
|
||||
|
||||
if (adjustFrames > 0)
|
||||
{
|
||||
ALOGV("Orignal total frames: %u, adjust frames: %u, current total frames: %u", totalFrames, adjustFrames, totalFrames + adjustFrames);
|
||||
totalFrames += adjustFrames;
|
||||
_totalFrames = remainingFrames = totalFrames;
|
||||
}
|
||||
|
||||
// Reset dataSize
|
||||
dataSize = totalFrames * bytesPerFrame;
|
||||
|
||||
free(tmpBuf);
|
||||
}
|
||||
case FileFormat::MP3:
|
||||
// Reset to frame 0
|
||||
BREAK_IF_ERR_LOG(!decoder->seek(0), "AudioDecoder::seek(0) failed!");
|
||||
|
||||
_pcmData = (char*)malloc(dataSize);
|
||||
memset(_pcmData, 0x00, dataSize);
|
||||
|
||||
if (adjustFrames > 0)
|
||||
{
|
||||
size_t done = 0;
|
||||
auto err = mpg123_read(mpg123handle,(unsigned char*)_pcmData, _pcmDataSize,&done);
|
||||
if (err == MPG123_ERR){
|
||||
log("Trouble with mpg123: %s\n", mpg123_strerror(mpg123handle) );
|
||||
goto ExitThread;
|
||||
}
|
||||
if (err == MPG123_DONE || err == MPG123_OK){
|
||||
_alBufferReady = true;
|
||||
_pcmDataSize = done;
|
||||
_bytesOfRead = done;
|
||||
}
|
||||
memcpy(_pcmData + (dataSize - adjustFrameBuf.size()), adjustFrameBuf.data(), adjustFrameBuf.size());
|
||||
}
|
||||
break;
|
||||
case FileFormat::UNKNOWN:
|
||||
default:
|
||||
break;
|
||||
|
||||
alGenBuffers(1, &_alBufferId);
|
||||
auto alError = alGetError();
|
||||
if (alError != AL_NO_ERROR) {
|
||||
ALOGE("%s: attaching audio to buffer fail: %x", __FUNCTION__, alError);
|
||||
break;
|
||||
}
|
||||
|
||||
if (*_isDestroyed)
|
||||
break;
|
||||
|
||||
framesRead = decoder->readFixedFrames(std::min(framesToReadOnce, remainingFrames), _pcmData + _framesRead * bytesPerFrame);
|
||||
_framesRead += framesRead;
|
||||
remainingFrames -= framesRead;
|
||||
|
||||
if (*_isDestroyed)
|
||||
break;
|
||||
|
||||
uint32_t frames = 0;
|
||||
while (!*_isDestroyed && _framesRead < originalTotalFrames)
|
||||
{
|
||||
frames = std::min(framesToReadOnce, remainingFrames);
|
||||
if (_framesRead + frames > originalTotalFrames)
|
||||
{
|
||||
frames = originalTotalFrames - _framesRead;
|
||||
}
|
||||
framesRead = decoder->read(frames, _pcmData + _framesRead * bytesPerFrame);
|
||||
if (framesRead == 0)
|
||||
break;
|
||||
_framesRead += framesRead;
|
||||
remainingFrames -= framesRead;
|
||||
}
|
||||
|
||||
if (*_isDestroyed)
|
||||
break;
|
||||
|
||||
if (_framesRead < originalTotalFrames)
|
||||
{
|
||||
memset(_pcmData + _framesRead * bytesPerFrame, 0x00, (totalFrames - _framesRead) * bytesPerFrame);
|
||||
}
|
||||
ALOGV("pcm buffer was loaded successfully, total frames: %u, total read frames: %u, adjust frames: %u, remainingFrames: %u", totalFrames, _framesRead, adjustFrames, remainingFrames);
|
||||
|
||||
_framesRead += adjustFrames;
|
||||
|
||||
alBufferData(_alBufferId, _format, _pcmData, (ALsizei)dataSize, (ALsizei)sampleRate);
|
||||
|
||||
_state = State::READY;
|
||||
}
|
||||
alBufferData(_alBufferId,_alBufferFormat,_pcmData,_pcmDataSize,_sampleRate);
|
||||
}
|
||||
else{
|
||||
_queBufferFrames = _sampleRate * QUEUEBUFFER_TIME_STEP;
|
||||
_queBufferBytes = _queBufferFrames * _bytesPerFrame;
|
||||
else
|
||||
{
|
||||
_queBufferFrames = sampleRate * QUEUEBUFFER_TIME_STEP;
|
||||
BREAK_IF_ERR_LOG(_queBufferFrames == 0, "_queBufferFrames == 0");
|
||||
|
||||
for (int index = 0; index < QUEUEBUFFER_NUM; ++index) {
|
||||
_queBuffers[index] = (char*)malloc(_queBufferBytes);
|
||||
const uint32_t queBufferBytes = _queBufferFrames * bytesPerFrame;
|
||||
|
||||
switch (_fileFormat){
|
||||
case FileFormat::MP3:
|
||||
{
|
||||
size_t done = 0;
|
||||
mpg123_read(mpg123handle,(unsigned char*)_queBuffers[index], _queBufferBytes,&done);
|
||||
_queBufferSize[index] = done;
|
||||
_bytesOfRead += done;
|
||||
}
|
||||
break;
|
||||
case FileFormat::OGG:
|
||||
{
|
||||
int current_section;
|
||||
auto readRet = ov_read(vf,_queBuffers[index],_queBufferBytes,0,2,1,¤t_section);
|
||||
_queBufferSize[index] = readRet;
|
||||
}
|
||||
break;
|
||||
for (int index = 0; index < QUEUEBUFFER_NUM; ++index)
|
||||
{
|
||||
_queBuffers[index] = (char*)malloc(queBufferBytes);
|
||||
_queBufferSize[index] = queBufferBytes;
|
||||
|
||||
decoder->readFixedFrames(_queBufferFrames, _queBuffers[index]);
|
||||
}
|
||||
|
||||
_state = State::READY;
|
||||
}
|
||||
|
||||
} while (false);
|
||||
|
||||
if (decoder != nullptr)
|
||||
{
|
||||
decoder->close();
|
||||
}
|
||||
|
||||
AudioDecoderManager::destroyDecoder(decoder);
|
||||
|
||||
if (_state != State::READY)
|
||||
{
|
||||
_state = State::FAILED;
|
||||
if (_alBufferId != INVALID_AL_BUFFER_ID && alIsBuffer(_alBufferId))
|
||||
{
|
||||
ALOGV("readDataTask failed, delete buffer: %u", _alBufferId);
|
||||
alDeleteBuffers(1, &_alBufferId);
|
||||
_alBufferId = INVALID_AL_BUFFER_ID;
|
||||
}
|
||||
}
|
||||
|
||||
ExitThread:
|
||||
switch (_fileFormat)
|
||||
{
|
||||
case FileFormat::OGG:
|
||||
ov_clear(vf);
|
||||
delete vf;
|
||||
break;
|
||||
case FileFormat::MP3:
|
||||
mpg123_close(mpg123handle);
|
||||
mpg123_delete(mpg123handle);
|
||||
break;
|
||||
case FileFormat::UNKNOWN:
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
_readDataTaskMutex.unlock();
|
||||
if (_queBufferFrames > 0)
|
||||
{
|
||||
_alBufferReady = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
_loadFail = true;
|
||||
}
|
||||
|
||||
invokingLoadCallbacks();
|
||||
//FIXME: Why to invoke play callback first? Should it be after 'load' callback?
|
||||
invokingPlayCallbacks();
|
||||
}
|
||||
invokingLoadCallbacks();
|
||||
|
||||
void AudioCache::invokingPlayCallbacks()
|
||||
{
|
||||
_callbackMutex.lock();
|
||||
auto count = _callbacks.size();
|
||||
for (size_t index = 0; index < count; ++index) {
|
||||
_callbacks[index]();
|
||||
}
|
||||
_callbacks.clear();
|
||||
_callbackMutex.unlock();
|
||||
_isLoadingFinished = true;
|
||||
_readDataTaskMutex.unlock();
|
||||
ALOGVV("readDataTask end, cache id=%u", selfId);
|
||||
}
|
||||
|
||||
void AudioCache::addPlayCallback(const std::function<void()>& callback)
|
||||
{
|
||||
_callbackMutex.lock();
|
||||
if (_alBufferReady) {
|
||||
callback();
|
||||
} else {
|
||||
_callbacks.push_back(callback);
|
||||
std::lock_guard<std::mutex> lk(_playCallbackMutex);
|
||||
switch (_state)
|
||||
{
|
||||
case State::INITIAL:
|
||||
case State::LOADING:
|
||||
_playCallbacks.push_back(callback);
|
||||
break;
|
||||
|
||||
case State::READY:
|
||||
// If state is failure, we still need to invoke the callback
|
||||
// since the callback will set the 'AudioPlayer::_removeByAudioEngine' flag to true.
|
||||
case State::FAILED:
|
||||
callback();
|
||||
break;
|
||||
|
||||
default:
|
||||
ALOGE("Invalid state: %d", _state);
|
||||
break;
|
||||
}
|
||||
_callbackMutex.unlock();
|
||||
}
|
||||
|
||||
void AudioCache::invokingLoadCallbacks()
|
||||
void AudioCache::invokingPlayCallbacks()
|
||||
{
|
||||
auto scheduler = Director::getInstance()->getScheduler();
|
||||
scheduler->performFunctionInCocosThread([&](){
|
||||
auto count = _loadCallbacks.size();
|
||||
for (size_t index = 0; index < count; ++index) {
|
||||
_loadCallbacks[index](_alBufferReady);
|
||||
}
|
||||
_loadCallbacks.clear();
|
||||
});
|
||||
std::lock_guard<std::mutex> lk(_playCallbackMutex);
|
||||
|
||||
for (auto&& cb : _playCallbacks)
|
||||
{
|
||||
cb();
|
||||
}
|
||||
|
||||
_playCallbacks.clear();
|
||||
}
|
||||
|
||||
void AudioCache::addLoadCallback(const std::function<void(bool)>& callback)
|
||||
{
|
||||
if (_alBufferReady) {
|
||||
callback(true);
|
||||
}
|
||||
else if (_loadFail){
|
||||
callback(false);
|
||||
}
|
||||
else {
|
||||
_loadCallbacks.push_back(callback);
|
||||
switch (_state)
|
||||
{
|
||||
case State::INITIAL:
|
||||
case State::LOADING:
|
||||
_loadCallbacks.push_back(callback);
|
||||
break;
|
||||
|
||||
case State::READY:
|
||||
callback(true);
|
||||
break;
|
||||
case State::FAILED:
|
||||
callback(false);
|
||||
break;
|
||||
|
||||
default:
|
||||
ALOGE("Invalid state: %d", _state);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void AudioCache::invokingLoadCallbacks()
|
||||
{
|
||||
if (*_isDestroyed)
|
||||
{
|
||||
ALOGV("AudioCache (%p) was destroyed, don't invoke preload callback ...", this);
|
||||
return;
|
||||
}
|
||||
|
||||
auto isDestroyed = _isDestroyed;
|
||||
auto scheduler = Director::getInstance()->getScheduler();
|
||||
scheduler->performFunctionInCocosThread([&, isDestroyed](){
|
||||
if (*isDestroyed)
|
||||
{
|
||||
ALOGV("invokingLoadCallbacks perform in cocos thread, AudioCache (%p) was destroyed!", this);
|
||||
return;
|
||||
}
|
||||
|
||||
for (auto&& cb : _loadCallbacks)
|
||||
{
|
||||
cb(_state == State::READY);
|
||||
}
|
||||
|
||||
_loadCallbacks.clear();
|
||||
});
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2014 Chukong Technologies Inc.
|
||||
Copyright (c) 2014-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -21,57 +21,24 @@
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "platform/CCPlatformConfig.h"
|
||||
|
||||
#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
|
||||
|
||||
#ifndef __AUDIO_CACHE_H_
|
||||
#define __AUDIO_CACHE_H_
|
||||
|
||||
#include <string>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#ifdef OPENAL_PLAIN_INCLUDES
|
||||
#include <al.h>
|
||||
#else
|
||||
#include <OpenalSoft/al.h>
|
||||
#include <AL/al.h>
|
||||
#endif
|
||||
#include "platform/CCPlatformMacros.h"
|
||||
|
||||
#define QUEUEBUFFER_NUM 5
|
||||
#define QUEUEBUFFER_TIME_STEP 0.1f
|
||||
|
||||
// log, CCLOG aren't threadsafe, since we uses sub threads for parsing pcm data, threadsafe log output
|
||||
// is needed. Define the following macros (ALOGV, ALOGD, ALOGI, ALOGW, ALOGE) for threadsafe log output.
|
||||
|
||||
//FIXME:Move the definition of the following macros to a separated file.
|
||||
|
||||
void audioLog(const char * format, ...);
|
||||
|
||||
#define QUOTEME_(x) #x
|
||||
#define QUOTEME(x) QUOTEME_(x)
|
||||
|
||||
#if defined(COCOS2D_DEBUG) && COCOS2D_DEBUG > 0
|
||||
#define ALOGV(fmt, ...) audioLog("V/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__)
|
||||
#else
|
||||
#define ALOGV(fmt, ...) do {} while(false)
|
||||
#endif
|
||||
#define ALOGD(fmt, ...) audioLog("D/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__)
|
||||
#define ALOGI(fmt, ...) audioLog("I/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__)
|
||||
#define ALOGW(fmt, ...) audioLog("W/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__)
|
||||
#define ALOGE(fmt, ...) audioLog("E/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__)
|
||||
|
||||
#if defined(COCOS2D_DEBUG) && COCOS2D_DEBUG > 0
|
||||
#define CHECK_AL_ERROR_DEBUG() \
|
||||
do { \
|
||||
GLenum __error = alGetError(); \
|
||||
if (__error) { \
|
||||
ALOGE("OpenAL error 0x%04X in %s %s %d\n", __error, __FILE__, __FUNCTION__, __LINE__); \
|
||||
} \
|
||||
} while (false)
|
||||
#else
|
||||
#define CHECK_AL_ERROR_DEBUG()
|
||||
#endif
|
||||
#include "audio/apple/AudioMacros.h"
|
||||
|
||||
NS_CC_BEGIN
|
||||
namespace experimental{
|
||||
@@ -79,17 +46,19 @@ namespace experimental{
|
||||
class AudioEngineImpl;
|
||||
class AudioPlayer;
|
||||
|
||||
class CC_DLL AudioCache{
|
||||
class CC_DLL AudioCache
|
||||
{
|
||||
public:
|
||||
enum class FileFormat
|
||||
|
||||
enum class State
|
||||
{
|
||||
UNKNOWN,
|
||||
OGG,
|
||||
MP3
|
||||
INITIAL,
|
||||
LOADING,
|
||||
READY,
|
||||
FAILED
|
||||
};
|
||||
|
||||
AudioCache();
|
||||
AudioCache(const AudioCache&);
|
||||
~AudioCache();
|
||||
|
||||
void addPlayCallback(const std::function<void()>& callback);
|
||||
@@ -97,53 +66,54 @@ public:
|
||||
void addLoadCallback(const std::function<void(bool)>& callback);
|
||||
|
||||
protected:
|
||||
void readDataTask();
|
||||
void setSkipReadDataTask(bool isSkip) { _isSkipReadDataTask = isSkip; };
|
||||
void readDataTask(unsigned int selfId);
|
||||
|
||||
void invokingPlayCallbacks();
|
||||
|
||||
void invokingLoadCallbacks();
|
||||
|
||||
std::string _fileFullPath;
|
||||
FileFormat _fileFormat;
|
||||
//pcm data related stuff
|
||||
size_t _pcmDataSize;
|
||||
ALenum _alBufferFormat;
|
||||
|
||||
int _channels;
|
||||
ALuint _sampleRate;
|
||||
size_t _bytesPerFrame;
|
||||
ALenum _format;
|
||||
ALsizei _sampleRate;
|
||||
float _duration;
|
||||
uint32_t _totalFrames;
|
||||
uint32_t _framesRead;
|
||||
|
||||
/*Cache related stuff;
|
||||
* Cache pcm data when sizeInBytes less than PCMDATA_CACHEMAXSIZE
|
||||
*/
|
||||
ALuint _alBufferId;
|
||||
void* _pcmData;
|
||||
size_t _bytesOfRead;
|
||||
char* _pcmData;
|
||||
|
||||
/*Queue buffer related stuff
|
||||
* Streaming in OpenAL when sizeInBytes greater then PCMDATA_CACHEMAXSIZE
|
||||
*/
|
||||
char* _queBuffers[QUEUEBUFFER_NUM];
|
||||
ALsizei _queBufferSize[QUEUEBUFFER_NUM];
|
||||
int _queBufferFrames;
|
||||
int _queBufferBytes;
|
||||
uint32_t _queBufferFrames;
|
||||
|
||||
bool _alBufferReady;
|
||||
bool _loadFail;
|
||||
std::mutex _callbackMutex;
|
||||
std::vector< std::function<void()> > _callbacks;
|
||||
std::mutex _playCallbackMutex;
|
||||
std::vector< std::function<void()> > _playCallbacks;
|
||||
|
||||
// loadCallbacks doesn't need mutex since it's invoked only in Cocos thread.
|
||||
std::vector< std::function<void(bool)> > _loadCallbacks;
|
||||
|
||||
std::mutex _readDataTaskMutex;
|
||||
|
||||
int _mp3Encoding;
|
||||
State _state;
|
||||
|
||||
std::shared_ptr<bool> _isDestroyed;
|
||||
std::string _fileFullPath;
|
||||
unsigned int _id;
|
||||
bool _isLoadingFinished;
|
||||
bool _isSkipReadDataTask;
|
||||
|
||||
friend class AudioEngineImpl;
|
||||
friend class AudioPlayer;
|
||||
} ;
|
||||
};
|
||||
|
||||
}
|
||||
NS_CC_END
|
||||
|
||||
#endif // __AUDIO_CACHE_H_
|
||||
#endif
|
||||
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
#include "audio/win32/AudioDecoder.h"
|
||||
#include "audio/win32/AudioMacros.h"
|
||||
#include "platform/CCFileUtils.h"
|
||||
|
||||
#define LOG_TAG "AudioDecoder"
|
||||
|
||||
namespace cocos2d { namespace experimental {
|
||||
|
||||
AudioDecoder::AudioDecoder()
|
||||
: _isOpened(false)
|
||||
, _totalFrames(0)
|
||||
, _bytesPerFrame(0)
|
||||
, _sampleRate(0)
|
||||
, _channelCount(0)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
AudioDecoder::~AudioDecoder()
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
bool AudioDecoder::isOpened() const
|
||||
{
|
||||
return _isOpened;
|
||||
}
|
||||
|
||||
uint32_t AudioDecoder::readFixedFrames(uint32_t framesToRead, char* pcmBuf)
|
||||
{
|
||||
uint32_t framesRead = 0;
|
||||
uint32_t framesReadOnce = 0;
|
||||
do
|
||||
{
|
||||
framesReadOnce = read(framesToRead - framesRead, pcmBuf + framesRead * _bytesPerFrame);
|
||||
framesRead += framesReadOnce;
|
||||
} while (framesReadOnce != 0 && framesRead < framesToRead);
|
||||
|
||||
if (framesRead < framesToRead)
|
||||
{
|
||||
memset(pcmBuf + framesRead * _bytesPerFrame, 0x00, (framesToRead - framesRead) * _bytesPerFrame);
|
||||
}
|
||||
|
||||
return framesRead;
|
||||
}
|
||||
|
||||
uint32_t AudioDecoder::getTotalFrames() const
|
||||
{
|
||||
return _totalFrames;
|
||||
}
|
||||
|
||||
uint32_t AudioDecoder::getBytesPerFrame() const
|
||||
{
|
||||
return _bytesPerFrame;
|
||||
}
|
||||
|
||||
uint32_t AudioDecoder::getSampleRate() const
|
||||
{
|
||||
return _sampleRate;
|
||||
}
|
||||
|
||||
uint32_t AudioDecoder::getChannelCount() const
|
||||
{
|
||||
return _channelCount;
|
||||
}
|
||||
|
||||
}} // namespace cocos2d { namespace experimental {
|
||||
@@ -0,0 +1,119 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#include "vorbis/vorbisfile.h"
|
||||
|
||||
namespace cocos2d { namespace experimental {
|
||||
|
||||
/**
|
||||
* @brief The class for decoding compressed audio file to PCM buffer.
|
||||
*/
|
||||
class AudioDecoder
|
||||
{
|
||||
public:
|
||||
static const uint32_t INVALID_FRAME_INDEX = UINT32_MAX;
|
||||
|
||||
/**
|
||||
* @brief Opens an audio file specified by a file path.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
virtual bool open(const char* path) = 0;
|
||||
|
||||
/**
|
||||
* @brief Checks whether decoder has opened file successfully.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
virtual bool isOpened() const;
|
||||
|
||||
/**
|
||||
* @brief Closes opened audio file.
|
||||
* @note The method will also be automatically invoked in the destructor.
|
||||
*/
|
||||
virtual void close() = 0;
|
||||
|
||||
/**
|
||||
* @brief Reads audio frames of PCM format.
|
||||
* @param framesToRead The number of frames excepted to be read.
|
||||
* @param pcmBuf The buffer to hold the frames to be read, its size should be >= |framesToRead| * _bytesPerFrame.
|
||||
* @return The number of frames actually read, it's probably less than 'framesToRead'. Returns 0 means reach the end of file.
|
||||
*/
|
||||
virtual uint32_t read(uint32_t framesToRead, char* pcmBuf) = 0;
|
||||
|
||||
/**
|
||||
* @brief Reads fixed audio frames of PCM format.
|
||||
* @param framesToRead The number of frames excepted to be read.
|
||||
* @param pcmBuf The buffer to hold the frames to be read, its size should be >= |framesToRead| * _bytesPerFrame.
|
||||
* @return The number of frames actually read, it's probably less than |framesToRead|. Returns 0 means reach the end of file.
|
||||
* @note The different between |read| and |readFixedFrames| is |readFixedFrames| will do multiple reading operations if |framesToRead| frames
|
||||
* isn't filled entirely, while |read| just does reading operation once whatever |framesToRead| is or isn't filled entirely.
|
||||
* If current position reaches the end of frames, the return value may smaller than |framesToRead| and the remaining
|
||||
* buffer in |pcmBuf| will be set with silence data (0x00).
|
||||
*/
|
||||
virtual uint32_t readFixedFrames(uint32_t framesToRead, char* pcmBuf);
|
||||
|
||||
/**
|
||||
* @brief Sets frame offest to be read.
|
||||
* @param frameOffset The frame offest to be set.
|
||||
* @return true if succeed, otherwise false
|
||||
*/
|
||||
virtual bool seek(uint32_t frameOffset) = 0;
|
||||
|
||||
/**
|
||||
* @brief Tells the current frame offset.
|
||||
* @return The current frame offset.
|
||||
*/
|
||||
virtual uint32_t tell() const = 0;
|
||||
|
||||
/** Gets total frames of current audio.*/
|
||||
virtual uint32_t getTotalFrames() const;
|
||||
|
||||
/** Gets bytes per frame of current audio.*/
|
||||
virtual uint32_t getBytesPerFrame() const;
|
||||
|
||||
/** Gets sample rate of current audio.*/
|
||||
virtual uint32_t getSampleRate() const;
|
||||
|
||||
/** Gets the channel count of current audio.
|
||||
* @note Currently we only support 1 or 2 channels.
|
||||
*/
|
||||
virtual uint32_t getChannelCount() const;
|
||||
|
||||
protected:
|
||||
AudioDecoder();
|
||||
virtual ~AudioDecoder();
|
||||
|
||||
bool _isOpened;
|
||||
uint32_t _totalFrames;
|
||||
uint32_t _bytesPerFrame;
|
||||
uint32_t _sampleRate;
|
||||
uint32_t _channelCount;
|
||||
|
||||
friend class AudioDecoderManager;
|
||||
};
|
||||
|
||||
}} // namespace cocos2d { namespace experimental {
|
||||
@@ -0,0 +1,70 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
#define LOG_TAG "AudioDecoderManager"
|
||||
|
||||
#include "audio/win32/AudioDecoderManager.h"
|
||||
#include "audio/win32/AudioDecoderOgg.h"
|
||||
#include "audio/win32/AudioDecoderMp3.h"
|
||||
#include "audio/win32/AudioMacros.h"
|
||||
#include "platform/CCFileUtils.h"
|
||||
#include "base/CCConsole.h"
|
||||
#include "mpg123.h"
|
||||
|
||||
namespace cocos2d { namespace experimental {
|
||||
|
||||
static bool __mp3Inited = false;
|
||||
|
||||
bool AudioDecoderManager::init()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
void AudioDecoderManager::destroy()
|
||||
{
|
||||
AudioDecoderMp3::destroy();
|
||||
}
|
||||
|
||||
AudioDecoder* AudioDecoderManager::createDecoder(const char* path)
|
||||
{
|
||||
std::string suffix = FileUtils::getInstance()->getFileExtension(path);
|
||||
if (suffix == ".ogg")
|
||||
{
|
||||
return new (std::nothrow) AudioDecoderOgg();
|
||||
}
|
||||
else if (suffix == ".mp3")
|
||||
{
|
||||
return new (std::nothrow) AudioDecoderMp3();
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void AudioDecoderManager::destroyDecoder(AudioDecoder* decoder)
|
||||
{
|
||||
delete decoder;
|
||||
}
|
||||
|
||||
}} // namespace cocos2d { namespace experimental {
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
#pragma once
|
||||
|
||||
namespace cocos2d { namespace experimental {
|
||||
|
||||
class AudioDecoder;
|
||||
|
||||
class AudioDecoderManager
|
||||
{
|
||||
public:
|
||||
static bool init();
|
||||
static void destroy();
|
||||
static AudioDecoder* createDecoder(const char* path);
|
||||
static void destroyDecoder(AudioDecoder* decoder);
|
||||
};
|
||||
|
||||
}} // namespace cocos2d { namespace experimental {
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
#include "audio/win32/AudioDecoderMp3.h"
|
||||
#include "audio/win32/AudioMacros.h"
|
||||
#include "platform/CCFileUtils.h"
|
||||
|
||||
#include "base/CCConsole.h"
|
||||
#include "mpg123.h"
|
||||
|
||||
#define LOG_TAG "AudioDecoderMp3"
|
||||
|
||||
namespace cocos2d { namespace experimental {
|
||||
|
||||
static bool __mp3Inited = false;
|
||||
|
||||
bool AudioDecoderMp3::lazyInit()
|
||||
{
|
||||
bool ret = true;
|
||||
if (!__mp3Inited)
|
||||
{
|
||||
int error = mpg123_init();
|
||||
if (error == MPG123_OK)
|
||||
{
|
||||
__mp3Inited = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
ALOGE("Basic setup goes wrong: %s", mpg123_plain_strerror(error));
|
||||
ret = false;
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
void AudioDecoderMp3::destroy()
|
||||
{
|
||||
if (__mp3Inited)
|
||||
{
|
||||
mpg123_exit();
|
||||
__mp3Inited = false;
|
||||
}
|
||||
}
|
||||
|
||||
AudioDecoderMp3::AudioDecoderMp3()
|
||||
: _mpg123handle(nullptr)
|
||||
{
|
||||
lazyInit();
|
||||
}
|
||||
|
||||
AudioDecoderMp3::~AudioDecoderMp3()
|
||||
{
|
||||
close();
|
||||
}
|
||||
|
||||
bool AudioDecoderMp3::open(const char* path)
|
||||
{
|
||||
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(path);
|
||||
|
||||
long rate = 0;
|
||||
int error = MPG123_OK;
|
||||
int mp3Encoding = 0;
|
||||
int channel = 0;
|
||||
do
|
||||
{
|
||||
_mpg123handle = mpg123_new(nullptr, &error);
|
||||
if (nullptr == _mpg123handle)
|
||||
{
|
||||
ALOGE("Basic setup goes wrong: %s", mpg123_plain_strerror(error));
|
||||
break;
|
||||
}
|
||||
|
||||
if (mpg123_open(_mpg123handle, fullPath.c_str()) != MPG123_OK
|
||||
|| mpg123_getformat(_mpg123handle, &rate, &channel, &mp3Encoding) != MPG123_OK)
|
||||
{
|
||||
ALOGE("Trouble with mpg123: %s\n", mpg123_strerror(_mpg123handle) );
|
||||
break;
|
||||
}
|
||||
|
||||
_channelCount = channel;
|
||||
_sampleRate = rate;
|
||||
|
||||
if (mp3Encoding == MPG123_ENC_SIGNED_16)
|
||||
{
|
||||
_bytesPerFrame = 2 * _channelCount;
|
||||
}
|
||||
else if (mp3Encoding == MPG123_ENC_FLOAT_32)
|
||||
{
|
||||
_bytesPerFrame = 4 * _channelCount;
|
||||
}
|
||||
else
|
||||
{
|
||||
ALOGE("Bad encoding: 0x%x!\n", mp3Encoding);
|
||||
break;
|
||||
}
|
||||
|
||||
/* Ensure that this output format will not change (it could, when we allow it). */
|
||||
mpg123_format_none(_mpg123handle);
|
||||
mpg123_format(_mpg123handle, rate, channel, mp3Encoding);
|
||||
/* Ensure that we can get accurate length by call mpg123_length */
|
||||
mpg123_scan(_mpg123handle);
|
||||
|
||||
_totalFrames = mpg123_length(_mpg123handle);
|
||||
|
||||
_isOpened = true;
|
||||
return true;
|
||||
} while (false);
|
||||
|
||||
if (_mpg123handle != nullptr)
|
||||
{
|
||||
mpg123_close(_mpg123handle);
|
||||
mpg123_delete(_mpg123handle);
|
||||
_mpg123handle = nullptr;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void AudioDecoderMp3::close()
|
||||
{
|
||||
if (isOpened())
|
||||
{
|
||||
if (_mpg123handle != nullptr)
|
||||
{
|
||||
mpg123_close(_mpg123handle);
|
||||
mpg123_delete(_mpg123handle);
|
||||
_mpg123handle = nullptr;
|
||||
}
|
||||
_isOpened = false;
|
||||
}
|
||||
}
|
||||
|
||||
uint32_t AudioDecoderMp3::read(uint32_t framesToRead, char* pcmBuf)
|
||||
{
|
||||
int bytesToRead = framesToRead * _bytesPerFrame;
|
||||
size_t bytesRead = 0;
|
||||
int err = mpg123_read(_mpg123handle, (unsigned char*)pcmBuf, bytesToRead, &bytesRead);
|
||||
if (err == MPG123_ERR)
|
||||
{
|
||||
ALOGE("Trouble with mpg123: %s\n", mpg123_strerror(_mpg123handle) );
|
||||
return 0;
|
||||
}
|
||||
|
||||
return static_cast<uint32_t>(bytesRead / _bytesPerFrame);
|
||||
}
|
||||
|
||||
bool AudioDecoderMp3::seek(uint32_t frameOffset)
|
||||
{
|
||||
off_t offset = mpg123_seek(_mpg123handle, frameOffset, SEEK_SET);
|
||||
//ALOGD("mpg123_seek return: %d", (int)offset);
|
||||
if (offset >= 0 && offset == frameOffset)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
uint32_t AudioDecoderMp3::tell() const
|
||||
{
|
||||
return static_cast<uint32_t>(mpg123_tell(_mpg123handle));
|
||||
}
|
||||
|
||||
}} // namespace cocos2d { namespace experimental {
|
||||
@@ -0,0 +1,85 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "audio/win32/AudioDecoder.h"
|
||||
|
||||
struct mpg123_handle_struct;
|
||||
|
||||
namespace cocos2d { namespace experimental {
|
||||
|
||||
/**
|
||||
* @brief The class for decoding compressed audio file to PCM buffer.
|
||||
*/
|
||||
class AudioDecoderMp3 : public AudioDecoder
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Opens an audio file specified by a file path.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
virtual bool open(const char* path) override;
|
||||
|
||||
/**
|
||||
* @brief Closes opened audio file.
|
||||
* @note The method will also be automatically invoked in the destructor.
|
||||
*/
|
||||
virtual void close() override;
|
||||
|
||||
/**
|
||||
* @brief Reads audio frames of PCM format.
|
||||
* @param framesToRead The number of frames excepted to be read.
|
||||
* @param pcmBuf The buffer to hold the frames to be read, its size should be >= |framesToRead| * _bytesPerFrame.
|
||||
* @return The number of frames actually read, it's probably less than 'framesToRead'. Returns 0 means reach the end of file.
|
||||
*/
|
||||
virtual uint32_t read(uint32_t framesToRead, char* pcmBuf) override;
|
||||
|
||||
/**
|
||||
* @brief Sets frame offest to be read.
|
||||
* @param frameOffset The frame offest to be set.
|
||||
* @return true if succeed, otherwise false
|
||||
*/
|
||||
virtual bool seek(uint32_t frameOffset) override;
|
||||
|
||||
/**
|
||||
* @brief Tells the current frame offset.
|
||||
* @return The current frame offset.
|
||||
*/
|
||||
virtual uint32_t tell() const override;
|
||||
|
||||
protected:
|
||||
|
||||
AudioDecoderMp3();
|
||||
~AudioDecoderMp3();
|
||||
|
||||
static bool lazyInit();
|
||||
static void destroy();
|
||||
|
||||
struct mpg123_handle_struct* _mpg123handle;
|
||||
|
||||
friend class AudioDecoderManager;
|
||||
};
|
||||
|
||||
}} // namespace cocos2d { namespace experimental {
|
||||
@@ -0,0 +1,86 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
#include "audio/win32/AudioDecoderOgg.h"
|
||||
#include "audio/win32/AudioMacros.h"
|
||||
#include "platform/CCFileUtils.h"
|
||||
|
||||
#define LOG_TAG "AudioDecoderOgg"
|
||||
|
||||
namespace cocos2d { namespace experimental {
|
||||
|
||||
AudioDecoderOgg::AudioDecoderOgg()
|
||||
{
|
||||
}
|
||||
|
||||
AudioDecoderOgg::~AudioDecoderOgg()
|
||||
{
|
||||
close();
|
||||
}
|
||||
|
||||
bool AudioDecoderOgg::open(const char* path)
|
||||
{
|
||||
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(path);
|
||||
if (0 == ov_fopen(fullPath.c_str(), &_vf))
|
||||
{
|
||||
// header
|
||||
vorbis_info* vi = ov_info(&_vf, -1);
|
||||
_sampleRate = static_cast<uint32_t>(vi->rate);
|
||||
_channelCount = vi->channels;
|
||||
_bytesPerFrame = vi->channels * sizeof(short);
|
||||
_totalFrames = static_cast<uint32_t>(ov_pcm_total(&_vf, -1));
|
||||
_isOpened = true;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void AudioDecoderOgg::close()
|
||||
{
|
||||
if (isOpened())
|
||||
{
|
||||
ov_clear(&_vf);
|
||||
_isOpened = false;
|
||||
}
|
||||
}
|
||||
|
||||
uint32_t AudioDecoderOgg::read(uint32_t framesToRead, char* pcmBuf)
|
||||
{
|
||||
int currentSection = 0;
|
||||
int bytesToRead = framesToRead * _bytesPerFrame;
|
||||
long bytesRead = ov_read(&_vf, pcmBuf, bytesToRead, 0, 2, 1, ¤tSection);
|
||||
return static_cast<uint32_t>(bytesRead / _bytesPerFrame);
|
||||
}
|
||||
|
||||
bool AudioDecoderOgg::seek(uint32_t frameOffset)
|
||||
{
|
||||
return 0 == ov_pcm_seek(&_vf, frameOffset);
|
||||
}
|
||||
|
||||
uint32_t AudioDecoderOgg::tell() const
|
||||
{
|
||||
return static_cast<uint32_t>(ov_pcm_tell(const_cast<OggVorbis_File*>(&_vf)));
|
||||
}
|
||||
|
||||
}} // namespace cocos2d { namespace experimental {
|
||||
@@ -0,0 +1,81 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "audio/win32/AudioDecoder.h"
|
||||
|
||||
#include "vorbis/vorbisfile.h"
|
||||
|
||||
namespace cocos2d { namespace experimental {
|
||||
|
||||
/**
|
||||
* @brief The class for decoding compressed audio file to PCM buffer.
|
||||
*/
|
||||
class AudioDecoderOgg : public AudioDecoder
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @brief Opens an audio file specified by a file path.
|
||||
* @return true if succeed, otherwise false.
|
||||
*/
|
||||
virtual bool open(const char* path) override;
|
||||
|
||||
/**
|
||||
* @brief Closes opened audio file.
|
||||
* @note The method will also be automatically invoked in the destructor.
|
||||
*/
|
||||
virtual void close() override;
|
||||
|
||||
/**
|
||||
* @brief Reads audio frames of PCM format.
|
||||
* @param framesToRead The number of frames excepted to be read.
|
||||
* @param pcmBuf The buffer to hold the frames to be read, its size should be >= |framesToRead| * _bytesPerFrame.
|
||||
* @return The number of frames actually read, it's probably less than 'framesToRead'. Returns 0 means reach the end of file.
|
||||
*/
|
||||
virtual uint32_t read(uint32_t framesToRead, char* pcmBuf) override;
|
||||
|
||||
/**
|
||||
* @brief Sets frame offest to be read.
|
||||
* @param frameOffset The frame offest to be set.
|
||||
* @return true if succeed, otherwise false
|
||||
*/
|
||||
virtual bool seek(uint32_t frameOffset) override;
|
||||
|
||||
/**
|
||||
* @brief Tells the current frame offset.
|
||||
* @return The current frame offset.
|
||||
*/
|
||||
virtual uint32_t tell() const override;
|
||||
|
||||
protected:
|
||||
AudioDecoderOgg();
|
||||
~AudioDecoderOgg();
|
||||
|
||||
OggVorbis_File _vf;
|
||||
|
||||
friend class AudioDecoderManager;
|
||||
};
|
||||
|
||||
}} // namespace cocos2d { namespace experimental {
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2014 Chukong Technologies Inc.
|
||||
Copyright (c) 2014-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -33,31 +33,97 @@
|
||||
#include "alc.h"
|
||||
#include "alext.h"
|
||||
#else
|
||||
#include "OpenalSoft/alc.h"
|
||||
#include "OpenalSoft/alext.h"
|
||||
#include "AL/alc.h"
|
||||
#include "AL/alext.h"
|
||||
#endif
|
||||
#include "audio/include/AudioEngine.h"
|
||||
#include "base/CCDirector.h"
|
||||
#include "base/CCScheduler.h"
|
||||
#include "platform/CCFileUtils.h"
|
||||
#include "mpg123/mpg123.h"
|
||||
#include "audio/win32/AudioDecoderManager.h"
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
// log, CCLOG aren't threadsafe, since we uses sub threads for parsing pcm data, threadsafe log output
|
||||
// is needed. Define the following macros (ALOGV, ALOGD, ALOGI, ALOGW, ALOGE) for threadsafe log output.
|
||||
|
||||
//FIXME: Move _winLog, winLog to a separated file
|
||||
static void _winLog(const char *format, va_list args)
|
||||
{
|
||||
static const int MAX_LOG_LENGTH = 16 * 1024;
|
||||
int bufferSize = MAX_LOG_LENGTH;
|
||||
char* buf = nullptr;
|
||||
|
||||
do
|
||||
{
|
||||
buf = new (std::nothrow) char[bufferSize];
|
||||
if (buf == nullptr)
|
||||
return; // not enough memory
|
||||
|
||||
int ret = vsnprintf(buf, bufferSize - 3, format, args);
|
||||
if (ret < 0)
|
||||
{
|
||||
bufferSize *= 2;
|
||||
|
||||
delete[] buf;
|
||||
}
|
||||
else
|
||||
break;
|
||||
|
||||
} while (true);
|
||||
|
||||
strcat(buf, "\n");
|
||||
|
||||
int pos = 0;
|
||||
int len = strlen(buf);
|
||||
char tempBuf[MAX_LOG_LENGTH + 1] = { 0 };
|
||||
WCHAR wszBuf[MAX_LOG_LENGTH + 1] = { 0 };
|
||||
|
||||
do
|
||||
{
|
||||
std::copy(buf + pos, buf + pos + MAX_LOG_LENGTH, tempBuf);
|
||||
|
||||
tempBuf[MAX_LOG_LENGTH] = 0;
|
||||
|
||||
MultiByteToWideChar(CP_UTF8, 0, tempBuf, -1, wszBuf, sizeof(wszBuf));
|
||||
OutputDebugStringW(wszBuf);
|
||||
|
||||
pos += MAX_LOG_LENGTH;
|
||||
|
||||
} while (pos < len);
|
||||
|
||||
delete[] buf;
|
||||
}
|
||||
|
||||
void audioLog(const char * format, ...)
|
||||
{
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
_winLog(format, args);
|
||||
va_end(args);
|
||||
}
|
||||
|
||||
using namespace cocos2d;
|
||||
using namespace cocos2d::experimental;
|
||||
|
||||
static ALCdevice *s_ALDevice = nullptr;
|
||||
static ALCcontext *s_ALContext = nullptr;
|
||||
static bool MPG123_LAZYINIT = true;
|
||||
|
||||
AudioEngineImpl::AudioEngineImpl()
|
||||
: _lazyInitLoop(true)
|
||||
, _currentAudioID(0)
|
||||
, _scheduler(nullptr)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
AudioEngineImpl::~AudioEngineImpl()
|
||||
{
|
||||
if (_scheduler != nullptr)
|
||||
{
|
||||
_scheduler->unschedule(CC_SCHEDULE_SELECTOR(AudioEngineImpl::update), this);
|
||||
}
|
||||
|
||||
if (s_ALContext) {
|
||||
alDeleteSources(MAX_AUDIOINSTANCES, _alSources);
|
||||
|
||||
@@ -67,30 +133,31 @@ AudioEngineImpl::~AudioEngineImpl()
|
||||
alcDestroyContext(s_ALContext);
|
||||
s_ALContext = nullptr;
|
||||
}
|
||||
|
||||
if (s_ALDevice) {
|
||||
alcCloseDevice(s_ALDevice);
|
||||
s_ALDevice = nullptr;
|
||||
}
|
||||
|
||||
mpg123_exit();
|
||||
MPG123_LAZYINIT = true;
|
||||
AudioDecoderManager::destroy();
|
||||
}
|
||||
|
||||
bool AudioEngineImpl::init()
|
||||
{
|
||||
bool ret = false;
|
||||
do{
|
||||
s_ALDevice = alcOpenDevice(NULL);
|
||||
s_ALDevice = alcOpenDevice(nullptr);
|
||||
|
||||
if (s_ALDevice) {
|
||||
auto alError = alGetError();
|
||||
s_ALContext = alcCreateContext(s_ALDevice, NULL);
|
||||
alGetError();
|
||||
s_ALContext = alcCreateContext(s_ALDevice, nullptr);
|
||||
alcMakeContextCurrent(s_ALContext);
|
||||
|
||||
alGenSources(MAX_AUDIOINSTANCES, _alSources);
|
||||
alError = alGetError();
|
||||
if(alError != AL_NO_ERROR){
|
||||
ALOGE("%s:generating sources fail! error = %x\n", __FUNCTION__, alError);
|
||||
auto alError = alGetError();
|
||||
if(alError != AL_NO_ERROR)
|
||||
{
|
||||
ALOGE("%s:generating sources failed! error = %x\n", __FUNCTION__, alError);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -98,7 +165,9 @@ bool AudioEngineImpl::init()
|
||||
_alSourceUsed[_alSources[i]] = false;
|
||||
}
|
||||
|
||||
ret = true;
|
||||
_scheduler = Director::getInstance()->getScheduler();
|
||||
ret = AudioDecoderManager::init();
|
||||
ALOGI("OpenAL was initialized successfully!");
|
||||
}
|
||||
}while (false);
|
||||
|
||||
@@ -109,106 +178,80 @@ AudioCache* AudioEngineImpl::preload(const std::string& filePath, std::function<
|
||||
{
|
||||
AudioCache* audioCache = nullptr;
|
||||
|
||||
do
|
||||
{
|
||||
auto it = _audioCaches.find(filePath);
|
||||
if (it != _audioCaches.end())
|
||||
{
|
||||
audioCache = &it->second;
|
||||
if (callback && audioCache->_alBufferReady)
|
||||
{
|
||||
callback(true);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
AudioCache::FileFormat fileFormat = AudioCache::FileFormat::UNKNOWN;
|
||||
|
||||
std::string fileExtension = FileUtils::getInstance()->getFileExtension(filePath);
|
||||
if (fileExtension == ".ogg")
|
||||
{
|
||||
fileFormat = AudioCache::FileFormat::OGG;
|
||||
}
|
||||
else if (fileExtension == ".mp3")
|
||||
{
|
||||
fileFormat = AudioCache::FileFormat::MP3;
|
||||
|
||||
if (MPG123_LAZYINIT)
|
||||
{
|
||||
auto error = mpg123_init();
|
||||
if (error == MPG123_OK)
|
||||
{
|
||||
MPG123_LAZYINIT = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
ALOGE("Basic setup goes wrong: %s", mpg123_plain_strerror(error));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ALOGE("Unsupported media type file: %s\n", filePath.c_str());
|
||||
break;
|
||||
}
|
||||
|
||||
auto it = _audioCaches.find(filePath);
|
||||
if (it == _audioCaches.end()) {
|
||||
audioCache = &_audioCaches[filePath];
|
||||
audioCache->_fileFormat = fileFormat;
|
||||
|
||||
audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
|
||||
AudioEngine::addTask(std::bind(&AudioCache::readDataTask, audioCache));
|
||||
} while (false);
|
||||
|
||||
if (callback)
|
||||
{
|
||||
if (audioCache)
|
||||
{
|
||||
audioCache->addLoadCallback(callback);
|
||||
}
|
||||
else
|
||||
{
|
||||
callback(false);
|
||||
}
|
||||
unsigned int cacheId = audioCache->_id;
|
||||
auto isCacheDestroyed = audioCache->_isDestroyed;
|
||||
AudioEngine::addTask([audioCache, cacheId, isCacheDestroyed](){
|
||||
if (*isCacheDestroyed)
|
||||
{
|
||||
ALOGV("AudioCache (id=%u) was destroyed, no need to launch readDataTask.", cacheId);
|
||||
audioCache->setSkipReadDataTask(true);
|
||||
return;
|
||||
}
|
||||
audioCache->readDataTask(cacheId);
|
||||
});
|
||||
}
|
||||
else {
|
||||
audioCache = &it->second;
|
||||
}
|
||||
|
||||
if (audioCache && callback)
|
||||
{
|
||||
audioCache->addLoadCallback(callback);
|
||||
}
|
||||
return audioCache;
|
||||
}
|
||||
|
||||
int AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume)
|
||||
{
|
||||
bool availableSourceExist = false;
|
||||
ALuint alSource;
|
||||
if (s_ALDevice == nullptr) {
|
||||
return AudioEngine::INVALID_AUDIO_ID;
|
||||
}
|
||||
|
||||
bool sourceFlag = false;
|
||||
ALuint alSource = 0;
|
||||
for (int i = 0; i < MAX_AUDIOINSTANCES; ++i) {
|
||||
alSource = _alSources[i];
|
||||
|
||||
if ( !_alSourceUsed[alSource]) {
|
||||
availableSourceExist = true;
|
||||
sourceFlag = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(!availableSourceExist){
|
||||
if(!sourceFlag){
|
||||
return AudioEngine::INVALID_AUDIO_ID;
|
||||
}
|
||||
|
||||
AudioCache* audioCache = preload(filePath, nullptr);
|
||||
if (audioCache == nullptr)
|
||||
{
|
||||
auto player = new (std::nothrow) AudioPlayer;
|
||||
if (player == nullptr) {
|
||||
return AudioEngine::INVALID_AUDIO_ID;
|
||||
}
|
||||
|
||||
auto player = &_audioPlayers[_currentAudioID];
|
||||
player->_alSource = alSource;
|
||||
player->_loop = loop;
|
||||
player->_volume = volume;
|
||||
audioCache->addPlayCallback(std::bind(&AudioEngineImpl::_play2d, this, audioCache, _currentAudioID));
|
||||
|
||||
auto audioCache = preload(filePath, nullptr);
|
||||
if (audioCache == nullptr) {
|
||||
delete player;
|
||||
return AudioEngine::INVALID_AUDIO_ID;
|
||||
}
|
||||
|
||||
player->setCache(audioCache);
|
||||
_threadMutex.lock();
|
||||
_audioPlayers[_currentAudioID] = player;
|
||||
_threadMutex.unlock();
|
||||
|
||||
_alSourceUsed[alSource] = true;
|
||||
|
||||
audioCache->addPlayCallback(std::bind(&AudioEngineImpl::_play2d,this,audioCache,_currentAudioID));
|
||||
|
||||
if (_lazyInitLoop) {
|
||||
_lazyInitLoop = false;
|
||||
|
||||
auto scheduler = cocos2d::Director::getInstance()->getScheduler();
|
||||
scheduler->schedule(schedule_selector(AudioEngineImpl::update), this, 0.05f, false);
|
||||
_scheduler->schedule(CC_SCHEDULE_SELECTOR(AudioEngineImpl::update), this, 0.05f, false);
|
||||
}
|
||||
|
||||
return _currentAudioID++;
|
||||
@@ -216,71 +259,76 @@ int AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume
|
||||
|
||||
void AudioEngineImpl::_play2d(AudioCache *cache, int audioID)
|
||||
{
|
||||
if(cache->_alBufferReady){
|
||||
auto playerIt = _audioPlayers.find(audioID);
|
||||
if (playerIt != _audioPlayers.end()) {
|
||||
if (playerIt->second.play2d(cache)) {
|
||||
AudioEngine::_audioIDInfoMap[audioID].state = AudioEngine::AudioState::PLAYING;
|
||||
}
|
||||
else{
|
||||
_threadMutex.lock();
|
||||
_toRemoveAudioIDs.push_back(audioID);
|
||||
_threadMutex.unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
//Note: It may bn in sub thread or main thread :(
|
||||
if (!*cache->_isDestroyed && cache->_state == AudioCache::State::READY)
|
||||
{
|
||||
_threadMutex.lock();
|
||||
_toRemoveCaches.push_back(cache);
|
||||
_toRemoveAudioIDs.push_back(audioID);
|
||||
auto playerIt = _audioPlayers.find(audioID);
|
||||
if (playerIt != _audioPlayers.end() && playerIt->second->play2d()) {
|
||||
_scheduler->performFunctionInCocosThread([audioID](){
|
||||
|
||||
if (AudioEngine::_audioIDInfoMap.find(audioID) != AudioEngine::_audioIDInfoMap.end()) {
|
||||
AudioEngine::_audioIDInfoMap[audioID].state = AudioEngine::AudioState::PLAYING;
|
||||
}
|
||||
});
|
||||
}
|
||||
_threadMutex.unlock();
|
||||
}
|
||||
else
|
||||
{
|
||||
ALOGD("AudioEngineImpl::_play2d, cache was destroyed or not ready!");
|
||||
auto iter = _audioPlayers.find(audioID);
|
||||
if (iter != _audioPlayers.end())
|
||||
{
|
||||
iter->second->_removeByAudioEngine = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void AudioEngineImpl::setVolume(int audioID,float volume)
|
||||
{
|
||||
auto& player = _audioPlayers[audioID];
|
||||
player._volume = volume;
|
||||
auto player = _audioPlayers[audioID];
|
||||
player->_volume = volume;
|
||||
|
||||
if (player._ready) {
|
||||
alSourcef(_audioPlayers[audioID]._alSource, AL_GAIN, volume);
|
||||
if (player->_ready) {
|
||||
alSourcef(_audioPlayers[audioID]->_alSource, AL_GAIN, volume);
|
||||
|
||||
auto error = alGetError();
|
||||
if (error != AL_NO_ERROR) {
|
||||
ALOGE("%s: audio id = %d, error = %x\n", __FUNCTION__,audioID,error);
|
||||
ALOGE("%s: audio id = %d, error = %x", __FUNCTION__,audioID,error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void AudioEngineImpl::setLoop(int audioID, bool loop)
|
||||
{
|
||||
auto& player = _audioPlayers[audioID];
|
||||
auto player = _audioPlayers[audioID];
|
||||
|
||||
if (player._ready) {
|
||||
if (player._streamingSource) {
|
||||
player.setLoop(loop);
|
||||
if (player->_ready) {
|
||||
if (player->_streamingSource) {
|
||||
player->setLoop(loop);
|
||||
} else {
|
||||
if (loop) {
|
||||
alSourcei(player._alSource, AL_LOOPING, AL_TRUE);
|
||||
alSourcei(player->_alSource, AL_LOOPING, AL_TRUE);
|
||||
} else {
|
||||
alSourcei(player._alSource, AL_LOOPING, AL_FALSE);
|
||||
alSourcei(player->_alSource, AL_LOOPING, AL_FALSE);
|
||||
}
|
||||
|
||||
auto error = alGetError();
|
||||
if (error != AL_NO_ERROR) {
|
||||
ALOGE("%s: audio id = %d, error = %x\n", __FUNCTION__,audioID,error);
|
||||
ALOGE("%s: audio id = %d, error = %x", __FUNCTION__,audioID,error);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
player._loop = loop;
|
||||
player->_loop = loop;
|
||||
}
|
||||
}
|
||||
|
||||
bool AudioEngineImpl::pause(int audioID)
|
||||
{
|
||||
bool ret = true;
|
||||
alSourcePause(_audioPlayers[audioID]._alSource);
|
||||
alSourcePause(_audioPlayers[audioID]->_alSource);
|
||||
|
||||
auto error = alGetError();
|
||||
if (error != AL_NO_ERROR) {
|
||||
@@ -294,7 +342,7 @@ bool AudioEngineImpl::pause(int audioID)
|
||||
bool AudioEngineImpl::resume(int audioID)
|
||||
{
|
||||
bool ret = true;
|
||||
alSourcePlay(_audioPlayers[audioID]._alSource);
|
||||
alSourcePlay(_audioPlayers[audioID]->_alSource);
|
||||
|
||||
auto error = alGetError();
|
||||
if (error != AL_NO_ERROR) {
|
||||
@@ -305,66 +353,34 @@ bool AudioEngineImpl::resume(int audioID)
|
||||
return ret;
|
||||
}
|
||||
|
||||
bool AudioEngineImpl::stop(int audioID)
|
||||
void AudioEngineImpl::stop(int audioID)
|
||||
{
|
||||
bool ret = true;
|
||||
auto& player = _audioPlayers[audioID];
|
||||
if (player._ready) {
|
||||
alSourceStop(player._alSource);
|
||||
|
||||
auto error = alGetError();
|
||||
if (error != AL_NO_ERROR) {
|
||||
ret = false;
|
||||
ALOGE("%s: audio id = %d, error = %x\n", __FUNCTION__,audioID,error);
|
||||
}
|
||||
}
|
||||
|
||||
alSourcei(player._alSource, AL_BUFFER, NULL);
|
||||
|
||||
_alSourceUsed[player._alSource] = false;
|
||||
if (player._streamingSource)
|
||||
{
|
||||
player._ready = false;
|
||||
player.notifyExitThread();
|
||||
}
|
||||
else
|
||||
{
|
||||
_audioPlayers.erase(audioID);
|
||||
}
|
||||
|
||||
return ret;
|
||||
auto player = _audioPlayers[audioID];
|
||||
player->destroy();
|
||||
//Note: Don't set the flag to false here, it should be set in 'update' function.
|
||||
// Otherwise, the state got from alSourceState may be wrong
|
||||
// _alSourceUsed[player->_alSource] = false;
|
||||
}
|
||||
|
||||
void AudioEngineImpl::stopAll()
|
||||
{
|
||||
for(int index = 0; index < MAX_AUDIOINSTANCES; ++index)
|
||||
for(auto&& player : _audioPlayers)
|
||||
{
|
||||
alSourceStop(_alSources[index]);
|
||||
alSourcei(_alSources[index], AL_BUFFER, NULL);
|
||||
_alSourceUsed[_alSources[index]] = false;
|
||||
}
|
||||
|
||||
for (auto it = _audioPlayers.begin(); it != _audioPlayers.end();)
|
||||
{
|
||||
auto& player = it->second;
|
||||
if (player._streamingSource)
|
||||
{
|
||||
player._ready = false;
|
||||
player.notifyExitThread();
|
||||
++it;
|
||||
}
|
||||
else
|
||||
{
|
||||
it = _audioPlayers.erase(it);
|
||||
}
|
||||
player.second->destroy();
|
||||
}
|
||||
//Note: Don't set the flag to false here, it should be set in 'update' function.
|
||||
// Otherwise, the state got from alSourceState may be wrong
|
||||
// for(int index = 0; index < MAX_AUDIOINSTANCES; ++index)
|
||||
// {
|
||||
// _alSourceUsed[_alSources[index]] = false;
|
||||
// }
|
||||
}
|
||||
|
||||
float AudioEngineImpl::getDuration(int audioID)
|
||||
{
|
||||
auto& player = _audioPlayers[audioID];
|
||||
if(player._ready){
|
||||
return player._audioCache->_duration;
|
||||
auto player = _audioPlayers[audioID];
|
||||
if(player->_ready){
|
||||
return player->_audioCache->_duration;
|
||||
} else {
|
||||
return AudioEngine::TIME_UNKNOWN;
|
||||
}
|
||||
@@ -373,12 +389,12 @@ float AudioEngineImpl::getDuration(int audioID)
|
||||
float AudioEngineImpl::getCurrentTime(int audioID)
|
||||
{
|
||||
float ret = 0.0f;
|
||||
auto& player = _audioPlayers[audioID];
|
||||
if(player._ready){
|
||||
if (player._streamingSource) {
|
||||
ret = player.getTime();
|
||||
auto player = _audioPlayers[audioID];
|
||||
if(player->_ready){
|
||||
if (player->_streamingSource) {
|
||||
ret = player->getTime();
|
||||
} else {
|
||||
alGetSourcef(player._alSource, AL_SEC_OFFSET, &ret);
|
||||
alGetSourcef(player->_alSource, AL_SEC_OFFSET, &ret);
|
||||
|
||||
auto error = alGetError();
|
||||
if (error != AL_NO_ERROR) {
|
||||
@@ -393,23 +409,29 @@ float AudioEngineImpl::getCurrentTime(int audioID)
|
||||
bool AudioEngineImpl::setCurrentTime(int audioID, float time)
|
||||
{
|
||||
bool ret = false;
|
||||
auto& player = _audioPlayers[audioID];
|
||||
auto player = _audioPlayers[audioID];
|
||||
|
||||
do {
|
||||
if (!player._ready) {
|
||||
if (!player->_ready) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (player._streamingSource) {
|
||||
ret = player.setTime(time);
|
||||
if (player->_streamingSource) {
|
||||
ret = player->setTime(time);
|
||||
break;
|
||||
}
|
||||
else {
|
||||
alSourcef(player._alSource, AL_SEC_OFFSET, time);
|
||||
if (player->_audioCache->_framesRead != player->_audioCache->_totalFrames &&
|
||||
(time * player->_audioCache->_sampleRate) > player->_audioCache->_framesRead) {
|
||||
ALOGE("%s: audio id = %d", __FUNCTION__,audioID);
|
||||
break;
|
||||
}
|
||||
|
||||
alSourcef(player->_alSource, AL_SEC_OFFSET, time);
|
||||
|
||||
auto error = alGetError();
|
||||
if (error != AL_NO_ERROR) {
|
||||
ALOGE("%s: audio id = %d, error = %x\n", __FUNCTION__,audioID,error);
|
||||
ALOGE("%s: audio id = %d, error = %x", __FUNCTION__,audioID,error);
|
||||
}
|
||||
ret = true;
|
||||
}
|
||||
@@ -420,70 +442,52 @@ bool AudioEngineImpl::setCurrentTime(int audioID, float time)
|
||||
|
||||
void AudioEngineImpl::setFinishCallback(int audioID, const std::function<void (int, const std::string &)> &callback)
|
||||
{
|
||||
_audioPlayers[audioID]._finishCallbak = callback;
|
||||
_audioPlayers[audioID]->_finishCallbak = callback;
|
||||
}
|
||||
|
||||
void AudioEngineImpl::update(float dt)
|
||||
{
|
||||
ALint sourceState;
|
||||
int audioID;
|
||||
AudioPlayer* player;
|
||||
ALuint alSource;
|
||||
|
||||
if (_threadMutex.try_lock()) {
|
||||
size_t removeAudioCount = _toRemoveAudioIDs.size();
|
||||
for (size_t index = 0; index < removeAudioCount; ++index) {
|
||||
audioID = _toRemoveAudioIDs[index];
|
||||
auto playerIt = _audioPlayers.find(audioID);
|
||||
if (playerIt != _audioPlayers.end()) {
|
||||
_alSourceUsed[playerIt->second._alSource] = false;
|
||||
if(playerIt->second._finishCallbak) {
|
||||
auto& audioInfo = AudioEngine::_audioIDInfoMap[audioID];
|
||||
playerIt->second._finishCallbak(audioID, *audioInfo.filePath);
|
||||
}
|
||||
_audioPlayers.erase(audioID);
|
||||
AudioEngine::remove(audioID);
|
||||
}
|
||||
}
|
||||
size_t removeCacheCount = _toRemoveCaches.size();
|
||||
for (size_t index = 0; index < removeCacheCount; ++index) {
|
||||
auto itEnd = _audioCaches.end();
|
||||
for (auto it = _audioCaches.begin(); it != itEnd; ++it) {
|
||||
if (&it->second == _toRemoveCaches[index]) {
|
||||
_audioCaches.erase(it);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
_threadMutex.unlock();
|
||||
}
|
||||
// ALOGV("AudioPlayer count: %d", (int)_audioPlayers.size());
|
||||
|
||||
for (auto it = _audioPlayers.begin(); it != _audioPlayers.end(); ) {
|
||||
audioID = it->first;
|
||||
auto& player = it->second;
|
||||
alGetSourcei(player._alSource, AL_SOURCE_STATE, &sourceState);
|
||||
|
||||
if (player._readForRemove && !player._ready)
|
||||
player = it->second;
|
||||
alSource = player->_alSource;
|
||||
alGetSourcei(alSource, AL_SOURCE_STATE, &sourceState);
|
||||
|
||||
if (player->_removeByAudioEngine)
|
||||
{
|
||||
AudioEngine::remove(audioID);
|
||||
_threadMutex.lock();
|
||||
it = _audioPlayers.erase(it);
|
||||
_threadMutex.unlock();
|
||||
delete player;
|
||||
_alSourceUsed[alSource] = false;
|
||||
}
|
||||
else if (player._ready && sourceState == AL_STOPPED) {
|
||||
_alSourceUsed[player._alSource] = false;
|
||||
if (player._finishCallbak) {
|
||||
else if (player->_ready && sourceState == AL_STOPPED) {
|
||||
|
||||
std::string filePath;
|
||||
if (player->_finishCallbak) {
|
||||
auto& audioInfo = AudioEngine::_audioIDInfoMap[audioID];
|
||||
player._finishCallbak(audioID, *audioInfo.filePath);
|
||||
filePath = *audioInfo.filePath;
|
||||
}
|
||||
|
||||
AudioEngine::remove(audioID);
|
||||
|
||||
_threadMutex.lock();
|
||||
it = _audioPlayers.erase(it);
|
||||
_threadMutex.unlock();
|
||||
|
||||
if (player._streamingSource)
|
||||
{
|
||||
player._ready = false;
|
||||
player.notifyExitThread();
|
||||
++it;
|
||||
}
|
||||
else
|
||||
{
|
||||
it = _audioPlayers.erase(it);
|
||||
if (player->_finishCallbak) {
|
||||
player->_finishCallbak(audioID, filePath); //FIXME: callback will delay 50ms
|
||||
}
|
||||
delete player;
|
||||
_alSourceUsed[alSource] = false;
|
||||
}
|
||||
else{
|
||||
++it;
|
||||
@@ -492,9 +496,7 @@ void AudioEngineImpl::update(float dt)
|
||||
|
||||
if(_audioPlayers.empty()){
|
||||
_lazyInitLoop = true;
|
||||
|
||||
auto scheduler = cocos2d::Director::getInstance()->getScheduler();
|
||||
scheduler->unschedule(schedule_selector(AudioEngineImpl::update), this);
|
||||
_scheduler->unschedule(CC_SCHEDULE_SELECTOR(AudioEngineImpl::update), this);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2014 Chukong Technologies Inc.
|
||||
Copyright (c) 2014-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -35,7 +35,10 @@
|
||||
#include "audio/win32/AudioPlayer.h"
|
||||
|
||||
NS_CC_BEGIN
|
||||
namespace experimental{
|
||||
|
||||
class Scheduler;
|
||||
|
||||
namespace experimental {
|
||||
#define MAX_AUDIOINSTANCES 32
|
||||
|
||||
class CC_DLL AudioEngineImpl : public cocos2d::Ref
|
||||
@@ -50,7 +53,7 @@ public:
|
||||
void setLoop(int audioID, bool loop);
|
||||
bool pause(int audioID);
|
||||
bool resume(int audioID);
|
||||
bool stop(int audioID);
|
||||
void stop(int audioID);
|
||||
void stopAll();
|
||||
float getDuration(int audioID);
|
||||
float getCurrentTime(int audioID);
|
||||
@@ -60,7 +63,6 @@ public:
|
||||
void uncache(const std::string& filePath);
|
||||
void uncacheAll();
|
||||
AudioCache* preload(const std::string& filePath, std::function<void(bool)> callback);
|
||||
|
||||
void update(float dt);
|
||||
|
||||
private:
|
||||
@@ -75,17 +77,13 @@ private:
|
||||
std::unordered_map<std::string, AudioCache> _audioCaches;
|
||||
|
||||
//audioID,AudioInfo
|
||||
std::unordered_map<int, AudioPlayer> _audioPlayers;
|
||||
|
||||
std::unordered_map<int, AudioPlayer*> _audioPlayers;
|
||||
std::mutex _threadMutex;
|
||||
|
||||
std::vector<AudioCache*> _toRemoveCaches;
|
||||
std::vector<int> _toRemoveAudioIDs;
|
||||
|
||||
bool _lazyInitLoop;
|
||||
|
||||
int _currentAudioID;
|
||||
|
||||
Scheduler* _scheduler;
|
||||
};
|
||||
}
|
||||
NS_CC_END
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2016-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
#pragma once
|
||||
|
||||
#define QUEUEBUFFER_NUM (3)
|
||||
#define QUEUEBUFFER_TIME_STEP (0.1f)
|
||||
|
||||
// log, CCLOG aren't threadsafe, since we uses sub threads for parsing pcm data, threadsafe log output
|
||||
// is needed. Define the following macros (ALOGV, ALOGD, ALOGI, ALOGW, ALOGE) for threadsafe log output.
|
||||
|
||||
//FIXME:Move the definition of the following macros to a separated file.
|
||||
|
||||
void audioLog(const char * format, ...);
|
||||
|
||||
#define QUOTEME_(x) #x
|
||||
#define QUOTEME(x) QUOTEME_(x)
|
||||
|
||||
#if defined(COCOS2D_DEBUG) && COCOS2D_DEBUG > 0
|
||||
#define ALOGV(fmt, ...) audioLog("V/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__)
|
||||
#else
|
||||
#define ALOGV(fmt, ...) do {} while(false)
|
||||
#endif
|
||||
#define ALOGD(fmt, ...) audioLog("D/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__)
|
||||
#define ALOGI(fmt, ...) audioLog("I/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__)
|
||||
#define ALOGW(fmt, ...) audioLog("W/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__)
|
||||
#define ALOGE(fmt, ...) audioLog("E/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__)
|
||||
|
||||
#if defined(COCOS2D_DEBUG) && COCOS2D_DEBUG > 0
|
||||
#define CHECK_AL_ERROR_DEBUG() \
|
||||
do { \
|
||||
GLenum __error = alGetError(); \
|
||||
if (__error) { \
|
||||
ALOGE("OpenAL error 0x%04X in %s %s %d\n", __error, __FILE__, __FUNCTION__, __LINE__); \
|
||||
} \
|
||||
} while (false)
|
||||
#else
|
||||
#define CHECK_AL_ERROR_DEBUG()
|
||||
#endif
|
||||
|
||||
#define BREAK_IF(condition) \
|
||||
if (!!(condition)) { \
|
||||
break; \
|
||||
}
|
||||
|
||||
#define BREAK_IF_ERR_LOG(condition, fmt, ...) \
|
||||
if (!!(condition)) { \
|
||||
ALOGE("(" QUOTEME(condition) ") failed, message: " fmt, ##__VA_ARGS__); \
|
||||
break; \
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2014 Chukong Technologies Inc.
|
||||
Copyright (c) 2014-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -29,302 +29,301 @@
|
||||
#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
|
||||
#include "audio/win32/AudioPlayer.h"
|
||||
#include "audio/win32/AudioCache.h"
|
||||
#include "base/CCConsole.h"
|
||||
#include "platform/CCFileUtils.h"
|
||||
#include "mpg123/mpg123.h"
|
||||
#include "vorbis/codec.h"
|
||||
#include "vorbis/vorbisfile.h"
|
||||
#include "audio/win32/AudioDecoderManager.h"
|
||||
#include "audio/win32/Audiodecoder.h"
|
||||
|
||||
#define VERY_VERY_VERBOSE_LOGGING
|
||||
#ifdef VERY_VERY_VERBOSE_LOGGING
|
||||
#define ALOGVV ALOGV
|
||||
#else
|
||||
#define ALOGVV(...) do{} while(false)
|
||||
#endif
|
||||
|
||||
using namespace cocos2d;
|
||||
using namespace cocos2d::experimental;
|
||||
|
||||
AudioPlayer::AudioPlayer()
|
||||
: _exitThread(false)
|
||||
, _timeDirty(false)
|
||||
, _streamingSource(false)
|
||||
, _currTime(0.0f)
|
||||
, _finishCallbak(nullptr)
|
||||
, _ready(false)
|
||||
, _audioCache(nullptr)
|
||||
, _readForRemove(false)
|
||||
{
|
||||
|
||||
namespace {
|
||||
unsigned int __idIndex = 0;
|
||||
}
|
||||
|
||||
AudioPlayer::AudioPlayer(const AudioPlayer& player)
|
||||
AudioPlayer::AudioPlayer()
|
||||
: _audioCache(nullptr)
|
||||
, _finishCallbak(nullptr)
|
||||
, _isDestroyed(false)
|
||||
, _removeByAudioEngine(false)
|
||||
, _ready(false)
|
||||
, _currTime(0.0f)
|
||||
, _streamingSource(false)
|
||||
, _rotateBufferThread(nullptr)
|
||||
, _timeDirty(false)
|
||||
, _isRotateThreadExited(false)
|
||||
, _id(++__idIndex)
|
||||
{
|
||||
_exitThread = player._exitThread;
|
||||
_timeDirty = player._timeDirty;
|
||||
_streamingSource = player._streamingSource;
|
||||
_currTime = player._currTime;
|
||||
_finishCallbak = player._finishCallbak;
|
||||
_ready = player._ready;
|
||||
_audioCache = player._audioCache;
|
||||
_readForRemove = player._readForRemove;
|
||||
memset(_bufferIds, 0, sizeof(_bufferIds));
|
||||
}
|
||||
|
||||
AudioPlayer::~AudioPlayer()
|
||||
{
|
||||
if (_audioCache && _audioCache->_queBufferFrames > 0) {
|
||||
alDeleteBuffers(QUEUEBUFFER_NUM, _bufferIds);
|
||||
}
|
||||
}
|
||||
|
||||
void AudioPlayer::notifyExitThread()
|
||||
{
|
||||
if (_audioCache && _audioCache->_queBufferFrames > 0) {
|
||||
std::unique_lock<std::mutex> lk(_sleepMutex);
|
||||
_exitThread = true;
|
||||
_sleepCondition.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
bool AudioPlayer::play2d(AudioCache* cache)
|
||||
{
|
||||
if (!cache->_alBufferReady) {
|
||||
return false;
|
||||
}
|
||||
_audioCache = cache;
|
||||
|
||||
alSourcei(_alSource, AL_BUFFER, NULL);
|
||||
alSourcef(_alSource, AL_PITCH, 1.0f);
|
||||
alSourcef(_alSource, AL_GAIN, _volume);
|
||||
|
||||
if (_audioCache->_queBufferFrames == 0) {
|
||||
if (_loop) {
|
||||
alSourcei(_alSource, AL_LOOPING, AL_TRUE);
|
||||
}
|
||||
else {
|
||||
alSourcei(_alSource, AL_LOOPING, AL_FALSE);
|
||||
}
|
||||
alSourcei(_alSource, AL_BUFFER, _audioCache->_alBufferId);
|
||||
|
||||
} else {
|
||||
_streamingSource = true;
|
||||
alSourcei(_alSource, AL_LOOPING, AL_FALSE);
|
||||
|
||||
auto alError = alGetError();
|
||||
alGenBuffers(QUEUEBUFFER_NUM, _bufferIds);
|
||||
alError = alGetError();
|
||||
if (alError == AL_NO_ERROR) {
|
||||
for (int index = 0; index < QUEUEBUFFER_NUM; ++index) {
|
||||
alBufferData(_bufferIds[index], _audioCache->_alBufferFormat, _audioCache->_queBuffers[index], _audioCache->_queBufferSize[index], _audioCache->_sampleRate);
|
||||
}
|
||||
alSourceQueueBuffers(_alSource, QUEUEBUFFER_NUM, _bufferIds);
|
||||
}
|
||||
else {
|
||||
ALOGE("%s:alGenBuffers error code:%x", __FUNCTION__,alError);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
ALOGVV("~AudioPlayer() (%p), id=%u", this, _id);
|
||||
destroy();
|
||||
|
||||
if (_streamingSource)
|
||||
{
|
||||
_rotateBufferThread = std::thread(&AudioPlayer::rotateBufferThread, this, _audioCache->_queBufferFrames * QUEUEBUFFER_NUM + 1);
|
||||
_rotateBufferThread.detach();
|
||||
alDeleteBuffers(3, _bufferIds);
|
||||
}
|
||||
else
|
||||
{
|
||||
alSourcePlay(_alSource);
|
||||
|
||||
auto alError = alGetError();
|
||||
if (alError != AL_NO_ERROR) {
|
||||
ALOGE("%s:alSourcePlay error code:%x\n", __FUNCTION__, alError);
|
||||
return false;
|
||||
}
|
||||
|
||||
_ready = true;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
int AudioPlayer::readPcmData(char* buffer, int bufferSize, const std::function<int/*readBytes*/(char* /*buf*/, int /*bytesToRead*/)>& fileReader)
|
||||
void AudioPlayer::destroy()
|
||||
{
|
||||
assert(buffer != nullptr && bufferSize > 0);
|
||||
if (_isDestroyed)
|
||||
return;
|
||||
|
||||
ALOGVV("AudioPlayer::destroy begin, id=%u", _id);
|
||||
|
||||
_isDestroyed = true;
|
||||
|
||||
int readBytes = 0;
|
||||
int readBytesOnce = 0;
|
||||
int remainBytes = bufferSize;
|
||||
do
|
||||
{
|
||||
readBytesOnce = fileReader(buffer + readBytes, remainBytes);
|
||||
if (readBytesOnce > 0)
|
||||
if (_audioCache != nullptr)
|
||||
{
|
||||
readBytes += readBytesOnce;
|
||||
remainBytes -= readBytesOnce;
|
||||
}
|
||||
} while (readBytesOnce > 0 && readBytes < bufferSize);
|
||||
if (_audioCache->_state == AudioCache::State::INITIAL)
|
||||
{
|
||||
ALOGV("AudioPlayer::destroy, id=%u, cache isn't ready!", _id);
|
||||
break;
|
||||
}
|
||||
|
||||
return readBytes;
|
||||
while (!_audioCache->_isLoadingFinished)
|
||||
{
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(5));
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for play2d to be finished.
|
||||
_play2dMutex.lock();
|
||||
_play2dMutex.unlock();
|
||||
|
||||
if (_streamingSource)
|
||||
{
|
||||
if (_rotateBufferThread != nullptr)
|
||||
{
|
||||
while (!_isRotateThreadExited)
|
||||
{
|
||||
_sleepCondition.notify_one();
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(5));
|
||||
}
|
||||
|
||||
if (_rotateBufferThread->joinable()) {
|
||||
_rotateBufferThread->join();
|
||||
}
|
||||
|
||||
delete _rotateBufferThread;
|
||||
_rotateBufferThread = nullptr;
|
||||
ALOGVV("rotateBufferThread exited!");
|
||||
}
|
||||
}
|
||||
} while(false);
|
||||
|
||||
ALOGVV("Before alSourceStop");
|
||||
alSourceStop(_alSource); CHECK_AL_ERROR_DEBUG();
|
||||
ALOGVV("Before alSourcei");
|
||||
alSourcei(_alSource, AL_BUFFER, NULL); CHECK_AL_ERROR_DEBUG();
|
||||
|
||||
_removeByAudioEngine = true;
|
||||
|
||||
_ready = false;
|
||||
ALOGVV("AudioPlayer::destroy end, id=%u", _id);
|
||||
}
|
||||
|
||||
void AudioPlayer::setCache(AudioCache* cache)
|
||||
{
|
||||
_audioCache = cache;
|
||||
}
|
||||
|
||||
bool AudioPlayer::play2d()
|
||||
{
|
||||
_play2dMutex.lock();
|
||||
ALOGV("AudioPlayer::play2d, _alSource: %u, player id=%u", _alSource, _id);
|
||||
|
||||
/*********************************************************************/
|
||||
/* Note that it may be in sub thread or in main thread. **/
|
||||
/*********************************************************************/
|
||||
bool ret = false;
|
||||
do
|
||||
{
|
||||
if (_audioCache->_state != AudioCache::State::READY)
|
||||
{
|
||||
ALOGE("alBuffer isn't ready for play!");
|
||||
break;
|
||||
}
|
||||
|
||||
alSourcei(_alSource, AL_BUFFER, 0);CHECK_AL_ERROR_DEBUG();
|
||||
alSourcef(_alSource, AL_PITCH, 1.0f);CHECK_AL_ERROR_DEBUG();
|
||||
alSourcef(_alSource, AL_GAIN, _volume);CHECK_AL_ERROR_DEBUG();
|
||||
alSourcei(_alSource, AL_LOOPING, AL_FALSE);CHECK_AL_ERROR_DEBUG();
|
||||
|
||||
if (_audioCache->_queBufferFrames == 0)
|
||||
{
|
||||
if (_loop) {
|
||||
alSourcei(_alSource, AL_LOOPING, AL_TRUE);
|
||||
CHECK_AL_ERROR_DEBUG();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
alGenBuffers(3, _bufferIds);
|
||||
|
||||
auto alError = alGetError();
|
||||
if (alError == AL_NO_ERROR)
|
||||
{
|
||||
for (int index = 0; index < QUEUEBUFFER_NUM; ++index)
|
||||
{
|
||||
alBufferData(_bufferIds[index], _audioCache->_format, _audioCache->_queBuffers[index], _audioCache->_queBufferSize[index], _audioCache->_sampleRate);
|
||||
}
|
||||
CHECK_AL_ERROR_DEBUG();
|
||||
}
|
||||
else
|
||||
{
|
||||
ALOGE("%s:alGenBuffers error code:%x", __FUNCTION__,alError);
|
||||
break;
|
||||
}
|
||||
_streamingSource = true;
|
||||
}
|
||||
|
||||
{
|
||||
std::unique_lock<std::mutex> lk(_sleepMutex);
|
||||
if (_isDestroyed)
|
||||
break;
|
||||
|
||||
if (_streamingSource)
|
||||
{
|
||||
alSourceQueueBuffers(_alSource, QUEUEBUFFER_NUM, _bufferIds);
|
||||
CHECK_AL_ERROR_DEBUG();
|
||||
_rotateBufferThread = new std::thread(&AudioPlayer::rotateBufferThread, this, _audioCache->_queBufferFrames * QUEUEBUFFER_NUM + 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
alSourcei(_alSource, AL_BUFFER, _audioCache->_alBufferId);
|
||||
CHECK_AL_ERROR_DEBUG();
|
||||
}
|
||||
|
||||
alSourcePlay(_alSource);
|
||||
}
|
||||
|
||||
auto alError = alGetError();
|
||||
if (alError != AL_NO_ERROR)
|
||||
{
|
||||
ALOGE("%s:alSourcePlay error code:%x", __FUNCTION__,alError);
|
||||
break;
|
||||
}
|
||||
|
||||
ALint state;
|
||||
alGetSourcei(_alSource, AL_SOURCE_STATE, &state);
|
||||
if (state != AL_PLAYING)
|
||||
{
|
||||
ALOGE("state isn't playing, %d, %s, cache id=%u, player id=%u", state, _audioCache->_fileFullPath.c_str(), _audioCache->_id, _id);
|
||||
}
|
||||
assert(state == AL_PLAYING);
|
||||
_ready = true;
|
||||
ret = true;
|
||||
} while (false);
|
||||
|
||||
if (!ret)
|
||||
{
|
||||
_removeByAudioEngine = true;
|
||||
}
|
||||
|
||||
_play2dMutex.unlock();
|
||||
return ret;
|
||||
}
|
||||
|
||||
void AudioPlayer::rotateBufferThread(int offsetFrame)
|
||||
{
|
||||
ALint sourceState;
|
||||
ALint bufferProcessed = 0;
|
||||
mpg123_handle* mpg123handle = nullptr;
|
||||
OggVorbis_File* vorbisFile = nullptr;
|
||||
|
||||
std::function<int(char*, int)> fileReader = nullptr;
|
||||
std::function<void(int)> fileSeeker = nullptr;
|
||||
|
||||
auto audioFileFormat = _audioCache->_fileFormat;
|
||||
char* tmpBuffer = (char*)malloc(_audioCache->_queBufferBytes);
|
||||
|
||||
switch (audioFileFormat)
|
||||
char* tmpBuffer = nullptr;
|
||||
AudioDecoder* decoder = AudioDecoderManager::createDecoder(_audioCache->_fileFullPath.c_str());
|
||||
do
|
||||
{
|
||||
case AudioCache::FileFormat::MP3:
|
||||
{
|
||||
int error = MPG123_OK;
|
||||
mpg123handle = mpg123_new(nullptr, &error);
|
||||
if (!mpg123handle){
|
||||
ALOGE("Basic setup goes wrong: %s", mpg123_plain_strerror(error));
|
||||
goto ExitBufferThread;
|
||||
}
|
||||
long rate = 0;
|
||||
int channels = 0;
|
||||
int mp3Encoding = 0;
|
||||
if (mpg123_open(mpg123handle,_audioCache->_fileFullPath.c_str()) != MPG123_OK
|
||||
|| mpg123_getformat(mpg123handle, &rate, &channels, &mp3Encoding) != MPG123_OK){
|
||||
ALOGE("Trouble with mpg123: %s\n", mpg123_strerror(mpg123handle) );
|
||||
goto ExitBufferThread;
|
||||
}
|
||||
BREAK_IF(decoder == nullptr || !decoder->open(_audioCache->_fileFullPath.c_str()));
|
||||
|
||||
/* Ensure that this output format will not change (it could, when we allow it). */
|
||||
mpg123_format_none(mpg123handle);
|
||||
mpg123_format(mpg123handle, _audioCache->_sampleRate, _audioCache->_channels, _audioCache->_mp3Encoding);
|
||||
uint32_t framesRead = 0;
|
||||
const uint32_t framesToRead = _audioCache->_queBufferFrames;
|
||||
const uint32_t bufferSize = framesToRead * decoder->getBytesPerFrame();
|
||||
tmpBuffer = (char*)malloc(bufferSize);
|
||||
memset(tmpBuffer, 0, bufferSize);
|
||||
|
||||
if (offsetFrame != 0) {
|
||||
mpg123_seek(mpg123handle,offsetFrame,SEEK_SET);
|
||||
}
|
||||
break;
|
||||
if (offsetFrame != 0) {
|
||||
decoder->seek(offsetFrame);
|
||||
}
|
||||
case AudioCache::FileFormat::OGG:
|
||||
{
|
||||
vorbisFile = new OggVorbis_File;
|
||||
int openCode;
|
||||
if (openCode = ov_fopen(FileUtils::getInstance()->getSuitableFOpen(_audioCache->_fileFullPath).c_str(), vorbisFile)){
|
||||
ALOGE("Input does not appear to be an Ogg bitstream: %s. Code: 0x%x\n", _audioCache->_fileFullPath.c_str(), openCode);
|
||||
goto ExitBufferThread;
|
||||
}
|
||||
if (offsetFrame != 0) {
|
||||
ov_pcm_seek(vorbisFile,offsetFrame);
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
alSourcePlay(_alSource);
|
||||
ALint sourceState;
|
||||
ALint bufferProcessed = 0;
|
||||
bool needToExitThread = false;
|
||||
|
||||
if (audioFileFormat == AudioCache::FileFormat::MP3)
|
||||
{
|
||||
fileReader = [&](char* buffer, int bufferSize) -> int {
|
||||
size_t ret = 0;
|
||||
mpg123_read(mpg123handle, (unsigned char*)buffer, bufferSize, &ret);
|
||||
return ret;
|
||||
};
|
||||
|
||||
fileSeeker = [&](int pos) {
|
||||
mpg123_seek(mpg123handle, pos, SEEK_SET);
|
||||
};
|
||||
}
|
||||
else if (audioFileFormat == AudioCache::FileFormat::OGG)
|
||||
{
|
||||
fileReader = [&](char* buffer, int bufferSize) -> int {
|
||||
int current_section = 0;
|
||||
return ov_read(vorbisFile, buffer, bufferSize, 0, 2, 1, ¤t_section);
|
||||
};
|
||||
|
||||
fileSeeker = [&](int pos) {
|
||||
ov_pcm_seek(vorbisFile, pos);
|
||||
};
|
||||
}
|
||||
|
||||
while (!_exitThread) {
|
||||
alGetSourcei(_alSource, AL_SOURCE_STATE, &sourceState);
|
||||
if (sourceState == AL_PLAYING) {
|
||||
_ready = true;
|
||||
|
||||
alGetSourcei(_alSource, AL_BUFFERS_PROCESSED, &bufferProcessed);
|
||||
while (bufferProcessed > 0) {
|
||||
bufferProcessed--;
|
||||
if (_timeDirty) {
|
||||
_timeDirty = false;
|
||||
offsetFrame = _currTime * _audioCache->_sampleRate;
|
||||
fileSeeker(offsetFrame);
|
||||
}
|
||||
else {
|
||||
_currTime += QUEUEBUFFER_TIME_STEP;
|
||||
if (_currTime > _audioCache->_duration) {
|
||||
if (_loop) {
|
||||
_currTime = 0.0f;
|
||||
} else {
|
||||
_currTime = _audioCache->_duration;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int readRet = readPcmData(tmpBuffer, _audioCache->_queBufferBytes, fileReader);
|
||||
if (readRet <= 0) {
|
||||
if (_loop) {
|
||||
fileSeeker(0);
|
||||
readRet = readPcmData(tmpBuffer, _audioCache->_queBufferBytes, fileReader);
|
||||
while (!_isDestroyed) {
|
||||
alGetSourcei(_alSource, AL_SOURCE_STATE, &sourceState);
|
||||
if (sourceState == AL_PLAYING) {
|
||||
alGetSourcei(_alSource, AL_BUFFERS_PROCESSED, &bufferProcessed);
|
||||
while (bufferProcessed > 0) {
|
||||
bufferProcessed--;
|
||||
if (_timeDirty) {
|
||||
_timeDirty = false;
|
||||
offsetFrame = _currTime * decoder->getSampleRate();
|
||||
decoder->seek(offsetFrame);
|
||||
}
|
||||
else {
|
||||
_exitThread = true;
|
||||
break;
|
||||
_currTime += QUEUEBUFFER_TIME_STEP;
|
||||
if (_currTime > _audioCache->_duration) {
|
||||
if (_loop) {
|
||||
_currTime = 0.0f;
|
||||
} else {
|
||||
_currTime = _audioCache->_duration;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_audioCache->_bytesOfRead += readRet;
|
||||
}
|
||||
|
||||
//ALOGV("readRet: %d, queBufferBytes: %d", (int)readRet, _audioCache->_queBufferBytes);
|
||||
ALuint bid;
|
||||
alSourceUnqueueBuffers(_alSource, 1, &bid);
|
||||
CHECK_AL_ERROR_DEBUG();
|
||||
alBufferData(bid, _audioCache->_alBufferFormat, tmpBuffer, readRet, _audioCache->_sampleRate);
|
||||
CHECK_AL_ERROR_DEBUG();
|
||||
alSourceQueueBuffers(_alSource, 1, &bid);
|
||||
CHECK_AL_ERROR_DEBUG();
|
||||
framesRead = decoder->readFixedFrames(framesToRead, tmpBuffer);
|
||||
|
||||
if (framesRead == 0) {
|
||||
if (_loop) {
|
||||
decoder->seek(0);
|
||||
framesRead = decoder->readFixedFrames(framesToRead, tmpBuffer);
|
||||
} else {
|
||||
needToExitThread = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
ALuint bid;
|
||||
alSourceUnqueueBuffers(_alSource, 1, &bid);
|
||||
alBufferData(bid, _audioCache->_format, tmpBuffer, framesRead * decoder->getBytesPerFrame(), decoder->getSampleRate());
|
||||
alSourceQueueBuffers(_alSource, 1, &bid);
|
||||
}
|
||||
}
|
||||
|
||||
std::unique_lock<std::mutex> lk(_sleepMutex);
|
||||
if (_isDestroyed || needToExitThread) {
|
||||
break;
|
||||
}
|
||||
|
||||
_sleepCondition.wait_for(lk,std::chrono::milliseconds(75));
|
||||
}
|
||||
|
||||
std::unique_lock<std::mutex> lk(_sleepMutex);
|
||||
if (_exitThread)
|
||||
{
|
||||
ALOGV("thread exit...");
|
||||
break;
|
||||
}
|
||||
} while(false);
|
||||
|
||||
_sleepCondition.wait_for(lk,std::chrono::milliseconds(35));
|
||||
}
|
||||
ExitBufferThread:
|
||||
switch (audioFileFormat)
|
||||
ALOGV("Exit rotate buffer thread ...");
|
||||
if (decoder != nullptr)
|
||||
{
|
||||
case AudioCache::FileFormat::OGG:
|
||||
ov_clear(vorbisFile);
|
||||
delete vorbisFile;
|
||||
break;
|
||||
case AudioCache::FileFormat::MP3:
|
||||
mpg123_close(mpg123handle);
|
||||
mpg123_delete(mpg123handle);
|
||||
break;
|
||||
case AudioCache::FileFormat::UNKNOWN:
|
||||
default:
|
||||
break;
|
||||
decoder->close();
|
||||
}
|
||||
AudioDecoderManager::destroyDecoder(decoder);
|
||||
free(tmpBuffer);
|
||||
_readForRemove = true;
|
||||
_isRotateThreadExited = true;
|
||||
ALOGV("%s exited.\n", __FUNCTION__);
|
||||
}
|
||||
|
||||
bool AudioPlayer::setLoop(bool loop)
|
||||
{
|
||||
if (!_exitThread ) {
|
||||
if (!_isDestroyed ) {
|
||||
_loop = loop;
|
||||
return true;
|
||||
}
|
||||
@@ -334,9 +333,11 @@ bool AudioPlayer::setLoop(bool loop)
|
||||
|
||||
bool AudioPlayer::setTime(float time)
|
||||
{
|
||||
if (!_exitThread && time >= 0.0f && time < _audioCache->_duration) {
|
||||
if (!_isDestroyed && time >= 0.0f && time < _audioCache->_duration) {
|
||||
|
||||
_currTime = time;
|
||||
_timeDirty = true;
|
||||
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2014 Chukong Technologies Inc.
|
||||
Copyright (c) 2014-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -21,23 +21,23 @@
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "platform/CCPlatformConfig.h"
|
||||
|
||||
#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
|
||||
|
||||
#ifndef __AUDIO_PLAYER_H_
|
||||
#define __AUDIO_PLAYER_H_
|
||||
|
||||
#include <string>
|
||||
#include <condition_variable>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#ifdef OPENAL_PLAIN_INCLUDES
|
||||
#include <al.h>
|
||||
#else
|
||||
#include <OpenalSoft/al.h>
|
||||
#include <AL/al.h>
|
||||
#endif
|
||||
#include "platform/CCPlatformMacros.h"
|
||||
#include "audio/win32/AudioCache.h"
|
||||
|
||||
NS_CC_BEGIN
|
||||
namespace experimental{
|
||||
@@ -49,19 +49,19 @@ class CC_DLL AudioPlayer
|
||||
{
|
||||
public:
|
||||
AudioPlayer();
|
||||
AudioPlayer(const AudioPlayer&);
|
||||
~AudioPlayer();
|
||||
|
||||
void destroy();
|
||||
|
||||
//queue buffer related stuff
|
||||
bool setTime(float time);
|
||||
float getTime() { return _currTime;}
|
||||
bool setLoop(bool loop);
|
||||
void notifyExitThread();
|
||||
|
||||
protected:
|
||||
void setCache(AudioCache* cache);
|
||||
void rotateBufferThread(int offsetFrame);
|
||||
bool play2d(AudioCache* cache);
|
||||
int readPcmData(char* buffer, int bufferSize, const std::function<int/*readBytes*/(char* /*buf*/, int /*bytesToRead*/)>& fileReader);
|
||||
bool play2d();
|
||||
|
||||
AudioCache* _audioCache;
|
||||
|
||||
@@ -69,25 +69,30 @@ protected:
|
||||
bool _loop;
|
||||
std::function<void (int, const std::string &)> _finishCallbak;
|
||||
|
||||
bool _isDestroyed;
|
||||
bool _removeByAudioEngine;
|
||||
bool _ready;
|
||||
ALuint _alSource;
|
||||
|
||||
//play by circular buffer
|
||||
float _currTime;
|
||||
bool _timeDirty;
|
||||
bool _streamingSource;
|
||||
ALuint _bufferIds[QUEUEBUFFER_NUM];
|
||||
std::thread _rotateBufferThread;
|
||||
std::mutex _sleepMutex;
|
||||
ALuint _bufferIds[3];
|
||||
std::thread* _rotateBufferThread;
|
||||
std::condition_variable _sleepCondition;
|
||||
bool _exitThread;
|
||||
bool _readForRemove;
|
||||
std::mutex _sleepMutex;
|
||||
bool _timeDirty;
|
||||
bool _isRotateThreadExited;
|
||||
|
||||
std::mutex _play2dMutex;
|
||||
|
||||
unsigned int _id;
|
||||
|
||||
friend class AudioEngineImpl;
|
||||
};
|
||||
|
||||
}
|
||||
NS_CC_END
|
||||
#endif // __AUDIO_PLAYER_H_
|
||||
|
||||
#endif //CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
|
||||
|
||||
|
||||
@@ -18,12 +18,16 @@ public:
|
||||
void Close();
|
||||
|
||||
/**
|
||||
@brief Play sound file
|
||||
@param pFileName Sound's file name,include the file path.
|
||||
@param nTimes Play mode£¬default value is 1,paly once
|
||||
@brief Open audio file
|
||||
@param pFileName The file name which includes the file path.
|
||||
@param uId The audio ID
|
||||
*/
|
||||
void Open(const char* pFileName, UINT uId);
|
||||
|
||||
/**
|
||||
@brief Play audio file
|
||||
@param nTimes The repeat times, its default value is 1 which means only play once
|
||||
*/
|
||||
void Play(UINT uTimes = 1);
|
||||
|
||||
/**
|
||||
@@ -73,4 +77,3 @@ private:
|
||||
} // end of namespace CocosDenshion
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2010-2012 cocos2d-x.org
|
||||
Copyright (c) 2013-2014 Chukong Technologies Inc.
|
||||
Copyright (c) 2013-2017 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
@@ -78,12 +78,10 @@ void SimpleAudioEngine::end()
|
||||
{
|
||||
sharedMusic().Close();
|
||||
|
||||
EffectList::iterator p = sharedList().begin();
|
||||
while (p != sharedList().end())
|
||||
for (auto& iter : sharedList())
|
||||
{
|
||||
delete p->second;
|
||||
p->second = nullptr;
|
||||
p++;
|
||||
delete iter.second;
|
||||
iter.second = nullptr;
|
||||
}
|
||||
sharedList().clear();
|
||||
return;
|
||||
@@ -204,10 +202,9 @@ void SimpleAudioEngine::pauseEffect(unsigned int nSoundId)
|
||||
|
||||
void SimpleAudioEngine::pauseAllEffects()
|
||||
{
|
||||
EffectList::iterator iter;
|
||||
for (iter = sharedList().begin(); iter != sharedList().end(); iter++)
|
||||
for (auto& iter : sharedList())
|
||||
{
|
||||
iter->second->Pause();
|
||||
iter.second->Pause();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -222,19 +219,17 @@ void SimpleAudioEngine::resumeEffect(unsigned int nSoundId)
|
||||
|
||||
void SimpleAudioEngine::resumeAllEffects()
|
||||
{
|
||||
EffectList::iterator iter;
|
||||
for (iter = sharedList().begin(); iter != sharedList().end(); iter++)
|
||||
for (auto& iter : sharedList())
|
||||
{
|
||||
iter->second->Resume();
|
||||
iter.second->Resume();
|
||||
}
|
||||
}
|
||||
|
||||
void SimpleAudioEngine::stopAllEffects()
|
||||
{
|
||||
EffectList::iterator iter;
|
||||
for (iter = sharedList().begin(); iter != sharedList().end(); iter++)
|
||||
for (auto& iter : sharedList())
|
||||
{
|
||||
iter->second->Stop();
|
||||
iter.second->Stop();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,8 @@ LOCAL_SRC_FILES := HttpClient-android.cpp \
|
||||
SocketIO.cpp \
|
||||
WebSocket.cpp \
|
||||
CCDownloader.cpp \
|
||||
CCDownloader-android.cpp
|
||||
CCDownloader-android.cpp \
|
||||
Uri.cpp
|
||||
|
||||
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user