調用baidu地圖API,實現語音導航播報


一、代碼

百度地圖開放平台:http://lbsyun.baidu.com/

百度AI開放平台:https://ai.baidu.com/

import pprint
import requests
from aip import AipSpeech

# 地理位置編碼url
geocoding_url = "http://api.map.baidu.com/geocoding/v3/"
# 路線規划url
direction_url = "http://api.map.baidu.com/direction/v2/"
# 應用AK
ak = "*****************"


# 獲取地理編碼
def get_geocoding(address, ak, callback):
    params = {
        "address": address,
        "ak": ak,
        "callback": callback,
        "output": "json"
    }
    result = requests.get(geocoding_url, params=params)
    if result.status_code == 200:
        res_json = result.json()
        lng = str(res_json.get("result").get("location").get("lng"))[:-8]  # 小數點長度限制
        lat = str(res_json.get("result").get("location").get("lat"))[:-8]
        return {"msg": [lat, lng]}
    else:
        return {"error": result.text}


def get_direction(origin_addr, destination_addr, type):
    origin = get_geocoding(origin_addr, ak, "")
    if origin.get("msg"):
        origin = ",".join(origin.get("msg"))
        print(origin)
    else:
        return
    destination = get_geocoding(destination_addr, ak, "")
    if destination.get("msg"):
        destination = ",".join(destination.get("msg"))
        print(destination)
    else:
        return
    params = {
        "origin": origin,  # 起點
        "ak": ak,
        "destination": destination,  # 目的地
    }
    type_dict = {"駕車": "driving", "摩托車": "motorcycle", "公交車": "transit", "騎行": "riding"}
    # 為了不讓參數中的逗號編碼,自己拼接url
    result = requests.get(url=direction_url + type_dict.get(type, "driving") + "?" + "".join(
        '%s=%s&' % (query, enc_params) for query, enc_params in params.items()).strip("&"))
    if result.status_code == 200:
        res_json = result.json()
        pprint.pprint(res_json)
        # 將信息拼接成文字
        all_distance = res_json.get("result").get("routes")[0].get("distance")
        all_duration = res_json.get("result").get("routes")[0].get("duration")
        all_text = "總路程%s公里,耗時%s分鍾" % (all_distance / 1000, int(all_duration / 60))

        steps = res_json.get("result").get("routes")[0].get("steps")
        cont = ""
        for dic in steps:
            for k, v in dic.items():
                if k == "instructions":
                    cont += "%s," % (v.replace("<b>","").replace("</b>",""))
                if k == "turn_type":
                    cont += "%s," % (v)
        print(all_text + cont.strip(","))
        text2audio(all_text + cont)
    else:
        return {"error": result.text}


def text2audio(text):
    APP_ID = '*********'  # AI中心app
    API_KEY = '************'  # AI中心key
    SECRET_KEY = '**************'  # AI中心SECRET

    client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
    result = client.synthesis(text, 'zh', 1, {'vol': 8, 'per': 4, 'spd': 4})
    '''
    固定值zh,語言選擇,目前只有中英文混合模式,填寫固定值zh
    客戶端類型選擇,web端填寫固定值1
    spd語速,取值0-15,默認為5中語速(選填)
    pit音調,取值0-15,默認為5中語調(選填)
    vol音量,取值0-15,默認為5中音量(選填)
    per發音人選擇, 0為普通女聲,1為普通男生,3為情感合成-度逍遙,4為情感合成-度丫丫,默認為普通女聲
    '''
    # 識別正確返回語音二進制 錯誤則返回dict 參照下面錯誤碼
    if not isinstance(result, dict):
        with open('路線規划.mp3', 'wb') as f:
            f.write(result)


get_direction("上海市浦東新區******", "上海市靜安區******", "騎行")

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM