zoukankan      html  css  js  c++  java
  • 通过http方式 post天气,并合成语音

    # coding=utf-8
    import sys
    import json
    import pygame
    import time
    
    IS_PY3 = sys.version_info.major == 3
    if IS_PY3:
        import requests
        from urllib.request import urlopen
        from urllib.request import Request
        from urllib.error import URLError
        from urllib.parse import urlencode
        from urllib.parse import quote_plus
    else:
        import urllib2
        from urllib import quote_plus
        from urllib2 import urlopen
        from urllib2 import Request
        from urllib2 import URLError
        from urllib import urlencode
    
    API_KEY = 'TutBVkq5Mv8gE7LqfulErVs9'
    SECRET_KEY = 'U8qtLfZQQ3qR12TiS7ZLjTxrdXjiQiNU'
    
    # 发音人选择, 基础音库:0为度小美,1为度小宇,3为度逍遥,4为度丫丫,
    # 精品音库:5为度小娇,103为度米朵,106为度博文,110为度小童,111为度小萌,默认为度小美 
    PER = 1
    # 语速,取值0-15,默认为5中语速
    SPD = 5
    # 音调,取值0-15,默认为5中语调
    PIT = 5
    # 音量,取值0-9,默认为5中音量
    VOL = 5
    # 下载的文件格式, 3:mp3(default) 4: pcm-16k 5: pcm-8k 6. wav
    AUE = 3
    
    FORMATS = {3: "mp3", 4: "pcm", 5: "pcm", 6: "wav"}
    FORMAT = FORMATS[AUE]
    
    CUID = "123456PYTHON"
    
    TTS_URL = 'http://tsn.baidu.com/text2audio'
    
    
    class DemoError(Exception):
        pass
    
    
    """  TOKEN start """
    
    TOKEN_URL = 'http://openapi.baidu.com/oauth/2.0/token'
    SCOPE = 'audio_tts_post'  # 有此scope表示有tts能力,没有请在网页里勾选
    
    def play():
        file = r'result.mp3'
        pygame.mixer.init()
        print("播放天气:")
        pygame.mixer.music.load(file)
    
        pygame.mixer.music.play()
        time.sleep(15)
        pygame.mixer.music.stop()
        print("播放完毕。")
    
    def fetch_token():
        # print("fetch token begin")
        params = {'grant_type': 'client_credentials',
                  'client_id': API_KEY,
                  'client_secret': SECRET_KEY}
        post_data = urlencode(params)
    
        post_data = post_data.encode('utf-8')
        req = Request(TOKEN_URL, post_data)
        try:
            f = urlopen(req, timeout=5)
            result_str = f.read()
        except URLError as err:
            print('token http response http code : ' + str(err.code))
            result_str = err.read()
    
            result_str = result_str.decode()
    
        # print(result_str)
        result = json.loads(result_str)
        # print(result)
        if ('access_token' in result.keys() and 'scope' in result.keys()):
            if not SCOPE in result['scope'].split(' '):
                raise DemoError('scope is not correct')
            # print('SUCCESS WITH TOKEN: %s ; EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))
            return result['access_token']
        else:
            raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')
    
    
    """  TOKEN end """
    
    if __name__ == '__main__':
    
        print("请输入要查询的天气:")
    
        r = requests.get('http://wthrcdn.etouch.cn/weather_mini?city=' + input())
        r.encoding='utf-8'
        weather = r.json()
        text_weather = '今日'+ weather['data']['city'] + ',' + weather['data']['forecast'][0]['type']  + ',' + weather['data']['forecast'][0]['date'] + ',' + 
        weather['data']['forecast'][0]['high']+ ',' + weather['data']['forecast'][0]['low'] + ',' + weather['data']['ganmao']
    
        token = fetch_token()
        tex = quote_plus(text_weather)  # 此处TEXT需要两次urlencode
        # print(tex)
        params = {'tok': token, 'tex': tex, 'per': PER, 'spd': SPD, 'pit': PIT, 'vol': VOL, 'aue': AUE, 'cuid': CUID,
                  'lan': 'zh', 'ctp': 1}  # lan ctp 固定参数
    
        data = urlencode(params)
        # print('test on Web Browser' + TTS_URL + '?' + data)
    
        req = Request(TTS_URL, data.encode('utf-8'))
        has_error = False
        try:
            f = urlopen(req)
            result_str = f.read()
    
            headers = dict((name.lower(), value) for name, value in f.headers.items())
    
            has_error = ('content-type' not in headers.keys() or headers['content-type'].find('audio/') < 0)
        except  URLError as err:
            print('asr http response http code : ' + str(err.code))
            result_str = err.read()
            has_error = True
    
        save_file = "error.txt" if has_error else 'result.' + FORMAT
        with open(save_file, 'wb') as of:
            of.write(result_str)
    
        if has_error:
            result_str = str(result_str, 'utf-8')
            print("tts api  error:" + result_str)
    
        # print("result saved as :" + save_file)
    
        play()
    

      

  • 相关阅读:
    javaweb学习(十一)—— 使用Cookie进行会话管理
    微信小程序授权登录-获取用户信息-手机号信息-及解密碰到的坑
    mysql数据库乱码问题,数据库和程序链接过程中查询和显示出现中文乱码
    javaWeb项目启动加载java类执行自己想要执行的操作
    spring mvc 把事物处理配置到Controller层
    maven项目外网向内网搬迁问题之找不到本地仓库已经有的jar包
    java 解析json 的各种jar包
    jquery ui 插架 之 dataTable 显示横向滚动条
    jsp spring Mvc前台提交数据到后天乱码
    java cs tab点击切换标签的实现 panel
  • 原文地址:https://www.cnblogs.com/xuyong437/p/11365891.html
Copyright © 2011-2022 走看看