zl程序教程

您现在的位置是:首页 >  后端

当前栏目

调用baidu地图API,实现语音导航播报

API 实现 调用 地图 导航 语音 baidu 播报
2023-09-14 08:59:07 时间

一、代码

百度地图开放平台: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("上海市浦东新区******", "上海市静安区******", "骑行")