Browse Source

V0.2.6
1、完成了发送mqtt的功能,还未发送成功

Apple 1 week ago
parent
commit
d7e95360b0

+ 1 - 0
CMakeLists.txt

@@ -194,4 +194,5 @@ file(GLOB GLOBAL_SRC
 add_subdirectory(${CMAKE_SOURCE_DIR}/Server)
 add_subdirectory(${CMAKE_SOURCE_DIR}/SettingLibrary)
 add_subdirectory(${CMAKE_SOURCE_DIR}/show2)
+# add_subdirectory(${CMAKE_SOURCE_DIR}/show3)
 

+ 6 - 1
Server/GlobalInfo/GlobalInfo.h

@@ -15,6 +15,7 @@
  */
 
 
+#include <qt5/QtCore/qchar.h>
 #include <string>
 #include <QString>
 
@@ -49,6 +50,8 @@ public:
     QString mqttIP() const {return m_mqttIP;}
     int mqttPort() const {return m_mqttPort;}
     void setMqttInfo(const QString& ip, int port);
+    QString mqttPublishTopic() const {return m_mqttPublishTopic;}
+    QString mqttPubTopicDB() const {return m_pubTopicDB;}
     
     /* 获取WebAPI信息 */
     QString webAPIUrl() const {return m_webAPIUrl;}
@@ -144,6 +147,8 @@ private:
     QString m_webAPIUrl;               /* WebAPI地址 */
     QString m_webAPIID;                /* WebAPI ID */
     const QString m_appType = "ACAWatch"; /* 应用类型 */
+    QString m_mqttPublishTopic = "LH_ACAServer"; /* MQTT发布主题 */
+    QString m_pubTopicDB = "LH_ACAServer/DB"; /* 音量包发布主题 */
 
     /******************** 音频基础数据 *********************/
     /* 环形队列中每个文件的大小,也是生成的wav文件的大小
@@ -160,7 +165,7 @@ private:
     // int32_t m_oneSecondCount = 0;              /* 这里使用一秒音频的字节个数 */
     int32_t m_queueElementCount = 180;          /* 默认缓冲区的大小,也就是音频处理线程的环形队列的大小,单位是秒 */
     int32_t m_wavFileDuration = 60;             /* 一个wav小文件有多少秒的数据 */
-    int32_t m_noiseElementDuration = 2;         /* 噪音检测元素大小,单位:秒 */
+    int32_t m_noiseElementDuration = 1;         /* 噪音检测元素大小,单位:秒 */
 
     /* 相关的文件夹 */
     const QString m_dirWav = "WAV";             /* wav文件存储目录 */

+ 0 - 4
Server/LHLibraryAPI/LHNoiseDetectAPI.cpp

@@ -1,4 +0,0 @@
-#include "LHNoiseDetectAPI.h"
-
-
-

+ 0 - 13
Server/LHLibraryAPI/LHNoiseDetectAPI.h

@@ -1,13 +0,0 @@
-#ifndef LHNOISEDETECTAPI_H
-#define LHNOISEDETECTAPI_H
-
-
-
-
-
-
-
-
-
-
-#endif // LHNOISEDETECTAPI_H

+ 107 - 3
Server/ThreadCalculate/CompareItemThread.cpp

@@ -1,11 +1,16 @@
 #include "CompareItemThread.h"
 
+#include "FromMQTT.h"
+#include "GlobalInfo.h"
 #include "ThreadManager.h"
 #include "CalculateDBThread.h"
 #include "NoiseDetectThread.h"
 #include "CompareDoubleThread.h"
 #include "ThreadPool.h"
+#include "commonDefine.h"
 #include "spdlog.h"
+#include <qt5/QtCore/qchar.h>
+#include <qt5/QtCore/qglobal.h>
 
 
 CompareItemThread::CompareItemThread(CalculateThreadInfo_t& threadInfo)
@@ -87,7 +92,7 @@ void CompareItemThread::task()
 
         /* 清除标志位 */
         clearUpdateFlags();
-        SPDLOG_LOGGER_WARN(m_logger, "{} 发送对比项数据到MQTT中", m_logBase);
+        // SPDLOG_LOGGER_WARN(m_logger, "{} 发送对比项数据到MQTT中", m_logBase);
     }
     /* 清理数据 */
     clearData();
@@ -157,6 +162,35 @@ bool CompareItemThread::initData()
         m_mapAlarmPhaseLast.insert({road.nCompareRoadNum, AlarmInfo_t()});
     }
 
+    /* 登陆MQTT */
+    m_pubTopic = QString("%1/%2").arg(GInfo.mqttPubTopicDB()).arg(QString::number(m_threadInfo.compareItemInfo.nID));
+    m_pFromMQTT = new FromMQTT;
+    m_pFromMQTT->setIPAndPort(GInfo.mqttIP(), GInfo.mqttPort());
+    m_pFromMQTT->connectToServer();
+    /* 等待连接成功 */
+    auto startTime = std::chrono::steady_clock::now(); // 记录开始时间
+    while(true)
+    {
+        if(m_pFromMQTT->connectState() == QMQTT::ConnectionState::STATE_CONNECTED)
+        {
+            break; // 连接成功
+        }
+        /* 超过10秒还没有连接成功,返回失败 */
+        if(std::chrono::steady_clock::now() - startTime > std::chrono::seconds(10))
+        {
+            SPDLOG_LOGGER_ERROR(m_logger, "{} 连接MQTT服务器超时", m_logBase);
+            if(m_pFromMQTT != nullptr)
+            {
+                delete m_pFromMQTT; // 删除MQTT对象
+                m_pFromMQTT = nullptr; // 设置为nullptr
+            }
+            return false;
+        }
+        std::this_thread::sleep_for(std::chrono::milliseconds(100));
+    }
+
+    SPDLOG_LOGGER_INFO(m_logger, "☆ {} 音量包订阅主题: {}", m_logBase, m_pubTopic.toStdString());
+
     return true;
 }
 
@@ -183,6 +217,12 @@ void CompareItemThread::clearData()
             SPDLOG_LOGGER_ERROR(m_logger, "{} 移除录音通道 {}:{} 失败", m_logBase, roadInfo.strSoundCardName.toStdString(), roadInfo.roadInfo.nRoadNum);
         }
     }
+
+    if(m_pFromMQTT != nullptr)
+    {
+        delete m_pFromMQTT; // 删除MQTT对象
+        m_pFromMQTT = nullptr; // 设置为nullptr
+    }
 }
 
 
@@ -476,9 +516,20 @@ void CompareItemThread::processAlarmData()
 void CompareItemThread::sendResultData()
 {
     /* 生成json数据 */
-
+    QByteArray jsonData;
+    if(!generateMQTTJsonData(m_compareResult, jsonData))
+    {
+        SPDLOG_LOGGER_WARN(m_logger, "{} 生成音量包 JSON数据失败", m_logBase);
+        return;
+    }
     /* 发送到mqtt中 */
-
+    int errorCode = 0;
+    if(!m_pFromMQTT->sendMessage(m_pubTopic, jsonData, 0, errorCode))
+    {
+        SPDLOG_LOGGER_ERROR(m_logger, "{} 发送音量包数据到 {} 失败,错误代码: {}", m_logBase, m_pubTopic.toStdString(), errorCode);
+    }else {
+        SPDLOG_LOGGER_DEBUG(m_logger, "{} 发送音量包数据到 {} 成功", m_logBase, m_pubTopic.toStdString());
+    }
 }
 
 /* 清除标志更新位 */
@@ -490,4 +541,57 @@ void CompareItemThread::clearUpdateFlags()
     }
 }
 
+/* 生成发送至MQTT的JSON数据 */
+bool CompareItemThread::generateMQTTJsonData(const CompareResult_t& compareResult, QByteArray& jsonData)
+{
+    try 
+    {
+        /* 生成基础信息 */
+        nJson json0;
+        json0["compareItem_id"] = compareResult.compareItemID;
+        json0["compareItem_name"] = compareResult.compareItemName.c_str();
+        json0["date_time"] = compareResult.dateTime.toString("yyyy-MM-dd hh:mm:ss").toStdString();
+        json0["is_client_alarm"] = compareResult.isClientAlarm;
+        
+        for(const auto& roadVolume : compareResult.mapRoadVolumes)
+        {
+            nJson json1;
+            json1["soundCard_id"] = roadVolume.second.roadInfo.scRoadInfo.strSoundCardID.toStdString(); /* 声卡id和声卡通道id */
+            json1["soundCard_road_id"] = roadVolume.second.roadInfo.scRoadInfo.roadInfo.nRoadNum;
+            /* 对比项通道编号和名称 */
+            json1["item_road_num"] = roadVolume.second.roadInfo.nCompareRoadNum;
+            json1["item_road_name"] = roadVolume.second.roadInfo.strCompareRoadName.toStdString();
+            json1["similarity"] = roadVolume.second.similarity;
+            json1["is_silence"] = roadVolume.second.isSilence;
+            json1["is_overload"] = roadVolume.second.isOverload;
+            json1["is_reversed"] = roadVolume.second.isReversed;
+            json1["is_noise"] = roadVolume.second.isNoise;
+            json1["is_noise_warning"] = roadVolume.second.isNoiseWarning;
+            json1["is_consistency"] = roadVolume.second.isConsistency;
+            json1["is_not_consistency_warning"] = roadVolume.second.isNotConsistencyWarning;
+            json1["left_real_time_db"] = roadVolume.second.leftRealTimeDB;
+            json1["right_real_time_db"] = roadVolume.second.rightRealTimeDB;
+            /* 添加音量包信息 */
+            for(const auto& db : roadVolume.second.vecleftDB)
+            {
+                json1["left_db_array"].push_back(db);
+            }
+            for(const auto& db : roadVolume.second.vecrightDB)
+            {
+                json1["right_db_array"].push_back(db);
+            }
+
+            /* 添加到基础信息中 */
+            json0["road_volumes"].push_back(json1);
+        }
+
+        /* 转换为字符串 */
+        jsonData.clear();
+        jsonData = QByteArray::fromStdString(json0.dump());
+
+    }nJsonCatch
+
+    return true;
+}
+
 

+ 9 - 0
Server/ThreadCalculate/CompareItemThread.h

@@ -2,10 +2,12 @@
 #define _COMPAREITEMTHREAD_H_
 
 #include <map>
+#include <qt5/QtCore/qchar.h>
 
 #include "BaseCalculateThread.h"
 #include "CompareResult.h"
 #include "AlarmInfo.h"
+#include "FromMQTT.h"
 
 class CalculateDBThread;
 class NoiseDetectThread;
@@ -61,8 +63,15 @@ private:
 
     /* 清除标志更新位 */
     void clearUpdateFlags();
+    /* 生成发送至MQTT的JSON数据 */
+    bool generateMQTTJsonData(const CompareResult_t& compareResult, QByteArray& jsonData);
 
 private:
+    /* 发送音量包信息到mqtt中 */
+    FromMQTT* m_pFromMQTT = nullptr;
+    /* 发布的主题 */
+    QString m_pubTopic;
+
     /* 计算音量信息的线程指针,第一个是主通道线程,int是对比项中的通道号 */
     std::map<int, CalculateDBThread*> m_mapCalculateDBThreads;
     std::map<int, bool> m_mapCDBUpdated;             /* 音量包更新标志位 */

+ 2 - 2
Server/ThreadCalculate/ConsistencyCompareThread.cpp

@@ -178,8 +178,8 @@ bool ConsistencyCompareThread::compareConsistency()
             return false;
         }
     }
-    SPDLOG_LOGGER_DEBUG(m_logger, "{} 一致性比对结果: 源文件: {}, 目标文件: {}, 最高相似度: {:.3f}, 平均相似度: {:.3f}",
-        m_logBase, m_wavFilePath1.fileName, m_wavFilePath2.fileName, result->highest_similarity, result->average_similarity);
+    // SPDLOG_LOGGER_DEBUG(m_logger, "{} 一致性比对结果: 源文件: {}, 目标文件: {}, 最高相似度: {:.3f}, 平均相似度: {:.3f}",
+    //     m_logBase, m_wavFilePath1.fileName, m_wavFilePath2.fileName, result->highest_similarity, result->average_similarity);
 
     /* 保存结果 */
     m_mutexResult.lock();

+ 30 - 4
Server/ThreadCalculate/NoiseDetectThread.cpp

@@ -1,11 +1,13 @@
 #include "NoiseDetectThread.h"
 
+#include <random>
 
 #include "CreateWAVThread.h"
 #include "ThreadManager.h"
 #include "commonDefine.h"
 #include "GlobalInfo.h"
 #include "signalstats_wrapper.h"
+#include "spdlog.h"
 
 
 NoiseDetectThread::NoiseDetectThread(CalculateThreadInfo_t& threadInfo)
@@ -86,18 +88,35 @@ bool NoiseDetectThread::initData()
     auto sampleRate = GInfo.sampleRate();
     m_sample_rate = static_cast<double>(sampleRate);
 
+    /* 初始化噪音检测功能 */
+    signalstats_wrapper::initialize();
+
     return true;
 }
 
 /* 清理数据 */
 void NoiseDetectThread::clearData()
 {
-
+    /* 释放资源 */
+    signalstats_wrapper::finalize();
 }
 
 /* 调用动态库检测噪音 */
 bool NoiseDetectThread::detectNoise()
 {
+    SPDLOG_LOGGER_ERROR(m_logger, "{} 开始调用动态库计算噪音", m_logBase);
+    SPDLOG_LOGGER_INFO(m_logger, "{} 左声道数据大小: {}, 右声道数据大小: {}", 
+        m_logBase, m_leftRightData.vecLeftData.size(), m_leftRightData.vecRightData.size());
+
+        // std::vector<double> audio_signal(48000);
+        // std::random_device rd;
+        // std::mt19937 gen(rd());
+        // std::normal_distribution<> dist(0.0, 1.0);
+        
+        // for (auto& sample : audio_signal) {
+        //     sample = dist(gen);
+        // }
+
     auto startTime = std::chrono::steady_clock::now();
     bool isNoiseLeft = false; /* 是否检测到左声道噪音 */
     bool isNoiseRight = false; /* 是否检测到右声道噪音 */
@@ -108,6 +127,7 @@ bool NoiseDetectThread::detectNoise()
         auto ret = signalstats_wrapper::detect_signal_wrapper(
             jsonOutput,             /* 返回结果,和jsonResult是一样的 */
             m_leftRightData.vecLeftData,  /* 左声道数据 */
+            // audio_signal,           /* 测试数据 */
             m_sample_rate,          /* 采样率(HZ) */
             m_silence_threshold,    /* 静音阈值 */
             m_db_threshold,         /* 分贝阈值 */
@@ -116,15 +136,21 @@ bool NoiseDetectThread::detectNoise()
             m_nperseg,              /* 每段样本数 */
             m_noverlap,             /* 重叠样本数 */
             m_nfft,                 /* FFT点数 */
-            false                   /* 是否输出调试信息, true表示输出调试信息, false表示不输出调试信息 */
+            true                   /* 是否输出调试信息, true表示输出调试信息, false表示不输出调试信息 */
         );
         isNoiseLeft = jsonOutput["noise"].is_null() ? false : jsonOutput["noise"].get<bool>();
 
+        std::chrono::duration<double> duration = std::chrono::steady_clock::now() - startTime;
+        std::chrono::milliseconds ms = std::chrono::duration_cast<std::chrono::milliseconds>(duration);
+        SPDLOG_LOGGER_ERROR(m_logger, "{} 计算左声道噪音耗时: {}ms", m_logBase, ms.count());
+        startTime = std::chrono::steady_clock::now(); /* 重置开始时间 */
+
         /*-------------------------- 再检测右声道 --------------------------*/
         jsonOutput.clear(); /* 清空输出结果 */
         signalstats_wrapper::detect_signal_wrapper(
             jsonOutput,             /* 返回结果,和jsonResult是一样的 */
             m_leftRightData.vecRightData,  /* 右声道数据 */
+            // audio_signal,           /* 测试数据 */
             m_sample_rate,          /* 采样率(HZ) */
             m_silence_threshold,    /* 静音阈值 */
             m_db_threshold,         /* 分贝阈值 */
@@ -146,9 +172,9 @@ bool NoiseDetectThread::detectNoise()
 
     std::chrono::duration<double> duration = std::chrono::steady_clock::now() - startTime;
     std::chrono::milliseconds ms = std::chrono::duration_cast<std::chrono::milliseconds>(duration);
-    SPDLOG_LOGGER_DEBUG(m_logger, "{} 调用动态库检测噪音耗时: {}ms", m_logBase, ms.count());
+    SPDLOG_LOGGER_ERROR(m_logger, "{} 计算右声道噪音耗时: {}ms", m_logBase, ms.count());
 
-    SPDLOG_LOGGER_DEBUG(m_logger, "{} 左声道噪音检测结果: {}, 右声道噪音检测结果: {}", m_logBase, isNoiseLeft, isNoiseRight);
+    SPDLOG_LOGGER_ERROR(m_logger, "{} 左声道噪音检测结果: {}, 右声道噪音检测结果: {}", m_logBase, isNoiseLeft, isNoiseRight);
 
     /* -------------------------- 和以往的结果对比 --------------------------*/
     m_isNoiseLast = m_isNoise.load(); /* 上一次的噪音检测结果 */

+ 29 - 7
Server/ThreadRecord/CreateWAVThread.cpp

@@ -2,9 +2,11 @@
 
 #include "GlobalInfo.h"
 #include "SystemConfig.h"
+#include "spdlog.h"
 
 #include <QFile>
 #include <QDir>
+#include <random>
 
 
 CreateWAVThread::CreateWAVThread(RecordThreadInfo_t& threadInfo)
@@ -41,8 +43,8 @@ bool CreateWAVThread::setData(const AudioSrcData& srcData)
     {
         /* 出队一个最早的元素 */
         AudioSrcData* oldData = m_queueWavSrcData.front_pop();
-        SPDLOG_LOGGER_WARN(m_logger, "{} 环形队列已满,出队一个元素,时间: {}, 大小: {}", 
-            m_logBase, oldData->startTime.toString("yyyy-MM-dd hh:mm:ss.zzz").toStdString(), oldData->dataSize);
+        SPDLOG_LOGGER_TRACE(m_logger, "{} 环形队列已满,出队一个元素,时间: {}, 大小: {}", 
+            m_logBase, oldData->startTime.toString("yyyy-MM-dd hh:mm:ss").toStdString(), oldData->dataSize);
         if(oldData != nullptr){
             delete oldData;
             oldData = nullptr;
@@ -62,8 +64,8 @@ bool CreateWAVThread::setData(const AudioSrcData& srcData)
     } else
     {
         AudioSrcData* oldData = m_queueLeftRightSrcData.front_pop();
-        SPDLOG_LOGGER_WARN(m_logger, "{} 左右声道环形队列已满,出队一个元素,时间: {}, 大小: {}", 
-            m_logBase, oldData->startTime.toString("yyyy-MM-dd hh:mm:ss.zzz").toStdString(), oldData->dataSize);
+        SPDLOG_LOGGER_TRACE(m_logger, "{} 左右声道环形队列已满,出队一个元素,时间: {}, 大小: {}", 
+            m_logBase, oldData->startTime.toString("yyyy-MM-dd hh:mm:ss").toStdString(), oldData->dataSize);
         delete oldData;
         oldData = nullptr;
         m_queueLeftRightSrcData.push(newData2);
@@ -91,7 +93,7 @@ bool CreateWAVThread::getLatestLeftRightData(AudioLeftRightData& leftRightData)
 {
     if(m_queueLeftRightData.isEmpty())
     {
-        SPDLOG_LOGGER_TRACE(m_logger, "{} 左右声道数据队列为空", m_logBase);
+        // SPDLOG_LOGGER_TRACE(m_logger, "{} 左右声道数据队列为空", m_logBase);
         return false;
     }
     std::lock_guard<std::mutex> lock(m_queueLeftRightData.mutex);
@@ -375,6 +377,7 @@ void CreateWAVThread::removeWAVFileFromList(std::list<WavFilePath>& listDeleteFi
     listDeleteFile.clear();
 }
 
+
 /* 将每秒的数据拆解成两个声道,给噪音检测线程使用 */
 bool CreateWAVThread::splitLeftRightChannel()
 {
@@ -404,8 +407,8 @@ bool CreateWAVThread::splitLeftRightChannel()
         }
         /* 先将char类型转换成short,然后转换成double */
         int dec = data->dataSize % 4;
-        int srcSize = data->dataSize - dec; // 确保是4的倍数
-        for(int j = 0; j < srcSize / 2; ++j)
+        int oneChannelSize = (data->dataSize - dec) / 2; // 确保是4的倍数
+        for(int j = 0; j < oneChannelSize; ++j)
         {
             int16_t sample = *reinterpret_cast<int16_t*>(data->pData + j * 2);
             double sampleDouble = static_cast<double>(sample);
@@ -419,10 +422,26 @@ bool CreateWAVThread::splitLeftRightChannel()
         }
         pLeftRightData->numMSecond += 1000; // 每次处理1秒的数据,增加1000毫秒
 
+        /* 更新结束时间戳 */
+        pLeftRightData->endTime = data->endTime;
+
         delete data;
         data = nullptr;
     }
 
+    /* 测试数据 */
+        // std::vector<double> audio_signal(m_sampleRate);
+        // std::random_device rd;
+        // std::mt19937 gen(rd());
+        // std::normal_distribution<> dist(0.0, 1.0);
+        
+        // for (auto& sample : audio_signal) {
+        //     sample = dist(gen);
+        // }
+        // pLeftRightData->vecLeftData = audio_signal; // 左声道数据
+        // pLeftRightData->vecRightData = audio_signal; // 右声道数据
+
+
     /* 将分离完成的数据添加到环形队列中 */
     m_queueLeftRightData.mutex.lock();
     auto tmp = m_queueLeftRightData.push(pLeftRightData);
@@ -434,6 +453,9 @@ bool CreateWAVThread::splitLeftRightChannel()
         tmp = nullptr;
     }
 
+    // SPDLOG_LOGGER_DEBUG(m_logger, "{} 分离左右声道数据完成,左声道数据大小: {}, 右声道数据大小: {}", 
+    //     m_logBase, pLeftRightData->vecLeftData.size(), pLeftRightData->vecRightData.size());
+
     return true;
 }
 

BIN
ThreeLib/signalstats/Explosion.wav


BIN
ThreeLib/signalstats/WAV_0-0_20250717_215245.wav


+ 1 - 2
ThreeLib/signalstats/sample/demo.cpp

@@ -74,8 +74,7 @@ int main(int argc, char* argv[]) {
         auto segments = split_audio(channels[ch], sf_info.samplerate, segment_duration);
 
         // 检测每个分段
-        for (size_t i = 0; i < segments.size(); ++i) 
-        {
+        for (size_t i = 0; i < segments.size(); ++i) {
             json segment_result;
             json output;
             signalstats_wrapper::detect_signal_wrapper(

+ 61 - 0
show3/CMakeLists.txt

@@ -0,0 +1,61 @@
+cmake_minimum_required(VERSION 3.10)
+
+set(this_exe show3)
+
+
+
+#包含源文件
+file(GLOB LOCAL_SRC
+    ${CMAKE_CURRENT_SOURCE_DIR}/*.qrc
+    ${CMAKE_CURRENT_SOURCE_DIR}/*.rc
+    ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp
+    ${CMAKE_CURRENT_SOURCE_DIR}/*.ui
+
+    ${CMAKE_SOURCE_DIR}/External/module/ThreadPool/*.cpp
+)
+
+
+link_directories(${CMAKE_SOURCE_DIR}/ThreeLib/signalstats/lib)
+
+# 生成可执行程序
+
+add_executable(${this_exe}
+    # WIN32
+    ${GLOBAL_SRC}
+    ${LOCAL_SRC} 
+)
+
+# set_target_properties(${this_exe} PROPERTIES
+    
+# )
+
+
+#添加头文件
+target_include_directories(${this_exe} PRIVATE
+
+    ${CMAKE_CURRENT_SOURCE_DIR}
+
+    ${CMAKE_SOURCE_DIR}
+    ${CMAKE_SOURCE_DIR}/External/common
+    ${CMAKE_SOURCE_DIR}/External/module
+    ${CMAKE_SOURCE_DIR}/External/module/ThreadPool
+    ${CMAKE_SOURCE_DIR}/ThreeLib/signalstats/include
+    
+    ${spdlog_INCLUDE_DIR}
+)
+
+
+target_link_libraries(${this_exe} PRIVATE
+    Qt${QT_VERSION_MAJOR}::Widgets
+    Qt${QT_VERSION_MAJOR}::Core
+    Qt${QT_VERSION_MAJOR}::Network
+
+)
+# message(STATUS "可执行文件输出位置: ${EXECUTABLE_OUTPUT_PATH}")
+target_link_libraries(${this_exe} PRIVATE
+    ${spdlog_LIBRARY}
+    libsignalstats.so
+)
+
+
+

+ 191 - 0
show3/main.cpp

@@ -0,0 +1,191 @@
+#include <iostream>
+#include <vector>
+#include <random>
+#include <nlohmann/json.hpp>
+#include "signalstats_wrapper.h"
+#include "ThreadPool.h"
+
+
+void test1();
+void test2();
+
+int main() {
+    // 初始化Python解释器
+    signalstats_wrapper::initialize();
+    
+    // try {
+    //     // 创建测试音频信号 (C++版本)
+    //     const int sample_rate = 44100;
+    //     const int duration_seconds = 1;
+    //     const int num_samples = sample_rate * duration_seconds;
+        
+    //     std::vector<double> audio_signal(num_samples);
+    //     std::random_device rd;
+    //     std::mt19937 gen(rd());
+    //     std::normal_distribution<> dist(0.0, 1.0);
+        
+    //     for (auto& sample : audio_signal) {
+    //         sample = dist(gen);
+    //     }
+        
+    //     std::cout << "生成测试音频信号完成" << std::endl;
+        
+    //     // 调用C++接口函数
+    //     nlohmann::json output;
+    //     std::vector<std::string> window_params = {"tukey", "0.25"};
+        
+    //     nlohmann::json& result = signalstats_wrapper::detect_signal_wrapper(
+    //         output,
+    //         audio_signal,
+    //         sample_rate,
+    //         3e-3,  // silence_threshold
+    //         -70.0, // db_threshold
+    //         -70.0, // cv_threshold
+    //         window_params,
+    //         256,   // nperseg
+    //         32,    // noverlap
+    //         256,   // nfft
+    //         true  // debug
+    //     );
+        
+    //     // 处理输出结果
+    //     if (!output.empty()) {
+    //         std::cout << "信号检测完成,输出结果: " << output.dump(4) << std::endl;
+    //         // 这里可以添加具体的结果解析逻辑
+    //     } else {
+    //         std::cout << "信号检测完成,但无输出结果" << std::endl;
+    //     }
+        
+    //     std::cout << "程序执行完成" << std::endl;
+        
+    // } catch (const std::exception& e) {
+    //     std::cerr << "错误: " << e.what() << std::endl;
+    //     return 1;
+    // }
+    // test1();
+
+    CPPTP.add_task(test1);
+    // std::this_thread::sleep_for(std::chrono::seconds(1));
+    CPPTP.add_task(test2);
+    // std::this_thread::sleep_for(std::chrono::seconds(5));
+    
+    
+
+    std::this_thread::sleep_for(std::chrono::seconds(10)); // 等待任务执行
+
+    signalstats_wrapper::finalize();
+    
+    return 0;
+}
+
+void test1()
+{
+    // signalstats_wrapper::initialize();
+    try {
+        // 创建测试音频信号 (C++版本)
+        const int sample_rate = 44100;
+        const int duration_seconds = 1;
+        const int num_samples = sample_rate * duration_seconds;
+        
+        std::vector<double> audio_signal(num_samples);
+        std::random_device rd;
+        std::mt19937 gen(rd());
+        std::normal_distribution<> dist(0.0, 1.0);
+        
+        for (auto& sample : audio_signal) {
+            sample = dist(gen);
+        }
+        
+        std::cout << "生成测试音频信号完成" << std::endl;
+        
+        // 调用C++接口函数
+        nlohmann::json output;
+        std::vector<std::string> window_params = {"tukey", "0.25"};
+        
+        nlohmann::json& result = signalstats_wrapper::detect_signal_wrapper(
+            output,
+            audio_signal,
+            sample_rate,
+            3e-3,  // silence_threshold
+            -70.0, // db_threshold
+            -70.0, // cv_threshold
+            window_params,
+            256,   // nperseg
+            32,    // noverlap
+            256,   // nfft
+            true  // debug
+        );
+        
+        // 处理输出结果
+        if (!output.empty()) {
+            std::cout << "信号检测完成,输出结果: " << output.dump(4) << std::endl;
+            // 这里可以添加具体的结果解析逻辑
+        } else {
+            std::cout << "信号检测完成,但无输出结果" << std::endl;
+        }
+        
+        std::cout << "程序执行完成" << std::endl;
+        
+    } catch (const std::exception& e) {
+        std::cerr << "错误: " << e.what() << std::endl;
+        return;
+    }
+
+    // signalstats_wrapper::finalize();
+}
+
+void test2()
+{
+    // signalstats_wrapper::initialize();
+    try {
+        // 创建测试音频信号 (C++版本)
+        const int sample_rate = 44100;
+        const int duration_seconds = 1;
+        const int num_samples = sample_rate * duration_seconds;
+        
+        std::vector<double> audio_signal(num_samples);
+        std::random_device rd;
+        std::mt19937 gen(rd());
+        std::normal_distribution<> dist(0.0, 1.0);
+        
+        for (auto& sample : audio_signal) {
+            sample = dist(gen);
+        }
+        
+        std::cout << "生成测试音频信号完成" << std::endl;
+        
+        // 调用C++接口函数
+        nlohmann::json output;
+        std::vector<std::string> window_params = {"tukey", "0.25"};
+        
+        nlohmann::json& result = signalstats_wrapper::detect_signal_wrapper(
+            output,
+            audio_signal,
+            sample_rate,
+            3e-3,  // silence_threshold
+            -70.0, // db_threshold
+            -70.0, // cv_threshold
+            window_params,
+            256,   // nperseg
+            32,    // noverlap
+            256,   // nfft
+            true  // debug
+        );
+        
+        // 处理输出结果
+        if (!output.empty()) {
+            std::cout << "信号检测完成,输出结果: " << output.dump(4) << std::endl;
+            // 这里可以添加具体的结果解析逻辑
+        } else {
+            std::cout << "信号检测完成,但无输出结果" << std::endl;
+        }
+        
+        std::cout << "程序执行完成" << std::endl;
+        
+    } catch (const std::exception& e) {
+        std::cerr << "错误: " << e.what() << std::endl;
+        return;
+    }
+
+    // signalstats_wrapper::finalize();
+}