python类gTTS()的实例源码

utils.py 文件源码 项目:MOSFiT 作者: guillochon 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def speak(text, lang='es'):
    """Text to speech. For funp."""
    try:
        from googletrans import Translator
        from gtts import gTTS
        from pygame import mixer
        from tempfile import TemporaryFile

        translator = Translator()
        tts = gTTS(text=translator.translate(text, dest=lang).text, lang=lang)
        mixer.init()

        sf = TemporaryFile()
        tts.write_to_fp(sf)
        sf.seek(0)
        mixer.music.load(sf)
        mixer.music.play()
    except Exception:
        raise
sayer.py 文件源码 项目:sketal 作者: vk-brain 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def __init__(self, *commands, key=None, use_yandex=True, prefixes=None, strict=False):
        """Answers with audio message of user's text"""

        if not commands:
            commands = ["?????", "?????????"]

        super().__init__(*commands, prefixes=prefixes, strict=strict)

        if not key:
            self.key = "e02d4514-b2a7-4edb-8ee8-825f854ef890"
        else:
            self.key = key

        self.providers = [(lambda text, lang, key=None: gTTS(text=text, lang=lang)),
                          (lambda text, lang, key=None: yTTS(text=text, lang=lang, key=key)),]

        if use_yandex:
            self.providers[0], self.providers[1] = self.providers[1], self.providers[0]

        example = self.command_example()
        self.description = [f"????? ? ????",
                            f"{example} [????] - ?????????? ????? (+ ?????? ???????? ????? ??????? ???????)."]
computer.py 文件源码 项目:raspberrypi_AI-NO-GUI 作者: Comm4nd0 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def speak(say):
    endProg(command='music')
    print("GENERATING VOICE")
    tts = gTTS(text=say, lang='en')
    tts.save("voice/temp/temp.mp3")
    voice = "runuser -l pi -c 'cvlc --play-and-exit /home/pi/computer/voice/temp/temp.mp3' "
    subprocess.call(voice, shell=True)
    endProg(command="exit")
    return
google.py 文件源码 项目:j2f 作者: jasper2fork 项目源码 文件源码 阅读 41 收藏 0 点赞 0 评论 0
def __init__(self, *args, **kwargs):
        plugin.TTSPlugin.__init__(self, *args, **kwargs)
        try:
            orig_language = self.profile['language']
        except:
            orig_language = 'en-US'

        language = orig_language.lower()

        if language not in gtts.gTTS.LANGUAGES:
            language = language.split('-')[0]

        if language not in gtts.gTTS.LANGUAGES:
            raise ValueError("Language '%s' ('%s') not supported" %
                             (language, orig_language))

        self.language = language
run.py 文件源码 项目:SpeechRecognition-awesomewm 作者: getzneet 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def play_answer(self, action, software=None, text=None):
        if software:
            if not path.isfile("answers/{}_{}.mp3".format(action, software)):
                tts = gTTS(
                text="Très bien, je {} {}...".format(action, software), lang="fr")
                tts.save("answers/{}_{}.mp3".format(action, software))

            notify("Alexa: Très bien, je {} {} ... ".format(
            action, software), self.icon)
            Popen(["mplayer", "answers/{}_{}.mp3".format(action, software)])
        else:
            if not path.isfile("answers/{}.mp3".format(action)):
                tts = gTTS(text=text, lang="fr")
                tts.save("answers/{}.mp3".format(action))

            notify("Alexa: {}".format(text), self.icon)
            call(["mplayer", "answers/{}.mp3".format(action)])

        self.end = True
   #--------------------------------------------------------------#
Speech.py 文件源码 项目:Tzara---A-Personal-Assistant 作者: Suman7495 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def speak(out_string):
    """
    Speaks using gTTs from the internet.
    """
    path = os.getcwd() + "/Text_Files/ping_result.txt"
    path_os = path.replace(" ", "\ ")
    path_os = path_os.replace("(", "\(")
    path_os = path_os.replace(")", "\)")
    os.system("if ! ping -c 1 www.google.com>/dev/null;"
        "then echo fail >"+ path_os +";"   
        "else echo success>"+ path_os + ";fi;")
    f_ping = open(path)  
    result = f_ping.read().strip().split("\n")
    f_ping.close()
    print '\033[1m' + 'Tzara: ' + '\033[0m' + out_string
    if result[0] == 'success':
        tts = gTTS(text = out_string, lang = 'en')
        tts.save("hello.mp3")
        os.system("mpg321 -q hello.mp3")
sfx.py 文件源码 项目:FlapJack-Cogs 作者: flapjax 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def enqueue_tts(self, vchan: discord.Channel,
                           text: str,
                            vol: int=None,
                       priority: int=5,
                          tchan: discord.Channel=None,
                       language: str=None):
        if vol is None:
            vol = self.tts_volume
        if language is None:
            language = self.language
        tts = gTTS(text=text, lang=language)
        path = self.temp_filepath + ''.join(random.choice(
                   '0123456789ABCDEF') for i in range(12)) + ".mp3"
        tts.save(path)

        try:
            item = {'cid': vchan.id, 'path': path, 'vol': vol,
                    'priority': priority, 'delete': True, 'tchan': tchan}
            self.master_queue.put_nowait(item)
            return True
        except asyncio.QueueFull:
            return False
sayer.py 文件源码 项目:sketal 作者: vk-brain 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def process_message(self, msg):
        command, text = self.parse_message(msg, full_text=True)

        if not text:
            return await msg.answer('??????? ????? ??? ???????? ??? ? ????!')

        answer, answer_file = await self.create_audio(gTTS, text)

        if answer_file is None:
            return await msg.answer(answer)

        audio = await upload_audio_message(self.api, answer_file, msg.user_id)
        answer_file.close()

        return await msg.answer("", attachment=str(audio))
voice.py 文件源码 项目:Abb1t 作者: k-freeman 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def __init__(self, bot):
        self.bot = bot.bot
        self.description = "*/voice* _<message>_ - using gTTS a voice message of _<message>_ is created"
        self.queue_in=Queue()
        #self.queue_out=Queue()
        thread.start_new_thread(self.run,())
        #self.resttime=0
        #self.lastcmd=0
voice.py 文件源码 项目:Abb1t 作者: k-freeman 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def run(self):
        while 1: 
            msg=self.queue_in.get() # get() is blocking
            chat_id=msg.get_chat_id()
            if re.search(r'^(?:/|!)voice ', msg.get_text().lower()) and len(msg.get_text().split(" "))>=2:
                tts=msg.get_text().split(" ",1)[1].lower().replace("Ä","ae").replace("ä","ae").replace("Ü","ue").replace("ü","ue").replace("Ö","oe").replace("ö","oe").replace("ß","ss")
                with tempfile.NamedTemporaryFile(suffix=".mp3") as temporaryfile:
                    gtts.gTTS(text=tts,lang="de").write_to_fp(temporaryfile)
                    temporaryfile.seek(0)
                    self.bot.sendAudio(chat_id,temporaryfile,title="Abb1tvoice")
tts.py 文件源码 项目:globibot 作者: best-coloc-ever 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def make_tts_file(content, lang):
    fp = mktemp()

    tts = gTTS(text=content, lang=lang)
    tts.save(fp)

    return fp
tts.py 文件源码 项目:dingdang-robot 作者: wzpan 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def get_speech(self, phrase):
        if self.language not in self.languages:
            raise ValueError("Language '%s' not supported by '%s'",
                             self.language, self.SLUG)
        tts = gtts.gTTS(text=phrase, lang=self.language)
        with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as f:
            tmpfile = f.name
        tts.save(tmpfile)
        return tmpfile
main.py 文件源码 项目:google-home-notifier-python 作者: harperreed 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def play_tts(text, lang='en', slow=False):
    tts = gTTS(text=text, lang=lang, slow=slow)
    filename = slugify(text+"-"+lang+"-"+str(slow)) + ".mp3"
    path = "/static/cache/"
    cache_filename = "." + path + filename
    tts_file = Path(cache_filename)
    if not tts_file.is_file():
        logging.info(tts)
        tts.save(cache_filename)

    urlparts = urlparse(request.url)
    mp3_url = "http://" +urlparts.netloc + path + filename 
    logging.info(mp3_url)
    play_mp3(mp3_url)
gttstest.py 文件源码 项目:Lab-Assistant 作者: SPARC-Auburn 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def speak(whattosay):
    print (whattosay)
    audio_file = "response.mp3"
    tts = gTTS(text=str(whattosay), lang="en")
    tts.save(audio_file)
    playsound(audio_file)
    os.remove(audio_file)
properties.py 文件源码 项目:Lab-Assistant 作者: SPARC-Auburn 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def speak(self, whattosay):
        """
        Converts text to speech
        :param whattosay: Text to speak
        """
        print (self.name.upper() + " > " + whattosay)
        audio_file = "response.mp3"
        tts = gTTS(text=str(whattosay), lang="en")
        tts.save(audio_file)
        self.playsound(audio_file)
        os.remove(audio_file)
text_recognizer.py 文件源码 项目:stephanie-va 作者: SlapBot 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def recognize_from_google(self, text):
        try:
            self.tts = gTTS(text=text, lang='en')
            return True
        except Exception:
            raise Exception
Functions.py 文件源码 项目:Personal_AI_Assistant 作者: PratylenClub 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def read_nicely_text(txt, instance_vlc, player_vlc):
    tts = gTTS(text=txt,lang='en')
    tts.save("rss_read.mp3")
    media = instance_vlc.media_new("rss_read.mp3")
    player_vlc.set_media(media)
    player_vlc.play()
gtts_audio_generator.py 文件源码 项目:LaSVeGAS 作者: mayankk4 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def GenerateAudio(text, output_path, audio_accent):
    print "Generating Audio."

    ttsKey = gTTS(text=text, lang=audio_accent)
    ttsKey.save(output_path)
assistant_button.py 文件源码 项目:ct-google-assistant-sdk 作者: merlinschumacher 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def speak_tts(ttstext, language="en-us"):
    tts = gTTS(text=ttstext, lang=language)
    tts.save("answer.mp3")
    call(["mpg123", "answer.mp3"])


# turn_on_led schaltet die LED an.
assistant.py 文件源码 项目:ct-google-assistant-sdk 作者: merlinschumacher 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def speak_tts(ttstext, language="en-us"):
    tts = gTTS(text=ttstext, lang=language)
    tts.save("answer.mp3")
    call(["mpg123", "answer.mp3"])


# turn_on_led schaltet die LED an.
google.py 文件源码 项目:jessy 作者: jessy-project 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def say(self, phrase, *args):
        self._logger.debug("Saying '%s' with '%s'", phrase, self.SLUG)
        if self.language not in self.languages:
            raise ValueError("Language '%s' not supported by '%s'",
                             self.language, self.SLUG)
        tts = gtts.gTTS(text=phrase, lang=self.language)
        with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as f:
            tmpfile = f.name
        tts.save(tmpfile)
        self.play_mp3(tmpfile)
        os.remove(tmpfile)
speech_bot_interface.py 文件源码 项目:ais-demos 作者: jaybutera 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def speakResponse(response):
    #tts = gTTS(text=response, lang='en')
    tts = gTTS(text=response, lang='en')
    tts.save("resources/bot_output.wav")
    os.system("start resources/bot_output.wav")
persia.py 文件源码 项目:Persia 作者: rjcf18 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def speak(self, text):
        """
        Processes the text and reproduces it (TTS method)
        """

        tts = gTTS(text=(text), lang='en')
        path = os.path.dirname(os.path.realpath(__file__))
        tts.save(path+"/data/speech.mp3")
        os.system("mpg321 "+path+ "/data/speech.mp3 -quiet")
donna_add_song.py 文件源码 项目:Donna 作者: kevinetore 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def requested_donna_audio():
    response_donna = "Hello Kevin, sure give me a moment!"
    tts = gTTS(text= response_donna, lang='en')
    # Google text to speech requires MP3 file
    tts.save('response_donna.mp3')
    # We are using Alsa as output to play the MP3
    os.system('mpg321 -o alsa response_donna.mp3')
    os.remove('response_donna.mp3')
added.py 文件源码 项目:Donna 作者: kevinetore 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def addedSong(title):
    donna = "Hello, I just added the song: {} to your favorites on Youtube! Have a nice day".format(title)
    tts = gTTS(text= donna, lang='en')
    tts.save('added_default.mp3')
    os.system('mpg321 -o alsa added_default.mp3')
    os.remove('added_default.mp3')
pandora.py 文件源码 项目:pandora 作者: ryzokuken 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def speak(engine, message):
    try:
        tts = gTTS(text=message, lang='en')
        tts.save('out.mp3')
        system('mpg123 out.mp3 && rm out.mp3')
    except:
        engine.say(message)
        engine.runAndWait()
sound.py 文件源码 项目:My-AppDaemon 作者: ReneTode 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def say(self,text,lang,priority,volume="00"):
############################################
# the TTS function. make a mp3 from the text
# and put a file in the prioritylist
############################################
    self.soundlog("say; put text in waitingrow: " + text)
    with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as f:
        fname = f.name
    tts = gTTS(text=text, lang=lang)
    tts.save(fname)
    self. write_in_prioritylist(priority,fname,"1",volume)
google.py 文件源码 项目:j2f 作者: jasper2fork 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def say(self, phrase):

        tts = gtts.gTTS(text=phrase, lang=self.language)
        with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as f:
            tmpfile = f.name
        tts.save(tmpfile)
        data = self.mp3_to_wave(tmpfile)
        os.remove(tmpfile)
        return data
chatter.py 文件源码 项目:Sarabot 作者: AlexR1712 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def chatter(bot,update):

    chat_id = update.message.chat_id
    message = update.message.text
    if message == 'foto':
        bot.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.UPLOAD_PHOTO)
        bot.sendPhoto(chat_id=chat_id, photo='https://unsplash.it/600?random')
    else:
        k = aiml.Kernel()
        k.learn("std-startup.xml")
        k.respond("sara")
        k.setBotPredicate("name", "Sara")
        k.setBotPredicate("anyo_nacimiento", "2015")
        k.setBotPredicate("edad", str(date.today().year-2015) )
        k.setBotPredicate("botmaster", 'Alexander' )
        k.setBotPredicate("nombre_bot", 'Sara' )
        k.setBotPredicate("birthday", '17/12/2015' )
        bot.sendChatAction(chat_id=chat_id, action=telegram.ChatAction.TYPING)
        response = k.respond(message)    
        #bot.sendMessage(chat_id, text=response)
        tts = gTTS(text=response, lang='es') 

        file = str(chat_id) + str(time.time()) + '.ogg'
        tts.save(file)
        bot.sendVoice(chat_id=chat_id, voice=open(file, 'rb'))
        os.remove(file)
clip.py 文件源码 项目:MangoByte 作者: mdiller 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def tts_save(filename, text, lang):
    # run_command(["pico2wave", "--wave", filename, "-l", "en-GB", text])
    try:
        tts = gTTS(text=text, lang=lang)
        tts.save(filename)
    except AttributeError:
        raise UserError("Whoops. Looks like gtts is broken right now.")
    except (RecursionError, requests.exceptions.HTTPError):
        raise UserError("There was a problem converting that via gtts")


问题


面经


文章

微信
公众号

扫码关注公众号