gpt4 book ai didi

c++ - 调用 QSound 调用,它们之间有延迟 Qt C++

转载 作者:行者123 更新时间:2023-11-28 08:35:00 27 4
gpt4 key购买 nike

嘿,我正在构建一个小游戏,我正在通过制作一个数字 vector 来创建关卡,该数字 vector 通过枚举与 1-4 种颜色相关联。问题是循环(在 Simon::loadChallenge 中)我将颜色代码添加到 vector 中,除了调用 playSound(调用 QSound::play ).在 Simon::startGame() 完成之前不会播放任何声音,然后您会同时听到所有声音。

auto Simon::playSound(Simon::Color color) -> void {
if (color == Simon::Color::green) {
QSound::play(":/sounds/green.wav");
} else if (color == Simon::Color::red) {
QSound::play(":/sounds/red.wav");
} else if (color == Simon::Color::blue) {
QSound::play(":/sounds/blue.wav");
} else if (color == Simon::Color::yellow) {
QSound::play(":/sounds/yellow.wav");
}
}
auto Simon::loadChallenge() -> void {
challengeVect.clear(); <- Clears previous level
for (auto i = 0; i < Simon::level; ++i) {
auto currentVal = static_cast<int>(std::rand() % 4);
qDebug() << currentVal;
playSound(Simon::Color(currentVal)); <- Calls method above and is meant to play the sound(doesn't)
challengeVect.push_back(currentVal);
std::this_thread::sleep_for(std::chrono::milliseconds(50)); <- delay which works
}
}
auto Simon::startGame() -> void {
auto i = 10;
while (i >= 0) { <- If you replace this with while(true) it will run infinitely without playing a sound
loadChallenge(); <- Where loadChallenge is called from
--i;
}

如果您想要更广泛的了解,如果这不够上下文,代码在这里 ( https://github.com/ItsChoudhry/SimonSaysQt),我深表歉意。

谢谢你看我的问题:D

最佳答案

感谢@RemyLebeau 为我指明了正确的方向。

在正确研究 QSoundEffect 时,我发现 QEventLoop 结合了它们的力量,我有声音和延迟,一切都在生成水平方面起作用。这些是我所做的更改。

  // Add this stuff to my constructor
m_soundEffect = std::make_unique<QSoundEffect>();
m_soundEffect->setLoopCount(1); <- must set loop count
m_eventLoop = std::make_unique<QEventLoop>(); <- event loop needed to hear sound
connect(m_soundEffect.get(), SIGNAL(playingChanged()), m_eventLoop.get(),
SLOT(quit())); <- needed to stop the event loop after sound is played or program locks up on m_eventLoop .exec()
//Updated playSound method
auto Simon::playSound(Simon::Color color) -> void {
if (color == Simon::Color::green) {
m_soundEffect->setSource(QUrl::fromLocalFile(":/sounds/green.wav"));
m_soundEffect->play();
m_eventLoop->exec();
} else if (color == Simon::Color::red) {
m_soundEffect->setSource(QUrl::fromLocalFile(":/sounds/red.wav"));
m_soundEffect->play();
m_eventLoop->exec();
} else if (color == Simon::Color::blue) {
m_soundEffect->setSource(QUrl::fromLocalFile(":/sounds/blue.wav"));
m_soundEffect->play();
m_eventLoop->exec();
} else if (color == Simon::Color::yellow) {
m_soundEffect->setSource(QUrl::fromLocalFile(":/sounds/yellow.wav"));
m_soundEffect->play();
m_eventLoop->exec();
}
}

关于c++ - 调用 QSound 调用,它们之间有延迟 Qt C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59401092/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com