2025-05-10 16:03:55 +08:00
|
|
|
#include <rtthread.h>
|
|
|
|
#include <finsh.h>
|
|
|
|
#include "common.h"
|
|
|
|
#include "param_config.h"
|
|
|
|
#include "ble_pub.h"
|
|
|
|
#include "drv_oled.h"
|
|
|
|
#include <rtdevice.h>
|
|
|
|
#include "app_temperature.h"
|
|
|
|
#ifdef PKG_USING_EASYFLASH
|
|
|
|
#include "easyflash.h"
|
|
|
|
#endif
|
|
|
|
#include "audio_device.h"
|
|
|
|
#include "app_voice_player.h"
|
|
|
|
#include "opus.h"
|
|
|
|
#include "opus_encoder.h"
|
|
|
|
#include "audio_device.h"
|
|
|
|
// 设置常量
|
|
|
|
#define SAMPLE_RATE 16000
|
|
|
|
#define CHANNELS 1
|
|
|
|
#define FRAME_SIZE 960 // 20ms的帧大小
|
|
|
|
#define MAX_PACKET_SIZE 4000 // 最大的OPUS数据包大小
|
|
|
|
|
|
|
|
// PCM缓冲区
|
|
|
|
int16_t pcm_buffer[2048];
|
|
|
|
uint8_t encoded_data[MAX_PACKET_SIZE]; // 用于存储编码后的OPUS数据
|
|
|
|
|
|
|
|
OpusEncoder *encoder = NULL;
|
|
|
|
|
|
|
|
//static const char *TAG = "PCM_to_Opus";
|
|
|
|
|
|
|
|
// 初始化Opus编码器
|
|
|
|
int initialize_opus_encoder() {
|
|
|
|
int error;
|
|
|
|
encoder = opus_encoder_create(SAMPLE_RATE, CHANNELS, OPUS_APPLICATION_AUDIO, &error);
|
|
|
|
if (error != OPUS_OK) {
|
|
|
|
rt_kprintf( "opus_encoder_create fail: %s", opus_strerror(error));
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
// 编码PCM到Opus
|
|
|
|
int encode_pcm_to_opus(int16_t *pcm_data, uint8_t *opus_data, int frame_size) {
|
|
|
|
int encoded_size = opus_encode(encoder, pcm_data, frame_size, opus_data, MAX_PACKET_SIZE);
|
|
|
|
if (encoded_size < 0) {
|
|
|
|
rt_kprintf( "opus_encode fail: %s", opus_strerror(encoded_size));
|
|
|
|
return encoded_size;
|
|
|
|
}
|
|
|
|
return encoded_size;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* 播放一个文件*/
|
|
|
|
void opus_work(void *p)
|
|
|
|
{
|
|
|
|
audio_device_init();
|
|
|
|
audio_device_mic_open();
|
|
|
|
audio_device_mic_set_channel(1);
|
|
|
|
audio_device_mic_set_rate(16000);
|
|
|
|
while(1){
|
|
|
|
|
|
|
|
rt_memset(pcm_buffer , 0, FRAME_SIZE);
|
|
|
|
/* read data from sound device */
|
|
|
|
int read_bytes=audio_device_mic_read(pcm_buffer, FRAME_SIZE);
|
|
|
|
rt_kprintf("read_bytes:%d\r\n",read_bytes);
|
|
|
|
|
|
|
|
// PCM数据编码成Opus
|
|
|
|
int ret = encode_pcm_to_opus(pcm_buffer, encoded_data, FRAME_SIZE/2);
|
|
|
|
// 将编码后的OPUS数据写入文件
|
|
|
|
//fwrite(encoded_data, sizeof(uint8_t), MAX_PACKET_SIZE, opus_file);
|
|
|
|
rt_kprintf( "encode_pcm_to_opus : %d", ret);
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void opous_encoder_start(){
|
|
|
|
rt_thread_t thread = RT_NULL;
|
|
|
|
thread = rt_thread_create("opus_work", opus_work, RT_NULL, 1024 *8, 10, 5);
|
|
|
|
if(thread != RT_NULL)
|
|
|
|
{
|
|
|
|
rt_thread_startup(thread);
|
|
|
|
}
|
2025-04-26 23:37:31 +08:00
|
|
|
}
|