ROS学习笔记-ROS语音识别与语音输出-语音交互[3]

说明:代码部分是基于古月居前辈的例程,在此对胡老师表示感谢!!

语音交互功能框图:
在这里插入图片描述

/* main thread: start/stop record ; query the result of recgonization.
 * record thread: record callback(data write)
 * helper thread: ui(keystroke detection)
 */
int main(int argc, char* argv[])
{
    // 初始化ROS
    ros::init(argc, argv, "voiceRecognition");
    ros::NodeHandle n;
    ros::Rate loop_rate(10);

    // 声明Publisher和Subscriber
    // 订阅唤醒语音识别的信号
    ros::Subscriber wakeUpSub = n.subscribe("voiceWakeup", 1000, WakeUp);   
    // 订阅唤醒语音识别的信号    
    ros::Publisher voiceWordsPub = n.advertise<std_msgs::String>("voiceWords", 1000);  

    ROS_INFO("Sleeping...");
    int count=0;

    int ret = MSP_SUCCESS;
    /* login params, please do keep the appid correct */
    const char* login_params = "appid = 594a7b46, work_dir = .";
    int aud_src = 0; /* from mic or file */

    /*
    * See "iFlytek MSC Reference Manual"
    */
    const char* session_begin_params =
        "sub = iat, domain = iat, language = zh_cn, "
        "accent = mandarin, sample_rate = 16000, "
        "result_type = plain, result_encoding = utf8";

    /* Login first. the 1st arg is username, the 2nd arg is password
     * just set them as NULL. the 3rd arg is login paramertes 
     * */
    ret = MSPLogin(NULL, NULL, login_params);
    if (MSP_SUCCESS != ret)	{
        printf("MSPLogin failed , Error code %d.\n",ret);
        goto exit; // login fail, exit the program
    }

    while(ros::ok())
    {
        // 语音识别唤醒     
        if(wakeupFlag)
        {
            ROS_INFO("Wakeup...");

	        printf("Demo recognizing the speech from microphone\n");
	        printf("Speak in 8 seconds\n");

	        demo_mic(session_begin_params);

	        printf("8 sec passed\n");
            
            wakeupFlag=0;
        }

        // 语音识别完成
        if(resultFlag){
            resultFlag=0;
            std_msgs::String msg;
            msg.data = g_result;
            voiceWordsPub.publish(msg);
        }

        ros::spinOnce();
        loop_rate.sleep();
        count++;
    }
exit:
	MSPLogout(); // Logout...

	return 0;
}

WakeUp()函数:

void WakeUp(const std_msgs::String::ConstPtr& msg)
{
    printf("waking up\r\n");
    usleep(700*1000);
    wakeupFlag=1;
}

demo_mic()函数:

/* demo recognize the audio from microphone */
static void demo_mic(const char* session_begin_params)
{
	int errcode;
	int i = 0;

	struct speech_rec iat;

	struct speech_rec_notifier recnotifier = {
		on_result,
		on_speech_begin,
		on_speech_end
	};

	errcode = sr_init(&iat, session_begin_params, SR_MIC, &recnotifier);
	if (errcode) {
		printf("speech recognizer init failed\n");
		return;
	}
	errcode = sr_start_listening(&iat);
	if (errcode) {
		printf("start listen failed %d\n", errcode);
	}
	/* demo 8 seconds recording */
	while(i++ < 8)
		sleep(1);
	errcode = sr_stop_listening(&iat);
	if (errcode) {
		printf("stop listening failed %d\n", errcode);
	}

	sr_uninit(&iat);
}

demo_file()函数:

/* demo send audio data from a file */
static void demo_file(const char* audio_file, const char* session_begin_params)
{
	int	errcode = 0;
	FILE*	f_pcm = NULL;
	char*	p_pcm = NULL;
	unsigned long	pcm_count = 0;
	unsigned long	pcm_size = 0;
	unsigned long	read_size = 0;
	struct speech_rec iat;
	struct speech_rec_notifier recnotifier = {
		on_result,
		on_speech_begin,
		on_speech_end
	};

	if (NULL == audio_file)
		goto iat_exit;

	f_pcm = fopen(audio_file, "rb");
	if (NULL == f_pcm)
	{
		printf("\nopen [%s] failed! \n", audio_file);
		goto iat_exit;
	}

	fseek(f_pcm, 0, SEEK_END);
	pcm_size = ftell(f_pcm);
	fseek(f_pcm, 0, SEEK_SET);

	p_pcm = (char *)malloc(pcm_size);
	if (NULL == p_pcm)
	{
		printf("\nout of memory! \n");
		goto iat_exit;
	}

	read_size = fread((void *)p_pcm, 1, pcm_size, f_pcm);
	if (read_size != pcm_size)
	{
		printf("\nread [%s] error!\n", audio_file);
		goto iat_exit;
	}

	errcode = sr_init(&iat, session_begin_params, SR_USER, &recnotifier);
	if (errcode) {
		printf("speech recognizer init failed : %d\n", errcode);
		goto iat_exit;
	}

	errcode = sr_start_listening(&iat);
	if (errcode) {
		printf("\nsr_start_listening failed! error code:%d\n", errcode);
		goto iat_exit;
	}

	while (1)
	{
		unsigned int len = 10 * FRAME_LEN; /* 200ms audio */
		int ret = 0;

		if (pcm_size < 2 * len)
			len = pcm_size;
		if (len <= 0)
			break;

		ret = sr_write_audio_data(&iat, &p_pcm[pcm_count], len);

		if (0 != ret)
		{
			printf("\nwrite audio data failed! error code:%d\n", ret);
			goto iat_exit;
		}

		pcm_count += (long)len;
		pcm_size -= (long)len;		
	}

	errcode = sr_stop_listening(&iat);
	if (errcode) {
		printf("\nsr_stop_listening failed! error code:%d \n", errcode);
		goto iat_exit;
	}

iat_exit:
	if (NULL != f_pcm)
	{
		fclose(f_pcm);
		f_pcm = NULL;
	}
	if (NULL != p_pcm)
	{
		free(p_pcm);
		p_pcm = NULL;
	}

	sr_stop_listening(&iat);
	sr_uninit(&iat);
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
【资源说明】 基于ros语音识别源码(采用python与科大讯飞语音听写api)+项目使用说明.zip 基于ros语音识别使用python与科大讯飞语音听写api实现实时的语音识别,并利用节点发布话题控制进程。 环境要求: * ros1,python3.x * 声卡:```sudo apt install libasound2-dev``` * requirement: * pass 项目结构: ``` XF_PYROS_IAT │ .gitattributes │ CMakeLists.txt │ package.xml │ README.md │ ├─launch │ main_node.launch │ ├─others │ node.png │ node_main.png │ ├─scripts │ close_switch_node.py │ main_node.py │ open_switch_node.py │ reset_node.py │ └─src func_open_node.cpp func_pause_node.cpp func_reset_node.cpp ``` 节点说明: ![节点图](others/node.png "节点图") * `main_node.py`是主程序,承担语音识别模块,对应节点为:/main_node,只运行该节点不会直接开始语音识别 * `open_switch_node.py`用于开启主程序语音识别,对应节点为:/open_node * `close_switch_node.py`用于关闭主程序语音识别,对应节点为:/pause_node * `reset_node.py`用于重置整个进程,使其恢复到休眠状态,对应节点为:/reset_node,运行一次该节点后就可以通过open_switch_node.py或/open_node再次开启语音识别 * src中的cpp生成的节点实际上就是用于控制以上节点,可有可无,根据自己需求使用,对应关系如下:(主要由于本人不会c++,故才加了src中的三个节点,如果你会C++可以自己把以上其他节点改写为C++) * _`func_open_node.cpp` --> `open_switch_node.py` 、`func_pause_node.cpp` --> `close_switch_node.py` 、`func_reset_node.cpp` --> `reset_node.py`_ 使用步骤: ***注意:请提前修改 main_node.py 中的科大讯飞APPID,APIKey,APISecret!*** 终端一: ``` roslaunch xf_pyros_iat main_node.launch ``` 终端二: * 发布话题:/func_switch_op启动语音识别,data: ' '里可以是任何字符串,没有也行 ``` rostopic pub /func_switch_op std_msgs/String "data: ''" ``` * 发布话题:/func_switch_cl关闭语音识别,data: ' '里可以是任何字符串,没有也行 ``` rostopic pub /func_switch_cl std_msgs/String "data: ''" ``` * 发布话题:/func_switch_re重置语音识别,data: ' '里可以是任何字符串,没有也行 ``` rostopic pub /func_switch_re std_msgs/String "data: ''" ``` * 此外通过:/func_op_node、/func_cl_node、/func_re_node三个节点也可以控制开、关、重置语音识别,命令如下: ``` rosrun xf_pyros_iat func_op_node ``` ``` rosrun xf_pyros_iat 【备注】 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载使用,也适合小白学习进阶,当然也可作为毕设项目、课程设计、作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可直接用于毕设、课设、作业等。 欢迎下载,沟通交流,互相学习,共同进步!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值