C++和python代码实现朗读文本的功能(附源代码)

2023-05-16

闲来无事,平时就喜欢看看小说之类的。突发奇想,好多小说软件上的听小说功能都是收费的,咱们写个小程序读一读,岂不是很哇塞!
看了一些资料,这里给大家分享出来,已经测试可以用。

C++代码和python代码实现对文本的朗读功能,代码比较简单,仅供参考。

主要是采用的接口是Microsoft Speech SDK。
Win7以上的系统不需要再次安装,首先包含头文件和库文件:

#include "sapi.h"	// 语音头文件
#include "sphelper.h"	// 语音识别头文件
#pragma comment(lib, "sapi.lib")

程序运行有可能报错,按以下流程处理即可。

error C4996: ‘GetVersionExW’: 被声明为已否决

在这里插入图片描述
右键工程属性,设置C++ ----- 常规 ----- SDL检查 为 “ 否 ”。
在这里插入图片描述

C++实例代码:
代码中没有写文本读取的操作,需要的可以自己改改,比较简单。

void CfvoiceDlg::OnBnClickedVoice()
{
	// TODO: 在此添加控件通知处理程序代码
	ISpVoice *pfvoice = NULL;
	if (FAILED(CoInitialize(NULL)))
	{
		return;
	}
	// 初始化
	HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void**)&pfvoice);
	ISpObjectToken * pSpObjToken = NULL;
	if (SUCCEEDED(SpFindBestToken(SPCAT_VOICES, _T("language=804"), NULL, &pSpObjToken)))	// 804 代表中文
	{
		pfvoice->SetVoice(pSpObjToken);	// 设置声音大小
		pfvoice->SetRate(-2);			// 设置语速
		pSpObjToken->Release();
	}
	else
	{
		return;
	}
	if (SUCCEEDED(hr))
	{
		CString csText = _T("播放语音测试文本");
		hr = pfvoice->Speak(csText.AllocSysString(), 0, NULL);
		pfvoice->Release();
		pfvoice = NULL;
	}
	CoUninitialize();
}

python代码运行用到的包,需要安装,可以按错误提示进行下载安装。
如果遇到安装问题,可以看看python学习之word文档转换成pdf文档

pip install pywin32
pip install pypiwin32
pip install --user pypdf2

python代码实例:

import winsound
import win32com
from win32com.client import Dispatch, constants
import random
import time
speak_out = win32com.client.Dispatch('sapi.spvoice')
lang={}


def view():                                    # 按字典顺序输出方言
    for key,value in lang.items():
        print(key,":",value)                   # 按字典顺序显示方言   
        speak(key+"     "+value)               # 按字典顺序语音播放方言
        time.sleep(1)                          # 循环间隔时间为1秒钟
def speak(str):                                # 按播放语音
    speak_out.speak(str)                       # 输出方言解释
    winsound.PlaySound(str,winsound.SND_ASYNC)   # 输出结束音
with open("note.txt","r",encoding='UTF-8') as file: # 读取文件中的方言给字典
    while True:
       line = file.readline()
       if line =='':            
           break
       group=line.split(":")           # 按“:”分割字符串
       lang[group[0]]=group[1] 
print("    东北方言\n")
print("说明:输入“q”退出系统;输入“s”按顺序输出并朗读词典内容。")
while True:
    word=input("请输入要查找的东北方言:").strip()
    if word.lower()=="q":
        break
    if word.lower()=="s":
        view()
    else:
        note=lang.get(word,"no")
        if note!="no":
            print(word,":",note)
            speak(word+":    "+note)
        else:
            print("没有检索到相关东北方言!")

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++和python代码实现朗读文本的功能(附源代码) 的相关文章

随机推荐