本周主要实现一个基于地理位置的实时景点音频播放系统。该系统能够根据用户当前的地理位置,自动识别最近的景点并播放对应的音频讲解。以下是实现该功能的详细步骤和代码示例。
1.系统功能概述
- 获取用户位置: 系统通过前端页面获取用户的当前地理坐标(纬度和经度)。
- 计算最近景点: 后端服务器根据用户提供的坐标,计算与预设景点的距离,并找到最近的景点。
- 返回音频链接: 如果找到最近的景点,服务器将返回对应景点的音频文件链接,前端进行播放。
2.后端实现思路
思路:后端服务器接收前端发送的经纬度信息,通过Haversine公式计算用户与各景点的距离,找到最近的景点并返回对应的音频文件链接。
- Haversine公式计算距离: haversine函数计算用户当前位置与各个景点之间的距离,返回结果单位为米。
# Haversine公式计算两点间的距离(单位:米)
def haversine(lat1, lon1, lat2, lon2):
R = 6371000 # 地球半径,单位:米
phi1 = math.radians(lat1)
phi2 = math.radians(lat2)
delta_phi = math.radians(lat2 - lat1)
delta_lambda = math.radians(lon2 - lon1)
a = math.sin(delta_phi / 2) ** 2 + math.cos(phi1) * math.cos(phi2) * math.sin(delta_lambda / 2) ** 2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
distance = R * c
return distance
max_distance = 100 # 最大距离100米
- 查找最近景点: find_nearest_spot函数遍历所有预设景点,找到距离用户最近且在最大距离范围内的景点。将景点经纬度信息预先存入audio.json文件中。
# 查找距离最近的景点
def find_nearest_spot(latitude, longitude, max_distance=max_distance):
nearest_spot = None
nearest_distance = float('inf')
for spot in spots:
spot_lat = spot['latitude']
spot_lon = spot['longitude']
distance = haversine(latitude, longitude, spot_lat, spot_lon)
if distance < nearest_distance:
nearest_spot = spot
nearest_distance = distance
if nearest_distance <= max_distance:
return nearest_spot
else:
return None
- 处理获取音频请求: /getAudio路由接收前端请求,根据提供的经纬度查找最近的景点,并返回对应的音频文件链接。
@app.route('/getAudio', methods=['GET'])
def get_audio():
latitude = request.args.get('latitude')
longitude = request.args.get('longitude')
if not latitude or not longitude:
return jsonify({"error": "Missing latitude or longitude"}), 400
latitude = float(latitude)
longitude = float(longitude)
spot = find_nearest_spot(latitude, longitude)
if spot:
print(f"最近的景点是: {spot['name']}")
else:
return jsonify({"error": "Spot not found"}), 404
spot_name = spot['id']
audio_filename = f"{spot_name}.mp3"
audio_filepath = os.path.join(AUDIO_FILES_PATH, audio_filename)
if os.path.exists(audio_filepath):
return jsonify({"audioUrl": f"https://www.aiguider666.asia/audio/{audio_filename}"})
else:
return jsonify({"error": "Audio file not found"}), 404
- 提供音频文件服务: /audio/路由用于提供音频文件的访问服务。
@app.route('/audio/<filename>', methods=['GET'])
def serve_audio_file(filename):
return send_from_directory(AUDIO_FILES_PATH, filename)
3.测试结果
- 运行后端服务器: 启动Flask服务器,通过python app.py命令运行后端代码。
- 前端页面测试: 打开前端页面,输入经纬度,点击获取音频按钮,验证音频文件是否能够正常播放。
- 后端服务器:输入经纬度,从服务器获取音频文件成功返回
总结: 我们实现了一个基于地理位置的实时景点音频播放系统。系统能够根据用户的当前地理位置,自动识别最近的景点并播放对应的音频讲解。这一功能不仅提升了用户的游览体验,还展示了多模态技术在实际应用中的潜力。