void FilePlayer::setLooping(const bool newState, float startPos)
{
while (newState == true)
{
float endPos = startPos + 4/audioTransportSource.getLengthInSeconds();
float currentPos = audioTransportSource.getCurrentPosition()/audioTransportSource.getLengthInSeconds();
if (currentPos == endPos || currentPos > endPos)
{
audioTransportSource.setPosition(startPos * audioTransportSource.getLengthInSeconds());
}
}
}
这是用于循环任何音频文件4秒的代码,无论多长时间。单击循环按钮,newState变量变为true。我有另一个按钮将其变为false,但是,当我在应用程序中执行循环任务时,CPU /内存/能量影响通过屋顶,应用程序变得无法使用,我无法点击按钮来结束循环
有人可以向我解释为什么会这样吗?
答案 0 :(得分:2)
您是否尝试过添加睡眠电话或确保返回主事件循环以处理按钮点击事件?
编辑:另外,你的newState变量是否应该通过引用(而不是const)传递,以便你可以更改值以停止循环?
Edit2:一个非常基本/简单的线程示例:
FilePlayer.h
#include <iostream>
#include <thread>
#include <chrono>
#include <atomic>
#include <mutex>
class
{
public:
/**
* @brief Constructor
*/
FilePlayer();
/**
* @brief Destructor
*/
~FilePlayer();
private:
/**
* @brief startThread Starts the thread
*/
void startThread();
/**
* @brief stopThread Stops the thread
*/
void stopThread();
/**
* @brief theLoop The threaded loop
*/
void theLoop(float startPos);
std::atomic<bool> running; //lock for thread control
std::mutex mtxAudioTransportSource; //mutex lock for audioTransportSource access
std::thread td;
}
FilePlayer.cpp
FilePlayer::FilePlayer()
{
running.store(false);
}
FilePlayer::~FilePlayer()
{
stopThreads();
}
void FilePlayer::startThreads()
{
if(running.load()){
//The thread is alread running, either call stopThreads before making a different one
//or error out (I just put return in)
return;
}
running.store(true);
td = thread(theLoop, 1.0);
}
void FilePlayer::stopThreads()
{
running.store(false);
if(td.joinable()){
td.join();
}
delete td;
td = NULL;
}
void FilePlayer::theLoop(float startPos)
{
while (running.load())
{
mtxAudioTransportSource.lock(); //Since the audioTransportSource object is being used in multiple threads,
//you must use a mutex lock to make sure only 1 thread is accessing it at any time
//you will need to add the lock/unlock to all threads using it.
//It is often a good idea to lock, get what you need, and unlock as soon as possible so
//the other thread isn't blocked for too long if it is waiting on it.
float audioLength = audioTransportSource.getLengthInSeconds();
float currentPos = audioTransportSource.getCurrentPosition()/audioLength;
mtxAudioTransportSource.unlock();
float endPos = startPos + 4/audioLength;
if (currentPos >= endPos)
{
mtxAudioTransportSource.lock();
audioTransportSource.setPosition(startPos * audioTransportSource.getLengthInSeconds());
mtxAudioTransportSource.unlock();
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
所以我根本没有编译这个,所以可能会有一些错误,但这应该是你工作的一个例子。如果有人有任何更正或优化,请随时说出来。关于线程的最重要的事情是在不使用某种锁的情况下永远不要访问共享变量。祝你的项目好运!