Python:语音处理,实现在线朗读RFC文档或本地文本文件


本文主要讲解如何使用python来实现将文本转为语音,以一个小例子为例,写了一下用pyTTS来朗读本地方件或在线朗读RFC文档,当然也可以修改一下,做成在线朗读新闻之类的,另本来想实现一个读中文小说的小程序,目前没有发现对中文支持得非常好的,且是免费的语音处理引擎,只能使用TTS实现一个英文的了,就当是用来练习听力了。

  1、准备:

       a. 下载pyTTS, http://sourceforge.net/projects/uncassist/files/pyTTS/pyTTS%203.0/

       b.  下载SpeechSDK51:下载

       c.  下载SpeechSDK51 patch,支持中文和日文,本例没有使用,下载

 2、实现:

  代码: [python]

  1. #!/usr/bin/env python   
  2. # -*- coding: utf-8 -*-   
  3.   
  4. #程序说明:此程序实现了通过TTS将文本内容读出来,提供了两种方式,一种是读本地文本文件,   
  5. #另一种方式为在线读RFC文档,要属入rfc编号,会将其内容逐行读出来打印到终端,其中音量   
  6. #大小,语速,朗读者可能过配置文件来设置,测试了下基本还算清楚,发现免费的TTS引擎对中文   
  7. #的支持均不是很好,所以本程序暂时没有处理对中文文件的阅读   
  8.   
  9. import pyTTS  
  10. import ConfigParser  
  11.   
  12. def read_local_file(tts):   
  13.     ''''' 
  14.     Function:朗读本地文件 
  15.     Input:TTS对象 
  16.     Output: NONE 
  17.     Author: socrates 
  18.     Blog:http://blog.csdn.net/dyx1024 
  19.     Date:2012-02-19 
  20.     '''    
  21.       
  22.     #输入要朗读的文本文件名   
  23.     file_name = raw_input("please input a text file name (for example: rfc4960.txt)").strip()  
  24.       
  25.     try:  
  26.         fobj = open(file_name,  'r')  
  27.     except IOError, err:  
  28.         print('file open error: {0}'.format(err))  
  29.         return   
  30.     else:  
  31.         #逐行输出并朗读的文本内容   
  32.         for eachLine in fobj:    
  33.             print(eachLine)  
  34.             tts.Speak(eachLine)   
  35.         fobj.close()  
  36.   
  37. def read_online_rfc(tts):    
  38.     ''''' 
  39.     Function:在线朗读RFC文档 
  40.     Input:TTS对象 
  41.     Output: NONE 
  42.     Author: socrates 
  43.     Blog:http://blog.csdn.net/dyx1024 
  44.     Date:2012-02-19 
  45.     '''        
  46.       
  47.     import urllib  
  48.       
  49.     #输入要朗读的RFC编号   
  50.     rfc_id = raw_input("please input a rfc number (for example: 4960):")  
  51.       
  52.     #打开RCF文档   
  53.     try:  
  54.         pager = urllib.urlopen("http://tools.ietf.org/rfc/rfc%s.txt" % rfc_id)  
  55.     except Exception, err:  
  56.         print("open url failed, ret = %s" % err.args[0])  
  57.         return  
  58.       
  59.     #逐行读取   
  60.     while True:  
  61.         if len(pager.readline()) == 0:  
  62.             break  
  63.         else:  
  64.             strtmp = pager.readline()   
  65.             print strtmp  
  66.             tts.Speak(strtmp)       
  67.           
  68. def Init_tts():  
  69.     ''''' 
  70.     Function:初始化TTS引擎 
  71.     Input:NONE 
  72.     Output: NONE 
  73.     Author: socrates 
  74.     Blog:http://blog.csdn.net/dyx1024 
  75.     Date:2012-02-19 
  76.     '''   
  77.          
  78.     tts_config = ConfigParser.ConfigParser()  
  79.       
  80.     #读取TTS相关配置文件   
  81.     try:  
  82.         tts_config.readfp(open('tts_config.ini'))  
  83.     except ConfigParser.Error:  
  84.         print 'read tts_config.ini failed.'  
  85.        
  86.     #创建TTS对象   
  87.     tts = pyTTS.Create()   
  88.       
  89.     #设置语速      
  90.     tts.Rate = int(tts_config.get("ttsinfo""TTS_READ_RATE"))  
  91.       
  92.     #设置音量   
  93.     tts.Volume = int(tts_config.get("ttsinfo""TTS_READ_VOLUME"))  
  94.       
  95.     #设置朗读者   
  96.     tts.SetVoiceByName(tts_config.get("ttsinfo""TTS_READ_READER"))         
  97.               
  98.     return tts  
  99.   
  100. def show_menu():  
  101.     ''''' 
  102.     Function:系统菜单 
  103.     Input:NONE 
  104.     Output: NONE 
  105.     Author: socrates 
  106.     Blog:http://blog.csdn.net/dyx1024 
  107.     Date:2012-02-19 
  108.     '''   
  109.           
  110.     prompt = ''''' 
  111.     l. read local file. 
  112.     2. read rfc online. 
  113.     3. exit 
  114.     please input your choice (1 or 2): 
  115.     '''  
  116.     command_name = {'1':read_local_file, '2':read_online_rfc}  
  117.       
  118.     while True:  
  119.           
  120.         while True:  
  121.               
  122.             try:  
  123.                 choice = raw_input(prompt).strip()[0]  
  124.             except (EOFError, KeyboardInterrupt, IndexError):  
  125.                 choice = '3'  
  126.           
  127.             if choice not in '123':  
  128.                 print 'error input, try again'  
  129.             else:  
  130.                 break  
  131.               
  132.         if choice == '3':  
  133.             break  
  134.         command_name[choice](Init_tts())  
  135.           
  136.                       
  137. if __name__ == '__main__':  
  138.     show_menu()  
  139.   
  140.       
  141.   
  142.   
  143.       

配置文件tts_config.ini:

[plain]

  1. [ttsinfo]  
  2. TTS_READ_RATE=-2 ;语速,默认为0,大于0表示快,小于0表示慢  
  3. TTS_READ_VOLUME=100 ;音量,0-100之间  
  4. TTS_READ_READER=MSMike ;朗读者,取值MSSam、MSMary、MSMike  

测试一:

[plain]

  1.     l. read local file.  
  2.     2. read rfc online.  
  3.     3. exit  
  4.     please input your choice (1 or 2):  
  5.     1  
  6. please input a text file name (for example: rfc4960.txt)english.txt  
  7. China says it condemns all acts of violence against innocent civilians  
  8.   
  9.   
  10.   
  11. BEIJING - China's negative vote on a draft resolution on Syria at the United Nations General Assembly on Thursday was consistent with China's independent foreign policy of peace and in the best interests of the Syrian situation, officials and experts said.   
  12.   
  13.   
  14.   
  15. China opposes armed intervention or forcing a so-called regime change in Syria, China's deputy permanent representative to the UN Wang Min said in explanatory remarks.  
  16.   
  17.   
  18.   
  19. "We condemn all acts of violence against innocent civilians and urge the government and all political factions of Syria to immediately and fully end all acts of violence, and quickly restore stability and the normal social order," Wang said.   
测试二:<>标记对中的内容仅打印,不朗读,各协议文档编号可从http://tools.ietf.org/rfc/中查询。

[plain]

  1.     l. read local file.  
  2.     2. read rfc online.  
  3.     3. exit  
  4.     please input your choice (1 or 2):  
  5.     2  
  6. please input a rfc number (for example: 4960):330  
  7. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  8.   
  9. <head>  
  10.   
  11.   <meta http-equiv="Content-Style-Type" content="text/css" />  
  12.   
  13.   <!-- JavaScript -->  
  14.   
  15.   <script language="javascript1.1" src="/js/updated.js" type="text/javascript"></script>  
  16.   
  17.   <link rel="icon" href="/ietf.ico" />  
  18.   
  19.   <title>IETF Tools</title>  
  20.   
  21.   <style type="text/css" >  
  22.   
  23.     /* HTML element styles */  
  24.   
  25.             background-color: white;      
  26.   
  27.             padding: 0;  
  28.   
  29.     }  
  30.   
  31.             font-family: "Times New Roman", times, serif;  
  32.   
  33.             margin: 0;  
  34.   
  35.           
  36.   
  37.     h1      { font-size: 150%; }  
  38.   
  39.     h4      { margin: 0.45em 0 0 0; }  
  40.   
  41.     .menu form  { margin: 0; }  
  42.   
  43.     input.frugal,textarea.frugal {  
  44.   
  45.         border-left: groove 2px #ccc;  

相关内容