#include <freertos/stream_buffer.h>
StreamBufferHandle_t xStreamMusic = NULL;//创建一个Stream Buffer 的 handler
void downloadTask(void *pvParam)
{
String music;
size_t xBytesSent;//The number of tytes written to the stream buffer.
while (1) {
//模拟从网路上下载音乐,放一些随机的延迟
for (int i = 0; i < random(20, 40); i++) vTaskDelay(1);
music = randomMusic();//随机生成一些数据
xBytesSent = xStreamBufferSend(xStreamMusic,
(void *)&music,
sizeof(music),
portMAX_DELAY);
if (xBytesSent != sizeof(music)) {
Serial.println("警告:xStreamBufferSend 写入数据出错");//Optional
}
vTaskDelay(100);
}
}
void playBackTask(void *pvParam)
{
size_t xReceivedBytes;//The number of bytes read from the stream buffer.
size_t xReadBytes = 8 * 10 - 1;
String music;
while (1) {
xReceivedBytes = xStreamBufferReceive(xStreamMusic,
(void *)&music,
xReadBytes,
portMAX_DELAY);
if (xReceivedBytes > 0) {
decode(music);
}
}
}
void monitorTask (void *pvParam)
{
size_t xAvailable, xUsed;
bool isFull;
while (1) {
//Queries a stream buffer to see if it is full.
if (xStreamBufferIsFull(xStreamMusic) == pdTRUE)
Serial.println("xStreamMusic is full");
//Queries a stream buffer to see how much free space it contains
xAvailable = xStreamBufferSpacesAvailable(xStreamMusic);
char msg[40];
sprintf(msg,"xStreamBuffer已使用 %d 字节",xUsed);
Serial.println(msg);
sprintf(msg,"xStreamBuffer可用空间为 %d 字节",xAvailable);
Serial.println(msg);
vTaskDelay(2000);
}
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
//
const size_t xStreamBufferSizeBytes = 540;
//
const size_t xTriggerLevel = 8;
xStreamMusic = xStreamBufferCreate(xStreamBufferSizeBytes,xTriggerLevel);
if(xStreamMusic == NULL){
Serial.println("UNABLE TO CREATE STREAM BUFFER");
}else{
xTaskCreate(downloadTask,"Download Music",1024*8,NULL,1,NULL);//下载音乐
xTaskCreate(playBackTask,"Playback Music",1024*8,NULL,1,NULL);//解码播放音乐
xTaskCreate(monitorTask,"Monitor Stream Buffer",1024*8,NULL,1,NULL);//对Stream Buffer进行监控
}
vTaskDelete(NULL);//setup 和loop 这个loopback 任务没用了,自宫了
}
void loop() {
// put your main code here, to run repeatedly:
delay(10); // this speeds up the simulation
}