audio_debugger.cc 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #include "audio_debugger.h"
  2. #include "sdkconfig.h"
  3. #if CONFIG_USE_AUDIO_DEBUGGER
  4. #include <esp_log.h>
  5. #include <arpa/inet.h>
  6. #include <unistd.h>
  7. #include <errno.h>
  8. #include <cstring>
  9. #include <string>
  10. #endif
  11. #define TAG "AudioDebugger"
  12. AudioDebugger::AudioDebugger() {
  13. #if CONFIG_USE_AUDIO_DEBUGGER
  14. udp_sockfd_ = socket(AF_INET, SOCK_DGRAM, 0);
  15. if (udp_sockfd_ >= 0) {
  16. // 解析配置的服务器地址 "IP:PORT"
  17. std::string server_addr = CONFIG_AUDIO_DEBUG_UDP_SERVER;
  18. size_t colon_pos = server_addr.find(':');
  19. if (colon_pos != std::string::npos) {
  20. std::string ip = server_addr.substr(0, colon_pos);
  21. int port = std::stoi(server_addr.substr(colon_pos + 1));
  22. memset(&udp_server_addr_, 0, sizeof(udp_server_addr_));
  23. udp_server_addr_.sin_family = AF_INET;
  24. udp_server_addr_.sin_port = htons(port);
  25. inet_pton(AF_INET, ip.c_str(), &udp_server_addr_.sin_addr);
  26. ESP_LOGI(TAG, "Initialized server address: %s", CONFIG_AUDIO_DEBUG_UDP_SERVER);
  27. } else {
  28. ESP_LOGW(TAG, "Invalid server address: %s, should be IP:PORT", CONFIG_AUDIO_DEBUG_UDP_SERVER);
  29. close(udp_sockfd_);
  30. udp_sockfd_ = -1;
  31. }
  32. } else {
  33. ESP_LOGW(TAG, "Failed to create UDP socket: %d", errno);
  34. }
  35. #endif
  36. }
  37. AudioDebugger::~AudioDebugger() {
  38. #if CONFIG_USE_AUDIO_DEBUGGER
  39. if (udp_sockfd_ >= 0) {
  40. close(udp_sockfd_);
  41. ESP_LOGI(TAG, "Closed UDP socket");
  42. }
  43. #endif
  44. }
  45. void AudioDebugger::Feed(const std::vector<int16_t>& data) {
  46. #if CONFIG_USE_AUDIO_DEBUGGER
  47. if (udp_sockfd_ >= 0) {
  48. ssize_t sent = sendto(udp_sockfd_, data.data(), data.size() * sizeof(int16_t), 0,
  49. (struct sockaddr*)&udp_server_addr_, sizeof(udp_server_addr_));
  50. if (sent < 0) {
  51. ESP_LOGW(TAG, "Failed to send audio data to %s: %d", CONFIG_AUDIO_DEBUG_UDP_SERVER, errno);
  52. } else {
  53. ESP_LOGD(TAG, "Sent %d bytes audio data to %s", sent, CONFIG_AUDIO_DEBUG_UDP_SERVER);
  54. }
  55. }
  56. #endif
  57. }