axmol/tests/cpp-tests/Classes/NewAudioEngineTest/NewAudioEngineTest.cpp

1238 lines
38 KiB
C++
Raw Normal View History

2019-11-23 20:27:39 +08:00
/****************************************************************************
Copyright (c) 2014-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
2022-04-25 12:06:43 +08:00
Copyright (c) 2021-2022 Bytedance Inc.
2019-11-23 20:27:39 +08:00
2022-10-01 16:24:52 +08:00
https://axmolengine.github.io/
2019-11-23 20:27:39 +08:00
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 "platform/CCPlatformConfig.h"
#include "NewAudioEngineTest.h"
#include "ui/CocosGUI.h"
USING_NS_AX;
using namespace ax::ui;
2019-11-23 20:27:39 +08:00
AudioEngineTests::AudioEngineTests()
{
ADD_TEST_CASE(AudioControlTest);
2020-08-01 19:25:39 +08:00
ADD_TEST_CASE(AudioWavTest);
2019-11-23 20:27:39 +08:00
ADD_TEST_CASE(AudioLoadTest);
ADD_TEST_CASE(PlaySimultaneouslyTest);
ADD_TEST_CASE(AudioProfileTest);
ADD_TEST_CASE(InvalidAudioFileTest);
ADD_TEST_CASE(LargeAudioFileTest);
ADD_TEST_CASE(AudioPerformanceTest);
ADD_TEST_CASE(AudioSmallFileTest);
ADD_TEST_CASE(AudioSmallFile2Test);
ADD_TEST_CASE(AudioSmallFile3Test);
ADD_TEST_CASE(AudioPauseResumeAfterPlay);
ADD_TEST_CASE(AudioPreloadSameFileMultipleTimes);
ADD_TEST_CASE(AudioPlayFileInWritablePath);
ADD_TEST_CASE(AudioIssue16938Test);
ADD_TEST_CASE(AudioPlayInFinishedCB);
ADD_TEST_CASE(AudioUncacheInFinishedCB);
ADD_TEST_CASE(AudioIssue18597Test);
ADD_TEST_CASE(AudioIssue11143Test);
// FIXME: Please keep AudioSwitchStateTest to the last position since this test case doesn't work well on each
// platforms.
2019-11-23 20:27:39 +08:00
ADD_TEST_CASE(AudioSwitchStateTest);
}
namespace
{
2022-10-18 19:17:36 +08:00
class TextButton : public ax::Label
{
public:
static TextButton* create(std::string_view text, const std::function<void(TextButton*)>& onTriggered)
2019-11-23 20:27:39 +08:00
{
auto ret = new TextButton();
TTFConfig ttfconfig("fonts/arial.ttf", 25);
if (ret->setTTFConfig(ttfconfig))
2019-11-23 20:27:39 +08:00
{
ret->setString(text);
ret->_onTriggered = onTriggered;
ret->autorelease();
return ret;
2019-11-23 20:27:39 +08:00
}
delete ret;
return nullptr;
}
void setEnabled(bool enabled)
{
_enabled = enabled;
if (_enabled)
2019-11-23 20:27:39 +08:00
{
this->setColor(Color3B::WHITE);
2019-11-23 20:27:39 +08:00
}
else
2019-11-23 20:27:39 +08:00
{
this->setColor(Color3B::GRAY);
2019-11-23 20:27:39 +08:00
}
}
private:
TextButton() : _onTriggered(nullptr), _enabled(true)
{
auto listener = EventListenerTouchOneByOne::create();
listener->setSwallowTouches(true);
2022-07-16 10:43:05 +08:00
listener->onTouchBegan = AX_CALLBACK_2(TextButton::onTouchBegan, this);
listener->onTouchEnded = AX_CALLBACK_2(TextButton::onTouchEnded, this);
listener->onTouchCancelled = AX_CALLBACK_2(TextButton::onTouchCancelled, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
}
bool touchHits(Touch* touch)
{
auto hitPos = this->convertToNodeSpace(touch->getLocation());
if (hitPos.x >= 0 && hitPos.y >= 0 && hitPos.x <= _contentSize.width && hitPos.y <= _contentSize.height)
2019-11-23 20:27:39 +08:00
{
return true;
2019-11-23 20:27:39 +08:00
}
return false;
}
bool onTouchBegan(Touch* touch, Event* event)
{
auto hits = touchHits(touch);
if (hits)
2019-11-23 20:27:39 +08:00
{
scaleButtonTo(0.95f);
2019-11-23 20:27:39 +08:00
}
return hits;
}
void onTouchEnded(Touch* touch, Event* event)
{
if (_enabled)
2019-11-23 20:27:39 +08:00
{
auto hits = touchHits(touch);
if (hits && _onTriggered)
{
_onTriggered(this);
2019-11-23 20:27:39 +08:00
}
}
scaleButtonTo(1);
}
void onTouchCancelled(Touch* touch, Event* event) { scaleButtonTo(1); }
void scaleButtonTo(float scale)
{
auto action = ScaleTo::create(0.05f, scale);
action->setTag(10000);
stopActionByTag(10000);
runAction(action);
}
std::function<void(TextButton*)> _onTriggered;
bool _enabled;
};
class SliderEx : public Slider
{
public:
static SliderEx* create()
{
auto ret = new SliderEx();
if (ret->init())
{
ret->loadBarTexture("cocosui/sliderTrack.png");
ret->loadSlidBallTextures("cocosui/sliderThumb.png", "cocosui/sliderThumb.png", "");
ret->loadProgressBarTexture("cocosui/sliderProgress.png");
ret->setTouchEnabled(true);
ret->autorelease();
2021-12-31 11:00:35 +08:00
return ret;
}
2022-07-16 10:43:05 +08:00
AX_SAFE_DELETE(ret);
return ret;
}
void setRatio(float ratio)
{
ratio = clampf(ratio, 0.0f, 1.0f);
_ratio = ratio;
setPercent(100 * _ratio);
}
float getRatio()
{
_ratio = 1.0f * _percent / _maxPercent;
return _ratio;
}
private:
float _ratio;
};
} // namespace
AudioEngineTestDemo::AudioEngineTestDemo() : _isDestroyed(std::make_shared<bool>(false)) {}
2019-11-23 20:27:39 +08:00
void AudioEngineTestDemo::onExit()
{
*_isDestroyed = true;
AudioEngine::uncacheAll();
TestCase::onExit();
}
std::string AudioEngineTestDemo::title() const
{
return "New Audio Engine Test";
}
2022-10-18 19:17:36 +08:00
void AudioEngineTestDemo::onBackCallback(ax::Ref* sender)
2019-11-23 20:27:39 +08:00
{
AudioEngine::end();
TestCase::onBackCallback(sender);
}
// AudioControlTest
bool AudioControlTest::init()
{
auto ret = AudioEngineTestDemo::init();
_audioID = AudioEngine::INVALID_AUDIO_ID;
_loopEnabled = false;
_volume = 1.0f;
_duration = AudioEngine::TIME_UNKNOWN;
_timeRatio = 0.0f;
2019-11-23 20:27:39 +08:00
_updateTimeSlider = true;
_isStopped = false;
2019-11-23 20:27:39 +08:00
std::string fontFilePath = "fonts/arial.ttf";
2019-11-23 20:27:39 +08:00
auto& layerSize = this->getContentSize();
2019-11-23 20:27:39 +08:00
_playOverLabel = Label::createWithSystemFont("Play Over", "", 30);
_playOverLabel->setPosition(Vec2(layerSize / 2) + Vec2(0, 30));
2019-11-23 20:27:39 +08:00
_playOverLabel->setVisible(false);
addChild(_playOverLabel, 99999);
2021-10-06 11:24:39 +08:00
auto playItem = TextButton::create("play", [&](TextButton* button) {
if (_audioID == AudioEngine::INVALID_AUDIO_ID)
{
_audioID = AudioEngine::play2d("background.mp3", _loopEnabled, _volume);
if (_audioID != AudioEngine::INVALID_AUDIO_ID)
{
2019-11-23 20:27:39 +08:00
_isStopped = false;
2019-11-23 20:27:39 +08:00
button->setEnabled(false);
AudioEngine::setFinishCallback(_audioID, [&](int id, std::string_view filePath) {
2019-11-23 20:27:39 +08:00
log("_audioID(%d), _isStopped:(%d), played over!!!", _audioID, _isStopped);
2019-11-23 20:27:39 +08:00
_playOverLabel->setVisible(true);
scheduleOnce([&](float dt) { _playOverLabel->setVisible(false); }, 2.0f, "hide_play_over_label");
assert(!_isStopped); // Stop audio should not trigger finished callback
2019-11-23 20:27:39 +08:00
_audioID = AudioEngine::INVALID_AUDIO_ID;
((TextButton*)_playItem)->setEnabled(true);
2019-11-23 20:27:39 +08:00
_timeRatio = 0.0f;
((SliderEx*)_timeSlider)->setRatio(_timeRatio);
});
}
}
});
_playItem = playItem;
playItem->setPosition(layerSize.width * 0.3f, layerSize.height * 0.8f);
2019-11-23 20:27:39 +08:00
addChild(playItem);
auto stopItem = TextButton::create("stop", [&](TextButton* button) {
if (_audioID != AudioEngine::INVALID_AUDIO_ID)
{
2019-11-23 20:27:39 +08:00
_isStopped = true;
AudioEngine::stop(_audioID);
2019-11-23 20:27:39 +08:00
_audioID = AudioEngine::INVALID_AUDIO_ID;
((TextButton*)_playItem)->setEnabled(true);
}
});
stopItem->setPosition(layerSize.width * 0.7f, layerSize.height * 0.8f);
2019-11-23 20:27:39 +08:00
addChild(stopItem);
auto pauseItem = TextButton::create("pause", [&](TextButton* button) {
if (_audioID != AudioEngine::INVALID_AUDIO_ID)
{
2019-11-23 20:27:39 +08:00
AudioEngine::pause(_audioID);
}
});
pauseItem->setPosition(layerSize.width * 0.3f, layerSize.height * 0.7f);
2019-11-23 20:27:39 +08:00
addChild(pauseItem);
auto resumeItem = TextButton::create("resume", [&](TextButton* button) {
if (_audioID != AudioEngine::INVALID_AUDIO_ID)
{
2019-11-23 20:27:39 +08:00
AudioEngine::resume(_audioID);
}
});
resumeItem->setPosition(layerSize.width * 0.7f, layerSize.height * 0.7f);
2019-11-23 20:27:39 +08:00
addChild(resumeItem);
auto loopItem = TextButton::create("enable-loop", [&](TextButton* button) {
2019-11-23 20:27:39 +08:00
_loopEnabled = !_loopEnabled;
if (_audioID != AudioEngine::INVALID_AUDIO_ID)
{
2019-11-23 20:27:39 +08:00
AudioEngine::setLoop(_audioID, _loopEnabled);
}
if (_loopEnabled)
{
2019-11-23 20:27:39 +08:00
button->setString("disable-loop");
}
else
{
2019-11-23 20:27:39 +08:00
button->setString("enable-loop");
}
});
loopItem->setPosition(layerSize.width * 0.5f, layerSize.height * 0.5f);
addChild(loopItem);
2019-11-23 20:27:39 +08:00
auto volumeSlider = SliderEx::create();
volumeSlider->setPercent(100);
volumeSlider->addEventListener([&](Ref* sender, Slider::EventType event) {
SliderEx* slider = dynamic_cast<SliderEx*>(sender);
_volume = slider->getRatio();
if (_audioID != AudioEngine::INVALID_AUDIO_ID)
{
2019-11-23 20:27:39 +08:00
AudioEngine::setVolume(_audioID, _volume);
}
});
volumeSlider->setPosition(Vec2(layerSize.width * 0.5f, layerSize.height * 0.35f));
2019-11-23 20:27:39 +08:00
addChild(volumeSlider);
2019-11-23 20:27:39 +08:00
auto timeSlider = SliderEx::create();
timeSlider->addEventListener([&](Ref* sender, Slider::EventType event) {
SliderEx* slider = dynamic_cast<SliderEx*>(sender);
switch (event)
{
case Slider::EventType::ON_SLIDEBALL_DOWN:
_updateTimeSlider = false;
break;
case Slider::EventType::ON_SLIDEBALL_UP:
if (_audioID != AudioEngine::INVALID_AUDIO_ID && _duration != AudioEngine::TIME_UNKNOWN)
{
float ratio = (float)slider->getPercent() / 100;
ratio = clampf(ratio, 0.0f, 1.0f);
AudioEngine::setCurrentTime(_audioID, _duration * ratio);
}
case Slider::EventType::ON_SLIDEBALL_CANCEL:
_updateTimeSlider = true;
case Slider::EventType::ON_PERCENTAGE_CHANGED:
default:
// ignore
break;
2019-11-23 20:27:39 +08:00
}
});
timeSlider->setPosition(Vec2(layerSize.width * 0.5f, layerSize.height * 0.25f));
2019-11-23 20:27:39 +08:00
addChild(timeSlider);
_timeSlider = timeSlider;
2019-11-23 20:27:39 +08:00
auto& volumeSliderPos = volumeSlider->getPosition();
auto& sliderSize = volumeSlider->getContentSize();
auto volumeLabel = Label::createWithTTF("volume: ", fontFilePath, 20);
2019-11-23 20:27:39 +08:00
volumeLabel->setAnchorPoint(Vec2::ANCHOR_MIDDLE_RIGHT);
volumeLabel->setPosition(volumeSliderPos.x - sliderSize.width / 2, volumeSliderPos.y);
addChild(volumeLabel);
2019-11-23 20:27:39 +08:00
auto& timeSliderPos = timeSlider->getPosition();
auto timeLabel = Label::createWithTTF("time: ", fontFilePath, 20);
2019-11-23 20:27:39 +08:00
timeLabel->setAnchorPoint(Vec2::ANCHOR_MIDDLE_RIGHT);
timeLabel->setPosition(timeSliderPos.x - sliderSize.width / 2, timeSliderPos.y);
addChild(timeLabel);
2022-07-16 10:43:05 +08:00
this->schedule(AX_CALLBACK_1(AudioControlTest::update, this), 0.1f, "update_key");
2019-11-23 20:27:39 +08:00
return ret;
}
void AudioControlTest::update(float dt)
{
if (_audioID != AudioEngine::INVALID_AUDIO_ID)
{
if (_duration == AudioEngine::TIME_UNKNOWN)
{
2019-11-23 20:27:39 +08:00
_duration = AudioEngine::getDuration(_audioID);
}
if (_duration != AudioEngine::TIME_UNKNOWN)
{
auto time = AudioEngine::getCurrentTime(_audioID);
2019-11-23 20:27:39 +08:00
_timeRatio = time / _duration;
if (_updateTimeSlider)
{
2019-11-23 20:27:39 +08:00
((SliderEx*)_timeSlider)->setRatio(_timeRatio);
}
}
}
}
AudioControlTest::~AudioControlTest() {}
2019-11-23 20:27:39 +08:00
std::string AudioControlTest::title() const
{
return "Audio control test";
}
bool AudioLoadTest::init()
{
if (AudioEngineTestDemo::init())
{
auto& layerSize = this->getContentSize();
auto stateLabel = Label::createWithTTF("status:", "fonts/arial.ttf", 30);
stateLabel->setPosition(layerSize.width / 2, layerSize.height * 0.7f);
addChild(stateLabel);
auto preloadItem = TextButton::create("preload", [&, stateLabel](TextButton* button) {
2019-11-23 20:27:39 +08:00
stateLabel->setString("status:loading...");
auto isDestroyed = _isDestroyed;
AudioEngine::preload("audio/SoundEffectsFX009/FX082.mp3", [isDestroyed, stateLabel](bool isSuccess) {
2019-11-23 20:27:39 +08:00
if (*isDestroyed)
{
2022-07-16 10:43:05 +08:00
AXLOG("AudioLoadTest scene was destroyed, no need to set the label text.");
2019-11-23 20:27:39 +08:00
return;
}
2019-11-23 20:27:39 +08:00
if (isSuccess)
{
stateLabel->setString("status:load success");
}
else
{
stateLabel->setString("status:load fail");
}
});
});
preloadItem->setPosition(layerSize.width * 0.35f, layerSize.height * 0.5f);
addChild(preloadItem);
auto uncacheItem = TextButton::create("uncache", [&, stateLabel](TextButton* button) {
2019-11-23 20:27:39 +08:00
stateLabel->setString("status:uncache");
AudioEngine::uncache("audio/SoundEffectsFX009/FX082.mp3");
});
uncacheItem->setPosition(layerSize.width * 0.65f, layerSize.height * 0.5f);
addChild(uncacheItem);
2019-11-23 20:27:39 +08:00
return true;
}
return false;
}
std::string AudioLoadTest::title() const
{
return "Audio preload/uncache test";
}
2020-08-01 19:25:39 +08:00
// AudioWavTest
AudioWavTest::~AudioWavTest() {}
2020-08-01 19:25:39 +08:00
std::string AudioWavTest::title() const
{
return "Audio wav test";
}
bool AudioWavTest::init()
{
if (AudioEngineTestDemo::init())
{
// list wav files, the wav samples download from wav wiki
_wavFiles = FileUtils::getInstance()->listFiles("wav-samples");
auto& layerSize = this->getContentSize();
_stateLabel = Label::createWithTTF("wav file:", "fonts/arial.ttf", 30);
_stateLabel->setPosition(layerSize.width / 2, layerSize.height * 0.7f);
addChild(_stateLabel);
auto playPrev = TextButton::create("Play Prev", [=](TextButton* button) {
if (_curIndex > 0)
{
2020-08-01 19:25:39 +08:00
AudioEngine::stop(_audioID);
_audioID = AudioEngine::play2d(_wavFiles[--_curIndex]);
_stateLabel->setString(StringUtils::format("[index: %d] %s", _curIndex,
FileUtils::getFileShortName(_wavFiles[_curIndex]).c_str()));
2020-08-01 19:25:39 +08:00
}
});
2020-08-01 19:25:39 +08:00
playPrev->setPosition(layerSize.width * 0.35f, layerSize.height * 0.5f);
addChild(playPrev);
auto playNext = TextButton::create("Play Next", [=](TextButton* button) {
if (_curIndex != -1 && _curIndex < (_wavFiles.size() - 1))
{
2020-08-01 19:25:39 +08:00
AudioEngine::stop(_audioID);
_audioID = AudioEngine::play2d(_wavFiles[++_curIndex]);
_stateLabel->setString(StringUtils::format("[index: %d] %s", _curIndex,
FileUtils::getFileShortName(_wavFiles[_curIndex]).c_str()));
2020-08-01 19:25:39 +08:00
}
});
2020-08-01 19:25:39 +08:00
playNext->setPosition(layerSize.width * 0.65f, layerSize.height * 0.5f);
addChild(playNext);
return true;
}
return false;
}
void AudioWavTest::onEnter()
{
AudioEngineTestDemo::onEnter();
if (!_wavFiles.empty())
{
2020-08-01 19:25:39 +08:00
_curIndex = 0;
_audioID = AudioEngine::play2d(_wavFiles[_curIndex]);
_stateLabel->setString(StringUtils::format("[index: %d] %s", _curIndex,
FileUtils::getFileShortName(_wavFiles[_curIndex]).c_str()));
2020-08-01 19:25:39 +08:00
}
}
2019-11-23 20:27:39 +08:00
// PlaySimultaneouslyTest
bool PlaySimultaneouslyTest::init()
{
auto ret = AudioEngineTestDemo::init();
2019-11-23 20:27:39 +08:00
char text[36];
int tmp = 81;
for (int index = 0; index < TEST_COUNT; ++index)
{
sprintf(text, "audio/SoundEffectsFX009/FX0%d.mp3", tmp + index);
2019-11-23 20:27:39 +08:00
_files[index] = text;
}
_playingcount = 0;
auto playItem = TextButton::create("play-simultaneously", [&](TextButton* button) {
2019-11-23 20:27:39 +08:00
int audioId;
_playingcount = 0;
button->setEnabled(false);
auto startTime = utils::gettime();
for (int index = 0; index < TEST_COUNT; ++index)
{
2019-11-23 20:27:39 +08:00
audioId = AudioEngine::play2d(_files[index]);
if (audioId != AudioEngine::INVALID_AUDIO_ID)
{
2019-11-23 20:27:39 +08:00
_playingcount += 1;
AudioEngine::setFinishCallback(audioId, [&](int id, std::string_view filePath) {
2019-11-23 20:27:39 +08:00
_playingcount -= 1;
if (_playingcount <= 0)
{
2019-11-23 20:27:39 +08:00
((TextButton*)_playItem)->setEnabled(true);
}
});
}
else
{
log("%s,%d,Fail to play file:%s", __FILE__, __LINE__, _files[index].c_str());
2019-11-23 20:27:39 +08:00
}
}
log("diff time:%lf", utils::gettime() - startTime);
2019-11-23 20:27:39 +08:00
});
playItem->setPositionNormalized(Vec2(0.5f, 0.5f));
2019-11-23 20:27:39 +08:00
this->addChild(playItem);
_playItem = playItem;
2019-11-23 20:27:39 +08:00
return ret;
}
PlaySimultaneouslyTest::~PlaySimultaneouslyTest() {}
2019-11-23 20:27:39 +08:00
std::string PlaySimultaneouslyTest::title() const
{
return "Simultaneously play multiple audio";
}
// AudioProfileTest
bool AudioProfileTest::init()
{
auto ret = AudioEngineTestDemo::init();
2019-11-23 20:27:39 +08:00
char text[30];
_files[0] = "background.mp3";
2022-07-16 10:43:05 +08:00
#if AX_TARGET_PLATFORM == AX_PLATFORM_IOS || AX_TARGET_PLATFORM == AX_PLATFORM_MAC
2019-11-23 20:27:39 +08:00
_files[1] = "background.caf";
#else
_files[1] = "background.ogg";
#endif
2019-11-23 20:27:39 +08:00
std::string fontFilePath = "fonts/arial.ttf";
_minDelay = 1.0f;
_time = 0.0f;
2019-11-23 20:27:39 +08:00
_audioProfile.name = "AudioProfileTest";
2019-11-23 20:27:39 +08:00
_audioProfile.maxInstances = 3;
_audioProfile.minDelay = 1.0;
Vec2 pos(0.5f, 0.7f);
for (int index = 0; index < FILE_COUNT; ++index)
{
sprintf(text, "play %s", _files[index].c_str());
auto playItem = TextButton::create(text, [&](TextButton* button) {
2019-11-23 20:27:39 +08:00
int index = button->getTag();
auto id = AudioEngine::play2d(_files[index], false, 1.0f, &_audioProfile);
if (id != AudioEngine::INVALID_AUDIO_ID)
{
2019-11-23 20:27:39 +08:00
_time = _minDelay;
_audioCount += 1;
char show[30];
sprintf(show, "audio count:%d", _audioCount);
2019-11-23 20:27:39 +08:00
_showLabel->setString(show);
AudioEngine::setFinishCallback(id, [&](int id, std::string_view filePath) {
2019-11-23 20:27:39 +08:00
_audioCount -= 1;
char show[30];
sprintf(show, "audio count:%d", _audioCount);
2019-11-23 20:27:39 +08:00
_showLabel->setString(show);
});
}
});
playItem->setTag(index);
playItem->setPositionNormalized(pos);
this->addChild(playItem);
pos.y -= 0.15f;
}
2019-11-23 20:27:39 +08:00
Vec2 origin = Director::getInstance()->getVisibleOrigin();
Size size = Director::getInstance()->getVisibleSize();
auto profileInfoLabel =
Label::createWithTTF("AudioProfile Info:\n max instance:3 \n minimum delay:1.0", fontFilePath, 12);
2019-11-23 20:27:39 +08:00
profileInfoLabel->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);
profileInfoLabel->setPosition(Vec2(origin.x, origin.y + size.height * 0.65f));
addChild(profileInfoLabel);
2019-11-23 20:27:39 +08:00
_audioCount = 0;
_showLabel = Label::createWithTTF("audio count:0", fontFilePath, 12);
2019-11-23 20:27:39 +08:00
_showLabel->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);
_showLabel->setPosition(Vec2(origin.x, origin.y + size.height * 0.5f));
addChild(_showLabel);
2019-11-23 20:27:39 +08:00
auto timeSlider = SliderEx::create();
timeSlider->setEnabled(false);
timeSlider->setPositionNormalized(pos);
addChild(timeSlider);
_timeSlider = timeSlider;
2022-07-16 10:43:05 +08:00
this->schedule(AX_CALLBACK_1(AudioProfileTest::update, this), 0.05f, "update_key");
2019-11-23 20:27:39 +08:00
return ret;
}
void AudioProfileTest::update(float dt)
{
if (_time > 0.0f)
2019-11-23 20:27:39 +08:00
{
_time -= dt;
((SliderEx*)_timeSlider)->setRatio(_time / _minDelay);
}
}
AudioProfileTest::~AudioProfileTest() {}
2019-11-23 20:27:39 +08:00
std::string AudioProfileTest::title() const
{
return "AudioProfileTest";
}
std::string AudioProfileTest::subtitle() const
{
return "See the console.";
}
// InvalidAudioFileTest
bool InvalidAudioFileTest::init()
{
auto ret = AudioEngineTestDemo::init();
auto playItem = TextButton::create("play unsupported media type", [&](TextButton* button) {
2022-07-16 10:43:05 +08:00
#if AX_TARGET_PLATFORM == AX_PLATFORM_IOS || AX_TARGET_PLATFORM == AX_PLATFORM_MAC
2019-11-23 20:27:39 +08:00
AudioEngine::play2d("background.ogg");
2022-07-16 10:43:05 +08:00
#elif AX_TARGET_PLATFORM == AX_PLATFORM_ANDROID || AX_TARGET_PLATFORM == AX_PLATFORM_WIN32
AudioEngine::play2d("background.caf");
2019-11-23 20:27:39 +08:00
#endif
});
playItem->setPositionNormalized(Vec2(0.5f, 0.6f));
this->addChild(playItem);
auto playItem2 = TextButton::create("play not-existent file",
[&](TextButton* button) { AudioEngine::play2d("not-existent file.mp3"); });
2019-11-23 20:27:39 +08:00
playItem2->setPositionNormalized(Vec2(0.5f, 0.4f));
this->addChild(playItem2);
2019-11-23 20:27:39 +08:00
return ret;
}
InvalidAudioFileTest::~InvalidAudioFileTest() {}
2019-11-23 20:27:39 +08:00
std::string InvalidAudioFileTest::title() const
{
return "Test invalid audio file";
}
std::string InvalidAudioFileTest::subtitle() const
{
return "Not crash,please see the console.";
}
// LargeAudioFileTest
bool LargeAudioFileTest::init()
{
auto ret = AudioEngineTestDemo::init();
auto playItem = TextButton::create("play large audio file",
[&](TextButton* button) { AudioEngine::play2d("audio/LuckyDay.mp3"); });
2019-11-23 20:27:39 +08:00
playItem->setPositionNormalized(Vec2::ANCHOR_MIDDLE);
this->addChild(playItem);
2019-11-23 20:27:39 +08:00
return ret;
}
LargeAudioFileTest::~LargeAudioFileTest() {}
2019-11-23 20:27:39 +08:00
std::string LargeAudioFileTest::title() const
{
return "Test large audio file";
}
bool AudioIssue18597Test::init()
{
if (AudioEngineTestDemo::init())
{
auto& layerSize = this->getContentSize();
// test case for https://github.com/cocos2d/cocos2d-x/issues/18597
this->schedule(
[=](float dt) {
2022-07-16 10:43:05 +08:00
AXLOG("issues 18597 audio crash test");
for (int i = 0; i < 2; ++i)
{
auto id = AudioEngine::play2d("audio/MUS_BGM_Battle_Round1_v1.caf", true, 1.0f);
this->runAction(Sequence::create(DelayTime::create(8.0f),
CallFunc::create([=]() { AudioEngine::stop(id); }), nullptr));
}
},
2.0, 10000, 0.0, "audio test");
2019-11-23 20:27:39 +08:00
// add label to show the side effect of "UnqueueBuffers Before alSourceStop"
_time = 0.0;
2019-11-23 20:27:39 +08:00
auto labelTime = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "time: ");
labelTime->setPosition(layerSize.width * 0.5f, layerSize.height * 0.5f);
labelTime->setTag(999);
this->addChild(labelTime);
// update label quickly
this->schedule(
[=](float dt) {
_time += dt;
char timeString[20] = {0};
sprintf(timeString, "Time %2.2f", _time);
dynamic_cast<Label*>(this->getChildByTag(999))->setString(timeString);
},
0.05, 1000000, 0, "update label quickly");
2019-11-23 20:27:39 +08:00
return true;
}
return false;
}
std::string AudioIssue18597Test::title() const
{
return "Test for issue 18597";
}
std::string AudioIssue18597Test::subtitle() const
{
return "no crash for more than 10 minutes";
}
bool AudioIssue11143Test::init()
{
if (AudioEngineTestDemo::init())
{
auto& layerSize = this->getContentSize();
auto playItem = TextButton::create("play", [](TextButton* button) {
2019-11-23 20:27:39 +08:00
AudioEngine::play2d("audio/SoundEffectsFX009/FX082.mp3", true);
AudioEngine::stopAll();
auto audioId = AudioEngine::play2d("audio/SoundEffectsFX009/FX082.mp3", true);
2019-11-23 20:27:39 +08:00
char key[100] = {0};
sprintf(key, "play another sound %d", audioId);
button->scheduleOnce(
[audioId](float dt) {
AudioEngine::stop(audioId);
AudioEngine::play2d("audio/SoundEffectsFX009/FX083.mp3");
},
0.3f, key);
2019-11-23 20:27:39 +08:00
});
playItem->setPosition(layerSize.width * 0.5f, layerSize.height * 0.5f);
addChild(playItem);
return true;
}
return false;
}
std::string AudioIssue11143Test::title() const
{
return "Test for issue 11143";
}
std::string AudioIssue11143Test::subtitle() const
{
return "2 seconds after first sound play,you should hear another sound.";
}
// Enable profiles for this file
2022-07-16 10:43:05 +08:00
#undef AX_PROFILER_DISPLAY_TIMERS
#define AX_PROFILER_DISPLAY_TIMERS() Profiler::getInstance()->displayTimers()
#undef AX_PROFILER_PURGE_ALL
#define AX_PROFILER_PURGE_ALL() Profiler::getInstance()->releaseAllTimers()
#undef AX_PROFILER_START
#define AX_PROFILER_START(__name__) ProfilingBeginTimingBlock(__name__)
#undef AX_PROFILER_STOP
#define AX_PROFILER_STOP(__name__) ProfilingEndTimingBlock(__name__)
#undef AX_PROFILER_RESET
#define AX_PROFILER_RESET(__name__) ProfilingResetTimingBlock(__name__)
#undef AX_PROFILER_START_CATEGORY
#define AX_PROFILER_START_CATEGORY(__cat__, __name__) \
do \
{ \
if (__cat__) \
ProfilingBeginTimingBlock(__name__); \
} while (0)
2022-07-16 10:43:05 +08:00
#undef AX_PROFILER_STOP_CATEGORY
#define AX_PROFILER_STOP_CATEGORY(__cat__, __name__) \
do \
{ \
if (__cat__) \
ProfilingEndTimingBlock(__name__); \
} while (0)
2022-07-16 10:43:05 +08:00
#undef AX_PROFILER_RESET_CATEGORY
#define AX_PROFILER_RESET_CATEGORY(__cat__, __name__) \
do \
{ \
if (__cat__) \
ProfilingResetTimingBlock(__name__); \
} while (0)
2019-11-23 20:27:39 +08:00
2022-07-16 10:43:05 +08:00
#undef AX_PROFILER_START_INSTANCE
#define AX_PROFILER_START_INSTANCE(__id__, __name__) \
do \
{ \
ProfilingBeginTimingBlock(String::createWithFormat("%08X - %s", __id__, __name__)->getCString()); \
} while (0)
2022-07-16 10:43:05 +08:00
#undef AX_PROFILER_STOP_INSTANCE
#define AX_PROFILER_STOP_INSTANCE(__id__, __name__) \
do \
{ \
ProfilingEndTimingBlock(String::createWithFormat("%08X - %s", __id__, __name__)->getCString()); \
} while (0)
2022-07-16 10:43:05 +08:00
#undef AX_PROFILER_RESET_INSTANCE
#define AX_PROFILER_RESET_INSTANCE(__id__, __name__) \
do \
{ \
ProfilingResetTimingBlock(String::createWithFormat("%08X - %s", __id__, __name__)->getCString()); \
} while (0)
2019-11-23 20:27:39 +08:00
bool AudioPerformanceTest::init()
{
if (AudioEngineTestDemo::init())
{
std::vector<std::string> audioFiles = {
"audio/SoundEffectsFX009/FX081.mp3", "audio/SoundEffectsFX009/FX082.mp3",
"audio/SoundEffectsFX009/FX083.mp3", "audio/SoundEffectsFX009/FX084.mp3",
"audio/SoundEffectsFX009/FX085.mp3", "audio/SoundEffectsFX009/FX086.mp3",
"audio/SoundEffectsFX009/FX087.mp3", "audio/SoundEffectsFX009/FX088.mp3",
"audio/SoundEffectsFX009/FX089.mp3", "audio/SoundEffectsFX009/FX090.mp3"};
2019-11-23 20:27:39 +08:00
for (const auto& audioFile : audioFiles)
{
AudioEngine::preload(audioFile);
}
2019-11-23 20:27:39 +08:00
auto& layerSize = this->getContentSize();
auto playItem = TextButton::create("Start Test", [this, audioFiles](TextButton* button) {
2019-11-23 20:27:39 +08:00
button->setEnabled(false);
static_cast<TextButton*>(getChildByName("DisplayButton"))->setEnabled(true);
2019-11-23 20:27:39 +08:00
unschedule("test");
schedule(
[audioFiles](float dt) {
2022-10-18 19:17:36 +08:00
int index = ax::random(0, (int)(audioFiles.size() - 1));
2022-07-16 10:43:05 +08:00
AX_PROFILER_START("play2d");
AudioEngine::play2d(audioFiles[index]);
2022-07-16 10:43:05 +08:00
AX_PROFILER_STOP("play2d");
},
0.25f, "test");
2019-11-23 20:27:39 +08:00
});
playItem->setPosition(layerSize.width * 0.5f, layerSize.height * 2 / 3);
playItem->setName("PlayButton");
addChild(playItem);
auto displayItem = TextButton::create("Display Result", [this, playItem](TextButton* button) {
2019-11-23 20:27:39 +08:00
unschedule("test");
AudioEngine::stopAll();
2022-07-16 10:43:05 +08:00
AX_PROFILER_DISPLAY_TIMERS();
2019-11-23 20:27:39 +08:00
playItem->setEnabled(true);
button->setEnabled(false);
});
displayItem->setEnabled(false);
displayItem->setPosition(layerSize.width * 0.5f, layerSize.height / 3);
displayItem->setName("DisplayButton");
addChild(displayItem);
2019-11-23 20:27:39 +08:00
return true;
}
2019-11-23 20:27:39 +08:00
return false;
}
std::string AudioPerformanceTest::title() const
{
return "Test Performance of AudioEngine::play2d, audio is played 1 time per second";
}
std::string AudioPerformanceTest::subtitle() const
{
return "Please see console for the result";
}
/////////////////////////////////////////////////////////////////////////
2021-10-06 11:24:39 +08:00
void AudioSwitchStateTest::onEnter()
2019-11-23 20:27:39 +08:00
{
2021-10-06 11:24:39 +08:00
AudioEngineTestDemo::onEnter();
//
// !!!Notes:
// a. No special reason, but we must play the tests audio at onEnter for this test suite only.
// b. The latst audio test scene will stop all audio players,
// so if play any sound at init funciton, you can't herer
// c. Please refer to AudioEngineTestDemo::onExit
//
2021-10-06 11:24:39 +08:00
AudioEngine::preload("audio/SoundEffectsFX009/FX081.mp3");
AudioEngine::play2d("audio/SoundEffectsFX009/FX082.mp3");
AudioEngine::play2d("audio/LuckyDay.mp3");
2019-11-23 20:27:39 +08:00
}
std::string AudioSwitchStateTest::title() const
{
return "play, preload, stop switch test";
}
std::string AudioSwitchStateTest::subtitle() const
{
return "Should not crash. No sound is ok";
}
/////////////////////////////////////////////////////////////////////////
void AudioSmallFileTest::onEnter()
2019-11-23 20:27:39 +08:00
{
2021-10-06 11:24:39 +08:00
AudioEngineTestDemo::onEnter();
//
// !!!Notes:
// a. No special reason, but we must play the tests audio at onEnter for this test suite only.
// b. The latst audio test scene will stop all audio players,
// so if play any sound at init funciton, you can't hear it
// c. Please refer to AudioEngineTestDemo::onExit
//
2021-10-06 11:24:39 +08:00
AudioEngine::play2d("audio/SmallFile.mp3");
2019-11-23 20:27:39 +08:00
}
std::string AudioSmallFileTest::title() const
{
return "Playing small mp3 file";
}
std::string AudioSmallFileTest::subtitle() const
{
return "Should not crash";
}
/////////////////////////////////////////////////////////////////////////
void AudioSmallFile2Test::onEnter()
{
AudioEngineTestDemo::onEnter();
2021-10-06 11:24:39 +08:00
//
// !!!Notes:
// a. No special reason, but we must play the tests audio at onEnter for this test suite only.
// b. The latst audio test scene will stop all audio players,
// so if play any sound at init funciton, you can't hear it
// c. Please refer to AudioEngineTestDemo::onExit
//
2021-10-06 11:24:39 +08:00
AudioEngine::play2d("audio/SmallFile2.mp3");
2019-11-23 20:27:39 +08:00
}
std::string AudioSmallFile2Test::title() const
{
return "Play small mp3 file 2";
}
std::string AudioSmallFile2Test::subtitle() const
{
return "Should not crash and should not have rasp!";
}
/////////////////////////////////////////////////////////////////////////
void AudioSmallFile3Test::onEnter()
{
AudioEngineTestDemo::onEnter();
2021-10-06 11:24:39 +08:00
//
// !!!Notes:
// a. No special reason, but we must play the tests audio at onEnter for this test suite only.
// b. The latst audio test scene will stop all audio players,
// so if play any sound at init funciton, you can't hear it
// c. Please refer to AudioEngineTestDemo::onExit
//
2021-10-06 11:24:39 +08:00
AudioEngine::play2d("audio/SmallFile3.mp3");
2019-11-23 20:27:39 +08:00
}
std::string AudioSmallFile3Test::title() const
{
return "Play small mp3 file 3";
}
std::string AudioSmallFile3Test::subtitle() const
{
return "Should not crash!";
}
/////////////////////////////////////////////////////////////////////////
void AudioPauseResumeAfterPlay::onEnter()
{
AudioEngineTestDemo::onEnter();
int audioId = AudioEngine::play2d("audio/SoundEffectsFX009/FX082.mp3");
AudioEngine::pause(audioId);
AudioEngine::resume(audioId);
2019-11-23 20:27:39 +08:00
for (int i = 0; i < 10; ++i)
{
AudioEngine::pause(audioId);
AudioEngine::resume(audioId);
}
}
std::string AudioPauseResumeAfterPlay::title() const
{
return "pause & resume right after play2d";
}
std::string AudioPauseResumeAfterPlay::subtitle() const
{
return "Should not crash";
}
/////////////////////////////////////////////////////////////////////////
void AudioIssue16938Test::onEnter()
{
AudioEngineTestDemo::onEnter();
AudioEngine::play2d("audio/EntireFramesTest.mp3");
}
std::string AudioIssue16938Test::title() const
{
return "Issue 16938 Test";
}
std::string AudioIssue16938Test::subtitle() const
{
return "Should heard the entire audio frames";
}
/////////////////////////////////////////////////////////////////////////
void AudioPreloadSameFileMultipleTimes::onEnter()
{
AudioEngineTestDemo::onEnter();
for (int i = 0; i < 10; ++i)
{
AudioEngine::preload("audio/SoundEffectsFX009/FX082.mp3", [i](bool isSucceed) {
2019-11-23 20:27:39 +08:00
log("111: %d preload %s", i, isSucceed ? "succeed" : "failed");
AudioEngine::preload("audio/SoundEffectsFX009/FX082.mp3", [i](bool isSucceed) {
2019-11-23 20:27:39 +08:00
log("222: %d preload %s", i, isSucceed ? "succeed" : "failed");
AudioEngine::preload("audio/SoundEffectsFX009/FX082.mp3", [i](bool isSucceed) {
2019-11-23 20:27:39 +08:00
log("333: %d preload %s", i, isSucceed ? "succeed" : "failed");
});
});
});
}
}
std::string AudioPreloadSameFileMultipleTimes::title() const
{
return "Preload same file multiple times";
}
std::string AudioPreloadSameFileMultipleTimes::subtitle() const
{
return "Should not crash";
}
void AudioPlayFileInWritablePath::onEnter()
{
AudioEngineTestDemo::onEnter();
auto fileUtils = FileUtils::getInstance();
2019-11-23 20:27:39 +08:00
std::string writablePath = fileUtils->getWritablePath();
std::string musicFile = "background.mp3";
2019-11-23 20:27:39 +08:00
std::string saveFilePath = writablePath + "background_in_writable_dir.mp3";
2019-11-23 20:27:39 +08:00
_oldSearchPaths = fileUtils->getOriginalSearchPaths();
fileUtils->addSearchPath(writablePath, true);
if (!fileUtils->isFileExist(saveFilePath))
{
Data data = fileUtils->getDataFromFile(musicFile);
FILE* fp = fopen(saveFilePath.c_str(), "wb");
2019-11-23 20:27:39 +08:00
if (fp != nullptr)
{
fwrite(data.getBytes(), data.getSize(), 1, fp);
fclose(fp);
}
}
2019-11-23 20:27:39 +08:00
AudioEngine::play2d(saveFilePath);
}
void AudioPlayFileInWritablePath::onExit()
{
AudioEngineTestDemo::onExit();
2019-11-23 20:27:39 +08:00
FileUtils::getInstance()->setSearchPaths(_oldSearchPaths);
}
std::string AudioPlayFileInWritablePath::title() const
{
return "Play audio in writable path";
}
std::string AudioPlayFileInWritablePath::subtitle() const
{
return "Could play audio";
}
//
void AudioPlayInFinishedCB::onEnter()
{
AudioEngineTestDemo::onEnter();
auto item = MenuItemFont::create("Play 3 files one by one", [this](Ref* sender) {
2019-11-23 20:27:39 +08:00
playMusic("background.mp3");
playMusic("background.mp3");
playMusic("background.mp3");
});
item->setPosition(VisibleRect::center());
auto menu = Menu::create(item, nullptr);
menu->setPosition(Vec2::ANCHOR_BOTTOM_LEFT);
addChild(menu);
}
void AudioPlayInFinishedCB::onExit()
{
AudioEngineTestDemo::onExit();
}
std::string AudioPlayInFinishedCB::title() const
{
return "Click menu item to play 3 audio files";
}
std::string AudioPlayInFinishedCB::subtitle() const
{
return "After played over, click again, should also hear 3 audios";
}
void AudioPlayInFinishedCB::doPlay(std::string_view filename)
2019-11-23 20:27:39 +08:00
{
int playID = AudioEngine::play2d(filename, false, 1);
AudioEngine::setFinishCallback(playID, [this](int finishID, std::string_view file) {
2019-11-23 20:27:39 +08:00
_playList.pop_front();
log("finish music %s", file.data());
if (!_playList.empty())
{
std::string_view name = _playList.front();
2019-11-23 20:27:39 +08:00
doPlay(name);
}
});
}
void AudioPlayInFinishedCB::playMusic(std::string_view filename)
2019-11-23 20:27:39 +08:00
{
_playList.emplace_back(std::string{filename});
if (_playList.size() == 1)
{
2019-11-23 20:27:39 +08:00
doPlay(filename);
}
}
//
void AudioUncacheInFinishedCB::onEnter()
{
AudioEngineTestDemo::onEnter();
int id = AudioEngine::play2d("background.mp3");
AudioEngine::setFinishCallback(id, [](int i, std::string_view str) { AudioEngine::uncacheAll(); });
2019-11-23 20:27:39 +08:00
}
void AudioUncacheInFinishedCB::onExit()
{
AudioEngineTestDemo::onExit();
}
std::string AudioUncacheInFinishedCB::title() const
{
return "UncacheAll in finshed callback";
}
std::string AudioUncacheInFinishedCB::subtitle() const
{
return "Should not crash";
}