ESP32蓝牙连扬声器触发提醒报错:is_connected()未声明
ESP32 A2DP蓝牙连接状态检测问题解决
初学者求助:
我想要实现ESP32蓝牙连接到扬声器时触发提醒。在loop中尝试相关代码时,出现“is_connected()未声明”的错误。
我已关联BluetoothA2DPSource.h和cpp文件,在其中找到了以下相关内容,但不确定如何使用。
virtual bool is_connected(); // 在BluetoothA2DPSource.h文件中找到
bool BluetoothA2DPSource::is_connected(){ // 在BluetoothA2DPSource.cpp文件中找到
return s_a2d_state == APP_AV_STATE_CONNECTED;}
你遇到的问题核心是:is_connected()是BluetoothA2DPSource类的成员函数,不是全局函数,不能直接在loop里调用,必须通过你代码中已经创建的BluetoothA2DPSource实例(也就是a2dp对象)来访问。
修正方案
修改loop中的代码,通过实例调用成员函数,同时可以补充断开连接时的逻辑:
void loop() { // 通过a2dp实例调用is_connected()获取连接状态 if (a2dp.is_connected()) { digitalWrite(led, HIGH); // 连接时点亮LED提醒 } else { digitalWrite(led, LOW); // 断开时熄灭LED } player.copy(); }
关键说明
- 类的非静态成员函数必须通过类的对象实例调用,格式为
实例名.成员函数() - 你代码中已经声明了
BluetoothA2DPSource a2dp;,直接用这个对象调用is_connected()就能正确获取蓝牙连接状态
修改后的完整代码
/** @file base-player-a2dp.ino @author Phil Schatzmann @brief Sketch which uses the A2DP callback to provide data from the AudioPlayer via a Queue @version 0.1 @date 2022-12-04 @copyright Copyright (c) 2022 */ #include "AudioTools.h" #include "AudioLibs/AudioA2DP.h" #include "AudioLibs/AudioSourceSDFAT.h" #include "AudioCodecs/CodecMP3Helix.h" #include "AudioLibs/AudioKit.h" const int led = 5; int buffer_count = 30; int buffer_size = 512; const char *startFilePath = "/"; const char* ext = "mp3"; AudioSourceSDFAT source(startFilePath, ext, PIN_AUDIO_KIT_SD_CARD_CS); MP3DecoderHelix decoder; //Setup of synchronized buffer SynchronizedNBuffer<uint8_t> buffer(buffer_size, buffer_count, portMAX_DELAY, 10); QueueStream<uint8_t> out(buffer); // convert Buffer to Stream AudioPlayer player(source, out, decoder); BluetoothA2DPSource a2dp; // Provide data to A2DP int32_t get_data(uint8_t *data, int32_t bytes) { size_t result_bytes = buffer.readArray(data, bytes); //LOGI("get_data_channels %d -> %d of (%d)", bytes, result_bytes , buffer.available()); return result_bytes; } void setup() { Serial.begin(115200); AudioLogger::instance().begin(Serial, AudioLogger::Warning); pinMode(led, OUTPUT); // sd_active is setting up SPI with the right SD pins by calling SPI.begin(PIN_AUDIO_KIT_SD_CARD_CLK, PIN_AUDIO_KIT_SD_CARD_MISO, PIN_AUDIO_KIT_SD_CARD_MOSI, PIN_AUDIO_KIT_SD_CARD_CS); // start QueueStream out.begin(); // setup player player.setDelayIfOutputFull(0); player.setVolume(0.6); player.begin(); // fill buffer with some data player.getStreamCopy().copyN(5); // start a2dp source Serial.println("starting A2DP..."); a2dp.start_raw("HW2-915", get_data); Serial.println("Started!"); } void loop() { // 修正:通过a2dp实例调用成员函数is_connected() if (a2dp.is_connected()) { digitalWrite(led, HIGH); } else { digitalWrite(led, LOW); } player.copy(); }
内容的提问来源于stack exchange,提问作者dinghy
相关产品推荐
相关产品推荐

