Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // bcigui_cspeechclient
- @echo off
- echo "bcigui cspeechclient called"
- "C:\Python27\python.exe" "CereVoiceClient\examples\python\speakTTS.py" -n %1
- // speakTTS.bat CerevoiceClient\examples\python
- c:\Python27\python.exe C:\Experiments\Z020\CereVoiceClient\examples\python\speakTTS.py %1 %2
- // speakTTS.py
- #coding: utf-8
- #-------------------------------------------------------------------------------
- # Name: speakTTS
- # Purpose: Without argument(s) --new or --last it creates a socket connection to the appropreate BCIApplication and waits for text from there and speaks it.
- # With arg -n (--new) or -l (--last) it uses the Cereproc cServer to create the new sound and then plays it.
- # call speakTTS -h to show all options
- # Cereproc cServer must be installed and running
- #
- # Author: battes
- #
- # Created: 22.07.2015
- # last edit: 08.04.16
- # - removed overhead for usage with BCI GUI, further cleaning up is needed
- # Copyright: (c) battes 2015
- # Licence: <your licence>
- #-------------------------------------------------------------------------------
- import sys
- import os
- import string
- import pygame
- import time
- import socket
- import select
- maxBackup = 200 # Maximum number of entries for backup list of spoken text
- def setupenv():
- thirdpartydir = os.path.join(os.path.split(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])[0], "3rdparty", "lib")
- cspeechdir = os.path.join(os.path.split(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])[0], "cSpeech", "lib")
- os.environ['PATH'] = os.environ['PATH'] + os.pathsep + thirdpartydir + os.pathsep + cspeechdir
- sys.path.append(os.path.join(os.path.split(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])[0], "cSpeech", "pylib"))
- def readSocket(serversocket, timeout):
- ret = 'None'
- try:
- readable, writable, errored = select.select([serversocket], [], [],timeout) # timeout prevents blocking through accept()
- except:
- return ret
- for s in readable:
- if s is serversocket:
- clientsocket, address = serversocket.accept() # blocked: waiting for input
- print "Connection from", address
- ret = clientsocket.recv(1024)
- print 'ret', ret
- if ret:
- pass
- else:
- s.close()
- return ret
- def writeFile(infile, text):
- global args
- f1 = open(infile,'w')
- f1.write(text)
- f1.close()
- # backup text list
- # write new line on top of file
- inpath, file = os.path.split(infile)
- try:
- with open(inpath +'/TTS_Backup.Txt', 'r+') as f1:
- content = f1.read()
- if text in content:
- content = content.replace(text.rstrip('\r\n') + '\n', '')
- cont = content.split('\n')
- if len(cont) > maxBackup:
- f1.close()
- with open(inpath +'/TTS_Backup.Txt', 'w') as f2:
- content = content.replace('\n'+cont[-1], '')
- f2.write(text.rstrip('\r\n') + '\n' + content)
- else:
- f1.seek(0, 0)
- f1.write(text.rstrip('\r\n') + '\n' + content)
- except IOError:
- # very first line
- with open(inpath +'/TTS_Backup.Txt', 'w') as f1:
- f1.write(text.rstrip('\r\n'))
- def createNewSound(args, newText):
- global CereSpeechclient
- writeFile(args.infile, newText)
- res = CereSpeechclient.run_client(args.host, int(args.port), args.outdir, args.voice, args.textmode, args.asynch, args.stream, args.headinfo, args.verbose, [args.infile])
- def speakLatest(soundfile):
- f = open(soundfile, 'rb')
- data = f.read()
- sound = pygame.mixer.Sound(data)
- plays = sound.play()
- while plays.get_busy(): # needed when speakTTS is startet from terminal
- pygame.time.delay(100) # otherwise prog returns immediately after start - no sound!
- def speak(args, newText):
- print 'text to speak:', newText
- print args.infile
- inpath, infile = os.path.split(args.infile)
- soundFile, ext = os.path.splitext(infile)
- soundFile += '.raw'
- try:
- port = int(args.port)
- except ValueError:
- parser.error("Port number has to be an integer")
- if newText == 'latest':
- speakLatest(args.outdir +soundFile)
- else:
- createNewSound(args, newText)
- speakLatest(args.outdir +soundFile)
- def main():
- global root, args, CereSpeechclient
- from optparse import OptionParser
- import argparse
- print "using speakTTS.py"
- setupenv()
- import CereSpeechclient
- pygame.mixer.quit()
- pygame.mixer.init(frequency=22050, size=16, channels=1)
- repRate = 1 # 0.5 # in Sec
- # Setup option parsing
- usage="usage: %prog [options] infiles\n"
- parser = argparse.ArgumentParser(description='This is to call Text To Speech')
- # Options
- parser.add_argument("-n", "--new", nargs='*', dest="newtext", default=[" ","", " "], help="new text to speak (write into input file)")
- parser.add_argument("-H", "--host", dest="host", default="localhost", help="Host name (default: localhost)")
- parser.add_argument("-p", "--port", dest="port", default="8989", help="Port number (default: 8989)")
- parser.add_argument("-i", "--infile", dest="infile", default="../../../TTS.txt", help="Input file including directory")
- parser.add_argument("-o", "--outdir", dest="outdir", default="../../../", help="Output directory")
- parser.add_argument("-V", "--voice", dest="voice", default=None, help="(Case-sensitive) Voice name (Gudrun or Alex)")
- parser.add_argument("-t", "--textmode", dest="textmode", action = "store_true", default=True, help="Flag: input files contain text")
- parser.add_argument("-a", "--asynch", dest="asynch", action = "store_true", default=False, help="Flag: use asynchronous socket")
- parser.add_argument("-s", "--stream", dest="stream", action = "store_true", default=False, help="Flag: stream the data")
- parser.add_argument("-hd", "--headinfo", dest="headinfo", action = "store_true", default=False, help="Flag: print voice header information")
- parser.add_argument("-v", "--verbose", dest="verbose", action = "store_true", default=False, help="Flag: print callback info messages")
- parser.add_argument("-l", "--last", dest="last", action = "store_true", default=False, help="Flag: speak last text")
- args = parser.parse_args()
- print args
- newText = string.join(args.newtext).strip()
- fs_encoding = sys.getfilesystemencoding()
- newText = newText.decode(fs_encoding)
- newText = newText.encode("utf-8")
- if args.last:
- newText = 'latest'
- if newText.strip() != '':
- speak(args, newText)
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement