Creating a sound manager in sdl - c++

#include <SDL.h>
#include <SDL_image.h>
#include <SDL_mixer.h>
#include <iostream>
#include "Constants.h"
#include "Texture2D.h"
#include "GameScreenManager.h"
#include "Audio.h"
using namespace::std;
Audio::Audio(string paths)
{
gMusic = NULL;
if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0)
{
cout << "Mixer could not initialise. error: " << Mix_GetError();
}
LoadMusic(paths);
Update();
}
Audio::~Audio()
{
Mix_FreeMusic(gMusic);
gMusic = NULL;
}
void Audio::LoadMusic(string path)
{
gMusic = Mix_LoadMUS(path.c_str());
if(gMusic == NULL)
{
cout << "Failed to load background music! Error: " << Mix_GetError() << endl;
}
}
bool Audio::Update()
{
if(Mix_PlayingMusic() == 0)
{
Mix_PlayMusic(gMusic, -1);
}
return false;
}
this is my sound manager so far. I call it in the source with Audio::Audio("Music/bubble-bobble.mp3"); yet it doesn't play anything. I think something is wrong with the update as the "string path" is being sent through and things. Anyone have any ideas?

Related

Error in lexClient->StartConversationAsync (Aws::Auth::DefaultAuthSignerProvider::GetSigner(const String&) const: Assertion `false' failed.)

I am currently trying to establish a stream connection between my AWSClient and a Lex Bot.
I am getting the following error:
aws-sdk-cpp/aws-cpp-sdk-core/source/auth/signer-provider/DefaultAuthSignerProvider.cpp:48: virtual std::shared_ptr<Aws::Client::AWSAuthSigner> Aws::Auth::DefaultAuthSignerProvider::GetSigner(const String&) const: Assertion `false' failed.
Aborted (core dumped)
when the code run through the following line:
lexClient->StartConversationAsync(LexRequest, OnStreamReady, OnResponseCallback, nullptr);
starting.WaitOne();
the entire .cpp follows:
#include <aws/core/Aws.h>
#include <aws/core/client/AsyncCallerContext.h>
#include <aws/core/utils/Outcome.h>
#include <aws/core/auth/AWSCredentialsProvider.h>
#include <aws/lexv2-runtime/LexRuntimeV2Client.h>
#include <aws/lexv2-runtime/model/AudioInputEvent.h>
#include <aws/lexv2-runtime/model/RecognizeUtteranceRequest.h>
#include <aws/lexv2-runtime/model/RecognizeUtteranceResult.h>
#include <aws/lexv2-runtime/model/StartConversationHandler.h>
#include <aws/lexv2-runtime/model/StartConversationRequest.h>
#include <aws/lexv2-runtime/model/StartConversationRequestEventStream.h>
#include <aws/lex/LexRuntimeServiceClient.h>
#include <aws/lex/LexRuntimeServiceRequest.h>
#include <aws/lex/model/PostContentRequest.h>
#include <aws/lex/model/PostContentResult.h>
#include <iterator>
#include <fstream>
#include <chrono>
#include <unistd.h>
using namespace Aws::LexRuntimeV2;
int SessionCount = 0;
int main(int argc, char* argv[])
{
std::string lexKey, lexSecret;
std::string botId, botAliasId, localeId, sessionId, regionId;
// bot credentials
botId = "_";
botAliasId = "_";
lexKey = "_";
lexSecret = "_";
localeId = "en_US";
// starting api
Aws::SDKOptions options;
options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Info;
Aws::InitAPI(options);
Aws::Client::ClientConfiguration config;
config.region = "us-east-1";
// creating a lex client
auto lexClient = Aws::MakeUnique<LexRuntimeV2Client>("MyClient", Aws::Auth::AWSCredentials(lexKey.c_str(), lexSecret.c_str()), config);
Model::StartConversationRequest LexRequest;
Model::StartConversationHandler requestHandler;
requestHandler.SetTranscriptEventCallback([](const Model::TranscriptEvent& ev)
{
std::cout << ev.GetTranscript() << std::endl;
});
requestHandler.SetOnErrorCallback([](const Aws::Client::AWSError<LexRuntimeV2Errors>& error)
{
std::cout << "Request handler: " << error.GetMessage() << std::endl;
});
LexRequest.WithLocaleId(localeId).WithBotId(botId.c_str()).WithBotAliasId(botAliasId.c_str()).WithSessionId("Blah")
.WithConversationMode(Model::ConversationMode::AUDIO).WithEventStreamHandler(requestHandler);
Aws::Utils::Threading::Semaphore signaling(0 /*initialCount*/, 1 /*maxCount*/);
auto OnResponseCallback = [&signaling](const LexRuntimeV2Client*,const Model::StartConversationRequest&,
const Model::StartConversationOutcome& outcome, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&)
{
std::cout << "Response handler: " << outcome.GetError().GetMessage();
signaling.Release();
};
Model::StartConversationRequestEventStream* pStream = nullptr;
Aws::Utils::Threading::Semaphore starting(0 /*initialCount*/, 1 /*maxCount*/);
auto OnStreamReady = [&starting,&pStream](Model::StartConversationRequestEventStream& stream)
{
pStream = &stream;
pStream->SetSignatureSeed("blah");
starting.Release();
};
lexClient->StartConversationAsync(LexRequest, OnStreamReady, OnResponseCallback, nullptr);
starting.WaitOne();
std::ifstream audioFile(argv[1], std::ios_base::binary);
if (!audioFile)
{
std::cout << "Cannot open audio file " << argv[2] << std::endl;
return 0;
}
if (audioFile) {
std:: cout << "Audio file is open: "<< std::endl;
}
while (!audioFile.eof())
{
unsigned char buf[320 + 1];
audioFile.read((char*)buf, 320);
Aws::Utils::ByteBuffer bytes(buf, audioFile.gcount());
Model::AudioInputEvent input;
auto millisec_since_epoch = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock().now().time_since_epoch()).count();
input.SetClientTimestampMillis(millisec_since_epoch);
input.SetAudioChunk(bytes);
input.SetContentType("audio/lpcm; sample-rate=8000; sample-size-bits=16; channel-count=1; is-big-endian=false");
pStream->WriteAudioInputEvent(input); // o erro está aqui (quando comento o StartConversation)
sleep(20);
}
signaling.WaitOne(); // prevent the application from exiting until we're done
Aws::ShutdownAPI(options);
}
//g++ -o main main.cpp -laws-cpp-sdk-s3 -laws-cpp-sdk-core -laws-cpp-sdk-lex -laws-cpp-sdk-lex-models -laws-cpp-sdk-lexv2-models -laws-cpp-sdk-lexv2-runtime
debug log](https://i.stack.imgur.com/tpA9c.png)
I have no idea why this is happening, and without this command i obviously can't publish events to lex, since the connection does not have started

Debug Assertion when using Interpreter in TensorFlowLite

I am trying to use the Mediapipe Hand tflite file using TensorFlowLite. But whenever I am getting an error when referring to the input tensor data and dimensions.\
This is the main.cpp:
#include <iostream>
#include <cstdio>
#include <vector>
#include <tensorflow/lite/interpreter.h>
#include <tensorflow/lite/kernels/register.h>
#include <tensorflow/lite/model.h>
#include <tensorflow/lite/optional_debug_tools.h>
#include <flatbuffers/flatbuffers.h>
#include <opencv2/opencv.hpp>
#include <opencv2/core.hpp>
#include <tensorflow/lite/model_builder.h>
#include <tensorflow/lite/string_util.h>
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "tensorflow/lite/interpreter.h"
#include "tensorflow/lite/model.h"
#include "tensorflow/lite/builtin_op_data.h"
#include "tensorflow/lite/kernels/register.h"
using namespace std;
int main()
{
const char* filename = "C:/Users/naren/OneDrive/Documents/MediapipeHands/hand_landmark_full.tflite";
const char* image_filename = "C:/Users/naren/OneDrive/Documents/MediapipeHands/hand.jpg";
std::unique_ptr<tflite::FlatBufferModel> model = tflite::FlatBufferModel::BuildFromFile(filename);
if (model == nullptr) {
cerr << "Fail to build FlatBufferModel from file: " << filename << std::endl;
exit(1);
}
tflite::ops::builtin::BuiltinOpResolver resolver;
std::unique_ptr<tflite::Interpreter> interpreter;
if (tflite::InterpreterBuilder(*model, resolver) (&interpreter) != kTfLiteOk) {
std::cerr << "Failed to build interpreter." << std::endl;
exit(1);
}
interpreter->SetNumThreads(-1);
if (interpreter->AllocateTensors() != kTfLiteOk) {
cerr << "Failed to allocate tensors." << endl;
exit(1);
}
cv::Mat image;
auto frame = cv::imread(image_filename);
if (frame.empty()) {
cout << "Image not loaded";
exit(1);
}
cv::cvtColor(frame, image, cv::COLOR_BGR2RGB);
cv::flip(image, image, 1);
cv::imshow("Image", image);
cv::waitKey(10);
const std::vector<int>& inputs = interpreter->inputs();
TfLiteTensor* inputTensor = interpreter->tensor(inputs[0]);
return 0;
}
The program is failing at the last line before the return 0 line. If we run only uptil cv::waitKey(10), then a debug assertion window pops up. I also have the cmake file, please comment if you need it.

how to reboot the application when there is a change in last modification time of an accesed file in that application

I'm new to thread programming. I'm trying to create an application which continually checks the Last Modification time of some file and exits the program when that time has changed.
Please find my code below:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <cerrno>
#include <unistd.h>
using namespace std;
#define NUM_THREADS 2
void *getFileCreationTime(void *path) {
const char *pt;
pt=(const char *)path;
struct stat attr;
stat("/home/utthunga/shmrp.cpp", &attr);
while(1){
char *timestamp= ctime(&attr.st_mtime);
if(timestamp)
{
cout<<"Last modified time: %s"<< ctime(&attr.st_mtime)<<endl;
cout<<"No changes has been made to the file"<<endl;
sleep(4);
}
else
{
cout<<"Last modified time: %s"<< ctime(&attr.st_mtime)<<endl;
cout<<"Time stamp has been changed"<<endl;
exit(0);
}
}
pthread_exit(NULL);
}
int main()
{
pthread_t threads[NUM_THREADS];
int i;
int rc;
for( i = 0; i < NUM_THREADS-1; i++ )
rc = pthread_create(&threads[i], NULL, getFileCreationTime, (void *)i);
pthread_exit(NULL);
return 0;
}
Can anyone please tell me what changes I have to implement in order to check the last modification time of that file continually and exit the application when that time has changed?
After you retrieve the file's modification time the first time, you need to save it so you can compare it to subsequent values retrieved afterwards.
Try something more like this instead:
void* getFileCreationTime(void *) {
const char *path = "/home/utthunga/shmrp.cpp";
struct stat attr;
if (stat(path, &attr) < 0) {
cout << "stat error" << endl;
exit(0);
}
time_t mtime = attr.st_mtime;
cout << "Last modified time: " << ctime(&mtime) << endl;
while(1) {
sleep(4);
if (stat(path, &attr) < 0) {
cout << "stat error" << endl;
exit(0);
}
if (attr.st_mtime != mtime) {
cout << "Time stamp has been changed" << endl;
exit(0);
} else {
cout << "No changes have been made to the file" << endl;
}
}
pthread_exit(NULL);
}

Want to update a QtableWidget within a QThread

I'm starting a project called Nice System Monitor aiming to monitor processes on Linux, and I'm using C++ and Qt with QtCreator.
I've started making a QThread with a function called to fill a QTableWidget repeatedly but the table doesn't update properly even if I delete each row before fulling it up again.
I'm quite new to Qt and inspired myself of different sources on the Internet.
Here's the code of the QThread :
#include <unistd.h>
#include <ios>
#include <iostream>
#include <fstream>
#include <string>
#include <dirent.h>
#include <stdio.h>
#include <cctype>
#include <stdlib.h>
#include <vector>
#include <sstream>
#include "renderprocesstablethread.h"
#include <proc/readproc.h>
#include <proc/procps.h>
#include "mainwindow.h"
using namespace std;
RenderProcessTableThread::RenderProcessTableThread(QObject *parent)
: QThread(parent)
{
restart = false;
abort = false;
}
RenderProcessTableThread::~RenderProcessTableThread()
{
mutex.lock();
abort = true;
condition.wakeOne();
mutex.unlock();
wait();
}
bool RenderProcessTableThread::isNum(char *s) {
int i = 0, flag;
while(s[i]){
//if there is a letter in a string then string is not a number
if(isalpha(s[i]) || s[i] == '.'){
flag = 0;
break;
}
else flag = 1;
i++;
}
if (flag == 1) return true;
else return false;
}
string RenderProcessTableThread::convertDouble(double value) {
std::ostringstream o;
if (!(o << value))
return "";
return o.str();
}
string RenderProcessTableThread::convertInt(int value) {
std::ostringstream o;
if (!(o << value))
return "";
return o.str();
}
void RenderProcessTableThread::run()
{
forever {
mutex.lock();
mutex.unlock();
fillProcessTable();
sleep(1000);
//cout << "ça marche" << endl;
}
mutex.lock();
if (!restart)
condition.wait(&mutex);
restart = false;
mutex.unlock();
}
void RenderProcessTableThread::setLocalMainWindow(MainWindow& w)
{
localMainWindow = &w;
ui_tableWidgetProcessus = localMainWindow->findChild<QTableWidget*>("tableWidgetProcessus");
ui_tableWidgetProcessus->setColumnCount(11);
ui_tableWidgetProcessus->setColumnWidth(10,508);
QFont fnt;
fnt.setPointSize(10);
fnt.setFamily("Arial");
ui_tableWidgetProcessus->setFont(fnt);
QStringList labels;
labels << "user" << "pid" << "cpu" << "nice" << "vsz" << "rss" << "tty" << "stat" << "start" << "time" << "cmd";
ui_tableWidgetProcessus->setHorizontalHeaderLabels(labels);
}
void RenderProcessTableThread::fillProcessTable() {
QMutexLocker locker(&mutex);
if (!isRunning()) {
start(LowPriority);
} else {
restart = true;
condition.wakeOne();
}
PROCTAB* proc = openproc(PROC_FILLUSR | PROC_FILLMEM | PROC_FILLSTAT | PROC_FILLSTATUS | PROC_FILLARG);
proc_t proc_info;
memset(&proc_info, 0, sizeof(proc_info));
int totalRow = ui_tableWidgetProcessus->rowCount();
for ( int i = 0; i < totalRow ; ++i )
{
ui_tableWidgetProcessus->removeRow(i);
}
int i = 0;
while (readproc(proc, &proc_info) != NULL) {
cout << proc_info.fuser << proc_info.tid << proc_info.cmd << proc_info.resident << proc_info.utime << proc_info.stime << endl;
ui_tableWidgetProcessus->setRowCount(i+1);
ui_tableWidgetProcessus->setItem(i,0,new QTableWidgetItem(QString(proc_info.fuser),0));
ui_tableWidgetProcessus->setItem(i,1,new QTableWidgetItem(QString((char*)convertInt(proc_info.tid).c_str()),0));
ui_tableWidgetProcessus->setItem(i,2,new QTableWidgetItem(QString((char*)convertInt(proc_info.pcpu).c_str()),0));
ui_tableWidgetProcessus->setItem(i,3,new QTableWidgetItem(QString((char*)convertInt(proc_info.nice).c_str()),0));
ui_tableWidgetProcessus->setItem(i,4,new QTableWidgetItem(QString((char*)convertInt(proc_info.vm_size).c_str()),0));
ui_tableWidgetProcessus->setItem(i,5,new QTableWidgetItem(QString((char*)convertInt(proc_info.rss).c_str()),0));
ui_tableWidgetProcessus->setItem(i,6,new QTableWidgetItem(QString((char*)convertInt(proc_info.tty).c_str()),0));
ui_tableWidgetProcessus->setItem(i,7,new QTableWidgetItem(QString(proc_info.state),0));
ui_tableWidgetProcessus->setItem(i,8,new QTableWidgetItem(QString((char*)convertInt(proc_info.start_time).c_str()),0));
ui_tableWidgetProcessus->setItem(i,9,new QTableWidgetItem(QString((char*)convertInt(proc_info.stime).c_str()),0));
//cout << "proc_info.tid : " << proc_info.tid << endl;
//cout << "proc_info.cmdline : " << proc_info.cmdline << endl;
string text;
if (proc_info.cmdline != 0) {
vector<string> v(proc_info.cmdline, proc_info.cmdline + sizeof(proc_info.cmdline) / sizeof(string));
text = v[0];
}
else {
vector<string> v;
v.push_back(proc_info.cmd);
text = v[0];
}
//string text = char_to_string(proc_info.cmdline);
ui_tableWidgetProcessus->setItem(i,10,new QTableWidgetItem(QString((char*)text.c_str()),0));
i++;
}
closeproc(proc);
}
Are they better ways of doing this ?
Thanks
Patrick
This looks like something for Qt's Signal and Slots.
In your case the the thread emits the signal and a slot in your window will be called.
So in your RenderProcessTableThread.h define a signal
signals:
void newValues(const QString &data);
And in your mainwindow.h
public slots:
void showNewValues(const QString &data);
add the data to your table in this slot.
Then you have to connect them (e. g. in the constructor of your mainwindow after the creation of the thread)
connect(yourThread, SIGNAL(newValues(QString)), this, SLOT(showNewValues(QString)));
Whenever you want to show new data, emit the signal (e. g. somewhere in your fillProcessTable() function):
emit newValues(yourValues);
Qt does the connection between the threads for you.

String Validation in a Certain Format

I'm creating a simple chess game which uses shared memory. There are two players (Black,White) in the game and they are working in Strict Alternation principle. I get input from every player in turn-based sense and use them. My question is: I want the user to give the input like mov(a1,b2). After getting the input First: I want to validate if it is in the correct format and then I want to use the a1,b2 values in a function. Here is the part of my code:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <stdlib.h>
#include <iostream>
using namespace std;
#define SHMSZ 27
int main() {
int shmid;
key_t key;
char *shm;
string cmd;
int check =1;
key = 111;
/*
* Locate the segment.
*/
if ((shmid = shmget(key, SHMSZ, 0666)) < 0) {
perror("shmget");
return 0;
}
/*
* Now we attach the segment to our data space.
*/
if ((shm = (char*) shmat(shmid, NULL, 0)) == (char *) -1) {
perror("shmat");
return 0;
}
cout << *shm << endl;
while(check)
{
if(*shm == '*') //checks if other player finished the game
{
cout<<"End of the game. Thank you for playing." <<endl;
*shm ='*';
exit(1);
}
while(*shm == 'B')
{
cout << "Enter a move" << endl;
cin >> cmd;
if(cmd=="eog") // Finish the game
{
cout<<"End of the game. Thank you for playing." <<endl;
*shm ='*';
exit(1);
}
*shm = 'W';
}
}
return 0;
}