当前位置: 首页>>代码示例>>Python>>正文


Python gtts.gTTS方法代码示例

本文整理汇总了Python中gtts.gTTS方法的典型用法代码示例。如果您正苦于以下问题:Python gtts.gTTS方法的具体用法?Python gtts.gTTS怎么用?Python gtts.gTTS使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在gtts的用法示例。


在下文中一共展示了gtts.gTTS方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: doFileStuff

# 需要导入模块: import gtts [as 别名]
# 或者: from gtts import gTTS [as 别名]
def doFileStuff(line,isSlow):
    myobj = gTTS(text=line, lang='en', slow=isSlow) 
    myobj.save("placeholder.mp3")
    
    y, sr = librosa.load("placeholder.mp3")
    data = librosa.resample(y, sr, SAMPLE_RATE)
    librosa.output.write_wav('placeholder.wav', data, SAMPLE_RATE)
    d, sr = sf.read('placeholder.wav')
    sf.write('placeholder.wav', d, sr)

    y, sr = librosa.load("placeholder.mp3")
    lowData = librosa.resample(y, sr, SAMPLE_RATE*LOW_FACTOR)
    librosa.output.write_wav('lowPlaceholder.wav', lowData, SAMPLE_RATE)
    d, sr = sf.read('lowPlaceholder.wav')
    sf.write('lowPlaceholder.wav', d, sr)

    return data 
开发者ID:carykh,项目名称:rapLyrics,代码行数:19,代码来源:rapSpeaker.py

示例2: validate_lang

# 需要导入模块: import gtts [as 别名]
# 或者: from gtts import gTTS [as 别名]
def validate_lang(ctx, param, lang):
    """Validation callback for the <lang> option.
    Ensures <lang> is a supported language unless the <nocheck> flag is set
    """
    if ctx.params['nocheck']:
        return lang

    try:
        if lang not in tts_langs():
            raise click.UsageError(
                "'%s' not in list of supported languages.\n"
                "Use --all to list languages or "
                "add --nocheck to disable language check." % lang)
        else:
            # The language is valid.
            # No need to let gTTS re-validate.
            ctx.params['nocheck'] = True
    except RuntimeError as e:
        # Only case where the <nocheck> flag can be False
        # Non-fatal. gTTS will try to re-validate.
        log.debug(str(e), exc_info=True)

    return lang 
开发者ID:luoliyan,项目名称:chinese-support-redux,代码行数:25,代码来源:cli.py

示例3: notify

# 需要导入模块: import gtts [as 别名]
# 或者: from gtts import gTTS [as 别名]
def notify(self, notification):
        if notification == "":
                notification = "No+Notification+Data+Recieved"
        
        mp3 = MP3_CACHE_DIR + "/" + notification.replace("+","_") + ".mp3"
        text = notification.replace("+"," ")

        if not os.path.isfile(mp3) :
            print("Generating MP3...")
            tts = gTTS(text=text, lang='en-uk') # See Google TTS API for more Languages (Note: This may do translation Also - Needs Testing)
            tts.save(mp3)
        else:
            print("Reusing MP3...")

        print("Sending notification...")
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Pull IP Address for Local HTTP File Serving (Note: This requires an internet connection)
        s.connect(("8.8.8.8", 80))
        ip_add = s.getsockname()[0]
        print (ip_add)
        s.close()
        self.Cast(ip_add, mp3)

        print("Notification Sent.")

        return 
开发者ID:GhostBassist,项目名称:GooglePyNotify,代码行数:27,代码来源:GooglePyNotify.py

示例4: __init__

# 需要导入模块: import gtts [as 别名]
# 或者: from gtts import gTTS [as 别名]
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)

        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} [текст] - произнести текст (+ значит ударение перед ударной гласной)."] 
开发者ID:ekonda,项目名称:sketal,代码行数:20,代码来源:outsource_sayer.py

示例5: say

# 需要导入模块: import gtts [as 别名]
# 或者: from gtts import gTTS [as 别名]
def say(text):
        print("%s" % text)
        if isinstance(text, str):
            text = text.decode("utf-8")
        md5 = hashlib.md5(text.encode('utf-8')).hexdigest()
        fname = "/tmp/%s.mp3" % md5
        if not os.path.exists(fname):
            myre = re.compile('[[A-Za-z]', re.UNICODE)
            lang = 'en' if myre.match(text) else 'ru'

            logging.getLogger('requests').setLevel(logging.getLogger('').getEffectiveLevel())
            tts = gtts.gTTS(text=text, lang=lang, slow=False)
            tts.save(fname)

        with open(os.devnull, 'w') as fnull:
            subprocess.call("mplayer %s" % fname, shell=True, stderr=fnull, stdout=fnull) 
开发者ID:undera,项目名称:pylgbst,代码行数:18,代码来源:__init__.py

示例6: _generate_audio_file

# 需要导入模块: import gtts [as 别名]
# 或者: from gtts import gTTS [as 别名]
def _generate_audio_file(self):
        """
        Generic method used as a Callback in TTSModule
            - must provided the audio file and write it on the disk

        .. raises:: FailToLoadSoundFile
        """

        # Since the gTTS lib disabled the SSL verification we get rid of insecure request warning
        urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
        
        tts = gTTS(text=self.words, lang=self.language)
        
        # OK we get the audio we can write the sound file
        tts.save(self.file_path)
        
        # Re enable the warnings to avoid affecting the whole kalliope process 
        warnings.resetwarnings() 
开发者ID:kalliope-project,项目名称:kalliope,代码行数:20,代码来源:googletts.py

示例7: textPlay

# 需要导入模块: import gtts [as 别名]
# 或者: from gtts import gTTS [as 别名]
def textPlay():
    f = open("output.txt", "r")

    text = f.read()


    # Language in which you want to convert
    language = 'en'

    # Passing the text and language to the engine, 
    # here we have marked slow=False. Which tells 
    # the module that the converted audio should 
    # have a high speed
    myobj = gTTS(text=text, lang=language, slow=False)
    myobj.save("welcome.wav")
    '''
    print('Playing')
    winsound.PlaySound("This is real this is me",winsound.SND_FILENAME)
    pygame.init()
    t= pygame.mixer.Sound("welcome.wav")
    t.play()'''

    os.system("start welcome.wav") 
开发者ID:ishita27,项目名称:Printed-Text-recognition-and-conversion,代码行数:25,代码来源:text2speech.py

示例8: tts

# 需要导入模块: import gtts [as 别名]
# 或者: from gtts import gTTS [as 别名]
def tts(bot: Bot, update: Update, args):
    current_time = datetime.strftime(datetime.now(), "%d.%m.%Y %H:%M:%S")
    filename = datetime.now().strftime("%d%m%y-%H%M%S%f")
    reply = " ".join(args)
    update.message.chat.send_action(ChatAction.RECORD_AUDIO)
    lang="ml"
    tts = gTTS(reply, lang)
    tts.save("k.mp3")
    with open("k.mp3", "rb") as f:
        linelist = list(f)
        linecount = len(linelist)
    if linecount == 1:
        update.message.chat.send_action(ChatAction.RECORD_AUDIO)
        lang = "en"
        tts = gTTS(reply, lang)
        tts.save("k.mp3")
    with open("k.mp3", "rb") as speech:
        update.message.reply_voice(speech, quote=False) 
开发者ID:TGExplore,项目名称:Marie-2.0-English,代码行数:20,代码来源:tts.py

示例9: validate_lang

# 需要导入模块: import gtts [as 别名]
# 或者: from gtts import gTTS [as 别名]
def validate_lang(ctx, param, lang):
    """Validation callback for the <lang> option.
    Ensures <lang> is a supported language unless the <nocheck> flag is set
    Uses <tld> to fetch languages from other domains
    """
    if ctx.params['nocheck']:
        return lang

    try:
        tld = ctx.params['tld']
        if lang not in tts_langs(tld):
            raise click.UsageError(
                "'%s' not in list of supported languages.\n"
                "Use --all to list languages or "
                "add --nocheck to disable language check." % lang)
        else:
            # The language is valid.
            # No need to let gTTS re-validate.
            ctx.params['nocheck'] = True
    except RuntimeError as e:
        # Only case where the <nocheck> flag can be False
        # Non-fatal. gTTS will try to re-validate.
        log.debug(str(e), exc_info=True)

    return lang 
开发者ID:pndurette,项目名称:gTTS,代码行数:27,代码来源:cli.py

示例10: __init__

# 需要导入模块: import gtts [as 别名]
# 或者: from gtts import gTTS [as 别名]
def __init__(self, language="en-us"):
        self._language = language
        self._tts = gTTS(lang=self._language, text="dummy")

    # public methods 
开发者ID:HoussemCharf,项目名称:FunUtils,代码行数:7,代码来源:tts.py

示例11: speak

# 需要导入模块: import gtts [as 别名]
# 或者: from gtts import gTTS [as 别名]
def speak(text):
    from gtts import gTTS
    import os
    tts = gTTS(text=text, lang='ko')
    tts.save("tmp_talk.mp3")
    os.system("omxplayer tmp_talk.mp3")
    os.system("rm -f tmp_talk.mp3") 
开发者ID:jeonghoonkang,项目名称:BerePi,代码行数:9,代码来源:sample.py

示例12: text_to_speech_online

# 需要导入模块: import gtts [as 别名]
# 或者: from gtts import gTTS [as 别名]
def text_to_speech_online(text, lang='en'):
    """Convert text to speech using Google Translate’s and save in mp3. Need an internet connection.

    Args:
        text (str): Text.
        lang (str): Language (Ex: pt-br).

    """
    tts = gTTS(text=text, lang=lang)
    tts.save("sound.mp3") 
开发者ID:lucasayres,项目名称:python-tools,代码行数:12,代码来源:text_to_speech_online.py

示例13: tts_save

# 需要导入模块: import gtts [as 别名]
# 或者: from gtts import gTTS [as 别名]
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")
	except AssertionError as e:
		if e.args and e.args[0] == "No text to send to TTS API":
			raise UserError("I can't convert that to TTS. Looks like there's not much there.")
		else:
			raise 
开发者ID:mdiller,项目名称:MangoByte,代码行数:16,代码来源:clip.py

示例14: text_to_speech

# 需要导入模块: import gtts [as 别名]
# 或者: from gtts import gTTS [as 别名]
def text_to_speech(self, speech):
        speech = remove_ansi_escape_seq(speech)
        tts = gTTS(speech, lang="en")
        tts.save("voice.mp3")
        audio = AudioSegment.from_mp3('voice.mp3')
        playback.play(audio)
        os.remove("voice.mp3") 
开发者ID:sukeesh,项目名称:Jarvis,代码行数:9,代码来源:voice.py

示例15: get_google

# 需要导入模块: import gtts [as 别名]
# 或者: from gtts import gTTS [as 别名]
def get_google(self):
        tts = gTTS(self.text, lang=self.lang)
        tts.save(self.path) 
开发者ID:luoliyan,项目名称:chinese-support-redux,代码行数:5,代码来源:tts.py


注:本文中的gtts.gTTS方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。