尝试了大量的代码,我可以导航的路线,但它并没有给我任何一种语音通知轮流左或右。
void startNavigation1(Route route) {
_prepareNavigation(route);
// Stop in case it was started before.
_locationSimulationProvider.stop();
// Access the device's GPS sensor and other data.
// The navigator is set as listener to receive location updates.
_herePositioningProvider!.startLocating(_visualNavigator, LocationAccuracy.navigation);
_startDynamicSearchForBetterRoutes(route);
setupListeners2();}
{print(‘ininsetuplistener2-);( HERE.RouteProgressListener((HERE.RouteProgress routeProgress)异步{地图jsonData ={ "load":load_info!.id,“卡车”:load_info!.truck_id,"load_size":"TL",“令牌”:str_accesstoken!,"type":"GPS",//"state":'_currentAddress',// "country":"US",// "postal":"10001",“位置”:{“坐标”:{ _herePositioningProvider!.getLastKnownLocation()!.coordinates .longitude,"lat":_herePositioningProvider!.getLastKnownLocation()!.coordinates .latitude },"type":"Point",};
if (socket == null && (load_info!.status == 'Intransit' ||
load_info!.status != 'Journey End')) {
if (socket == null) {
print(' inside socket');
Socket? _socket =
await SocketIOConnection()
.connectToServer(
str_accesstoken!);
setState(() {
socket = _socket;
});
socket!.connect();
socket!.onConnect((data) {
print('connected......');
Timer.periodic(new Duration(seconds: 20), (timer) {
socket!.emit("gps", jsonData);
});
});
}
// Timer mytimer = Timer.periodic(Duration(minutes:0, seconds: 15), (timer) async {
//code to run on every 2 minutes 5 seconds
// await SocketIOConnection().sendLocation(jsonData);
// });
// Timer.periodic(new Duration(seconds: 20), (timer) {
// print('connected inside');
// print(jsonData);
// });
// timer= new Timer(new Duration(seconds: 15), () async {
// debugPrint("Print after 15 seconds");
// // await SocketIOConnection().sendMessage(socket!, jsonData);
// await Future.delayed(Duration(milliseconds: 10000));
// await SocketIOConnection().sendLocation(jsonData);
// await Future.delayed(Duration(milliseconds: 10000));
//
// });
// Timer.periodic(new Duration(seconds: 1), (timer) {
// debugPrint(timer.tick.toString());
// });
//
}
// Handle results from onRouteProgressUpdated():
List<HERE.SectionProgress> sectionProgressList = routeProgress.sectionProgress;
// sectionProgressList is guaranteed to be non-empty.
HERE.SectionProgress lastSectionProgress = sectionProgressList.elementAt(sectionProgressList.length - 1);
print('Distance to destination in meters: ' + lastSectionProgress.remainingDistanceInMeters.toString());
//print('Traffic delay ahead in seconds: ' + lastSectionProgress.trafficDelay.inSeconds.toString());
// Contains the progress for the next maneuver ahead and the next-next maneuvers, if any.
List<HERE.ManeuverProgress> nextManeuverList = routeProgress.maneuverProgress;
if (nextManeuverList.isEmpty) {
print('No next maneuver available.');
return;
}
HERE.ManeuverProgress nextManeuverProgress = nextManeuverList.first;
int nextManeuverIndex = nextManeuverProgress.maneuverIndex;
HERE.Maneuver? nextManeuver = _visualNavigator.getManeuver(nextManeuverIndex);
if (nextManeuver == null) {
// Should never happen as we retrieved the next maneuver progress above.
return;
}
HERE.ManeuverAction action = nextManeuver.action;
String roadName = _getRoadName(nextManeuver);
String logMessage = describeEnum(action) +
' on ' +
roadName +
' in ' +
nextManeuverProgress.remainingDistanceInMeters.toString() +
' meters.';
if (_previousManeuverIndex != nextManeuverIndex) {
_updateMessageState('New maneuver: $logMessage');
} else {
// A maneuver update contains a different distance to reach the next maneuver.
_updateMessageState("Maneuver update: $logMessage");
}
_previousManeuverIndex = nextManeuverIndex;
if (_lastMapMatchedLocation != null) {
// Update the route based on the current location of the driver.
// We periodically want to search for better traffic-optimized routes.
_dynamicRoutingEngine.updateCurrentLocation(_lastMapMatchedLocation!, routeProgress.sectionIndex);
}
if (str_action != 'Truck Location' ||
str_action != 'Truck Drop Location') {
// button_text == 'Check In Truck Location';
// setState(() {
// flag3 = 1;
// });
} else {
if (double.parse(str_distance!) <= 2) {
SetTracking? setTracking =
// await GetTracking(str_accesstoken, str_user_id)
await GetTracking(str_accesstoken,context)
.GetTrackingDetails();
setState(() {
_setTracking = setTracking!;
button_color = _setTracking!.button_color;
button_text = _setTracking!.button_text;
});
if (button_text == 'Check In') {
setState(() {
flag5=1;
flag3 = 1;
});
} else if (button_text == 'Check Out') {
setState(() {
flag5=1;
flag3 = 1;
});
} else if (button_text == 'Hook Now') {
setState(() {
flag3 = 1;
});
} else if (button_text == 'Drop Now') {
setState(() {
flag3 = 1;
});
}
}
}
// Contains the progress for the next maneuver ahead and the next-next maneuvers, if any.
// Contains the progress for the next maneuver ahead and the next-next maneuvers, if any.
setState(() {
maneuver_action =
_visualNavigator.getManeuver(nextManeuverIndex)!.action.toString();
str_direction = logMessage;
});
if (_previousManeuverIndex != nextManeuverIndex) {
print('New maneuver: $logMessage');
} else {
// A maneuver update contains a different distance to reach the next maneuver.
print('Maneuver update: $logMessage');
}
});
// Notifies on voice maneuver messages.
_visualNavigator.maneuverNotificationListener = HERE.ManeuverNotificationListener((String voiceText) async {
// Handle results lambda_onManeuverNotification().
// Flutter itself does not provide a text-to-speech engine. Use one of the available TTS plugins to speak
// the voiceText message.
print("Voice guidance text: $voiceText");
// setState(() async {
maneuver_icon = getManeuveraction(maneuver_action!);
print('icon :' + maneuver_icon!);
await flutterTts.setSpeechRate(1.0);
await flutterTts.setVolume(1.0);
await flutterTts.setPitch(1.0);
await flutterTts.synthesizeToFile("Hello World", Platform.isAndroid ? "tts.wav" : "tts.caf");
await flutterTts.setVoice({"name": "Karen", "locale": "en-AU"});
await flutterTts.isLanguageAvailable("en-US");
await flutterTts.speak(voiceText);
// flutterTts.speak(voiceText);
// flutterTts.setVolume(150);
// });
});
// Notifies on the current map-matched location and other useful information while driving or walking.
// The map-matched location is used to update the map view.
_visualNavigator.navigableLocationListener =
HERE.NavigableLocationListener((HERE.NavigableLocation currentNavigableLocation) {
// Handle results from onNavigableLocationUpdated():
HERE.MapMatchedLocation? mapMatchedLocation = currentNavigableLocation.mapMatchedLocation;
if (mapMatchedLocation == null) {
print("This new location could not be map-matched. Are you off-road?");
return;
}
_lastMapMatchedLocation = mapMatchedLocation;
var speed = currentNavigableLocation.originalLocation.speedInMetersPerSecond;
var accuracy = currentNavigableLocation.originalLocation.speedAccuracyInMetersPerSecond;
print("Driving speed (m/s): $speed plus/minus an accuracy of: $accuracy");
});
// Notifies when the destination of the route is reached.
_visualNavigator.destinationReachedListener = HERE.DestinationReachedListener(() {
// Handle results from onDestinationReached().
_updateMessageState("Destination reached. Stopping turn-by-turn navigation.");
// Handle r
print('Destination reached. Stopping turn-by-turn navigation.');
print('str_action on destination reached:'+str_action.toString());
if (str_action == 'Truck Location')
// &&
// str_action != 'Truck Drop Location')
{
setState(() {
flag2 = 1;
flag1=0;
flag5=1;
// flag3=0;
str_next_consignment='Reached Truck Location';
});
if(socket!=null){
socket!.disconnect();
socket!.ondisconnect();
print('......disconnected');
}
_settingModalBottomSheet();
}
else if (str_action == 'Pickup')
// &&
// str_action != 'Truck Drop Location')
{
setState(() {
// flag2 = 1;
// flag2 = 0;
// flag1 = 0;
flag5=1;
button_text = 'Check In';
flag3 = 1;
str_next_consignment='Reached Pickup Location';
//button_text = 'Check In';
// endflag=1;
});
if(socket!=null){
socket!.disconnect();
socket!.ondisconnect();
print('......disconnected');
}
_settingModalBottomSheet();
}
else if (str_action == 'Dropoff')
// &&
// str_action != 'Truck Drop Location')
{
setState(() {
// flag2 = 0;
// flag1 = 0;
flag5=1;
button_text = 'Check In';
flag3 = 1;
//flag2 = 1;
str_next_consignment='Reached Dropoff Location';
// button_text = 'Check In';
// endflag=1;
});
if(socket!=null){
socket!.disconnect();
socket!.ondisconnect();
print('......disconnected');
}
_settingModalBottomSheet();
}
else if (str_action == 'Truck End Location')
// &&
// str_action != 'Truck Drop Location').
{
Map data =
{
'load': load_info!.id,
'event': 'Dropped Truck',
"truck":load_info!.truck_id
};
UpdateJourneyStatus(data);
print('data:'+data.toString());
setState(() {
str_next_consignment='Reached Truck End Location';
flag1=0;
flag5=1;
endflag=1;
}
);
if(endflag==1)
{
_selectendtrip();
}
}
// else {
// setState(() {
// button_text = 'Check In';
// // endflag=1;
// flag3 = 1;
// });
// // if(endflag==1)
// // {
// // _selectendtrip();
// // }
// }
if (socket != null)
{
socket!.onDisconnect((data) => print('disconnected'));
}
stopNavigation();
});
// Notifies when a waypoint on the route is reached or missed
// _visualNavigator.milestoneStatusListener = MilestoneStatusListener((Milestone milestone, MilestoneStatus milestoneStatus) {
// // Handle results from onMilestoneStatusUpdated().
// if (milestone.waypointIndex != null && milestoneStatus == MilestoneStatus.reached) {
// print("A user-defined waypoint was reached, index of waypoint: " + milestone.waypointIndex.toString());
// print("Original coordinates: " + milestone.originalCoordinates.toString());
// } else if (milestone.waypointIndex != null && milestoneStatus == MilestoneStatus.missed) {
// print("A user-defined waypoint was missed, index of waypoint: " + milestone.waypointIndex.toString());
// print("Original coordinates: " + milestone.originalCoordinates.toString());
// } else if (milestone.waypointIndex == null && milestoneStatus == MilestoneStatus.reached) {
// // For example, when transport mode changes due to a ferry a system-defined waypoint may have been added.
// print("A system-defined waypoint was reached at: " + milestone.mapMatchedCoordinates.toString());
// } else if (milestone.waypointIndex == null && milestoneStatus == MilestoneStatus.reached) {
// // For example, when transport mode changes due to a ferry a system-defined waypoint may have been added.
// print("A system-defined waypoint was missed at: " + milestone.mapMatchedCoordinates.toString());
// }
// });
// Notifies on the current speed limit valid on the current road.
_visualNavigator.speedLimitListener = HERE.SpeedLimitListener((HERE.SpeedLimit speedLimit) {
// Handle results from onSpeedLimitUpdated().
double? currentSpeedLimit = _getCurrentSpeedLimit(speedLimit);
if (currentSpeedLimit == null) {
print("Warning: Speed limits unknown, data could not be retrieved.");
} else if (currentSpeedLimit == 0) {
print("No speed limits on this road! Drive as fast as you feel safe ...");
} else {
print("Current speed limit (m/s): $currentSpeedLimit");
}
});
// Notifies when the current speed limit is exceeded.
_visualNavigator.speedWarningListener = HERE.SpeedWarningListener((HERE.SpeedWarningStatus speedWarningStatus) {
// Handle results from onSpeedWarningStatusChanged().
if (speedWarningStatus == HERE.SpeedWarningStatus.speedLimitExceeded) {
// Driver is faster than current speed limit (plus an optional offset, see setupSpeedWarnings()).
// Play a click sound to indicate this to the driver.
// As Flutter itself does not provide support for sounds,
// alternatively use a 3rd party plugin to play an alert sound of your choice.
// Note that this may not include temporary special speed limits, see SpeedLimitListener.
SystemSound.play(SystemSoundType.click);
print("Speed limit exceeded.");
}
if (speedWarningStatus == HERE.SpeedWarningStatus.speedLimitRestored) {
print("Driver is again slower than current speed limit (plus an optional offset.)");
}
});
// Notifies on a possible deviation from the route.
// When deviation is too large, an app may decide to recalculate the route from current location to destination.
_visualNavigator.routeDeviationListener = HERE.RouteDeviationListener((HERE.RouteDeviation routeDeviation) {
// Handle results from onRouteDeviation().
HERE.Route? route = _visualNavigator.route;
if (route == null) {
// May happen in rare cases when route was set to null inbetween.
return;
}
// Get current geographic coordinates.
HERE.MapMatchedLocation? currentMapMatchedLocation = routeDeviation.currentLocation.mapMatchedLocation;
GeoCoordinates currentGeoCoordinates = currentMapMatchedLocation == null
? routeDeviation.currentLocation.originalLocation.coordinates
: currentMapMatchedLocation.coordinates;
// Get last geographic coordinates on route.
GeoCoordinates lastGeoCoordinatesOnRoute;
if (routeDeviation.lastLocationOnRoute != null) {
HERE.MapMatchedLocation? lastMapMatchedLocationOnRoute = routeDeviation.lastLocationOnRoute!.mapMatchedLocation;
lastGeoCoordinatesOnRoute = lastMapMatchedLocationOnRoute == null
? routeDeviation.lastLocationOnRoute!.originalLocation.coordinates
: lastMapMatchedLocationOnRoute.coordinates;
} else {
print("User was never following the route. So, we take the start of the route instead.");
lastGeoCoordinatesOnRoute = route.sections.first.departurePlace.originalCoordinates!;
}
int distanceInMeters = currentGeoCoordinates.distanceTo(lastGeoCoordinatesOnRoute) as int;
print("RouteDeviation in meters is " + distanceInMeters.toString());
});
// // Notifies on voice maneuver messages.
// _visualNavigator.maneuverNotificationListener = HERE.ManeuverNotificationListener((String voiceText) async {
// // Handle results lambda_onManeuverNotification().
// // Flutter itself does not provide a text-to-speech engine. Use one of the available TTS plugins to speak
// // the voiceText message.
// print("Voice guidance text: $voiceText");
// // setState(() async {
// maneuver_icon = getManeuveraction(maneuver_action!);
// print('icon :' + maneuver_icon!);
// await flutterTts.setSpeechRate(1.0);
//
// await flutterTts.setVolume(1.0);
//
// await flutterTts.setPitch(1.0);
// await flutterTts.synthesizeToFile("Hello World", Platform.isAndroid ? "tts.wav" : "tts.caf");
//
// await flutterTts.setVoice({"name": "Karen", "locale": "en-AU"});
// await flutterTts.isLanguageAvailable("en-US");
// await flutterTts.speak(voiceText);
//
// // flutterTts.speak(voiceText);
// // flutterTts.setVolume(150);
// // });
//
// });
// Notifies on the attributes of the current road including usage and physical characteristics.
_visualNavigator.roadAttributesListener = HERE.RoadAttributesListener((HERE.RoadAttributes roadAttributes) {
// Handle results from onRoadAttributesUpdated().
// This is called whenever any road attribute has changed.
// If all attributes are unchanged, no new event is fired.
// Note that a road can have more than one attribute at the same time.
print("Received road attributes update.");
if (roadAttributes.isBridge) {
// Identifies a structure that allows a road, railway, or walkway to pass over another road, railway,
// waterway, or valley serving map display and route guidance functionalities.
print("Road attributes: This is a bridge.");
}
if (roadAttributes.isControlledAccess) {
// Controlled access roads are roads with limited entrances and exits that allow uninterrupted
// high-speed traffic flow.
print("Road attributes: This is a controlled access road.");
}
if (roadAttributes.isDirtRoad) {
// Indicates whether the navigable segment is paved.
print("Road attributes: This is a dirt road.");
}
if (roadAttributes.isDividedRoad) {
// Indicates if there is a physical structure or painted road marking intended to legally prohibit
// left turns in right-side driving countries, right turns in left-side driving countries,
// and U-turns at divided intersections or in the middle of divided segments.
print("Road attributes: This is a divided road.");
}
if (roadAttributes.isNoThrough) {
// Identifies a no through road.
print("Road attributes: This is a no through road.");
}
if (roadAttributes.isPrivate) {
// Private identifies roads that are not maintained by an organization responsible for maintenance of
// public roads.
print("Road attributes: This is a private road.");
}
if (roadAttributes.isRamp) {
// Range is a ramp: connects roads that do not intersect at grade.
print('Road attributes: This is a ramp.');
}
if (roadAttributes.isRightDrivingSide) {
// Indicates if vehicles have to drive on the right-hand side of the road or the left-hand side.
// For example, in New York it is always true and in London always false as the United Kingdom is
// a left-hand driving country.
print("Road attributes: isRightDrivingSide = " + roadAttributes.isRightDrivingSide.toString());
}
if (roadAttributes.isRoundabout) {
// Indicates the presence of a roundabout.
print("Road attributes: This is a roundabout.");
}
if (roadAttributes.isTollway) {
// Identifies a road for which a fee must be paid to use the road.
print("Road attributes change: This is a road with toll costs.");
}
if (roadAttributes.isTunnel) {
// Identifies an enclosed (on all sides) passageway through or under an obstruction.
print("Road attributes: This is a tunnel.");
}
});
// Notifies which lane(s) lead to the next (next) maneuvers.
_visualNavigator.maneuverViewLaneAssistanceListener =
HERE.ManeuverViewLaneAssistanceListener((HERE.ManeuverViewLaneAssistance laneAssistance) {
// Handle events from onLaneAssistanceUpdated().
// This lane list is guaranteed to be non-empty.
List<HERE.Lane> lanes = laneAssistance.lanesForNextManeuver;
logLaneRecommendations(lanes);
List<HERE.Lane> nextLanes = laneAssistance.lanesForNextNextManeuver;
if (nextLanes.isNotEmpty) {
print("Attention, the next next maneuver is very close.");
print("Please take the following lane(s) after the next maneuver: ");
logLaneRecommendations(nextLanes);
}
});
// Notifies which lane(s) allow to follow the route.
_visualNavigator.junctionViewLaneAssistanceListener =
HERE.JunctionViewLaneAssistanceListener((HERE.JunctionViewLaneAssistance junctionViewLaneAssistance) {
List<HERE.Lane> lanes = junctionViewLaneAssistance.lanesForNextJunction;
if (lanes.isEmpty) {
_updateMessageState("You have passed the complex junction.");
} else {
_updateMessageState("Attention, a complex junction is ahead.");
logLaneRecommendations(lanes);
}
});
// Notifies truck drivers on road restrictions ahead.
// For example, there can be a bridge ahead not high enough to pass a big truck
// or there can be a road ahead where the weight of the truck is beyond it's permissible weight.
// This event notifies on truck restrictions in general,
// so it will also deliver events, when the transport type was set to a non-truck transport type.
// The given restrictions are based on the HERE database of the road network ahead.
_visualNavigator.truckRestrictionsWarningListener =
HERE.TruckRestrictionsWarningListener((List<HERE.TruckRestrictionWarning> list) {
// The list is guaranteed to be non-empty.
for (HERE.TruckRestrictionWarning truckRestrictionWarning in list) {
if (truckRestrictionWarning.distanceType == HERE.DistanceType.ahead) {
print("TruckRestrictionWarning ahead in: ${truckRestrictionWarning.distanceInMeters} meters.");
} else if (truckRestrictionWarning.distanceType == HERE.DistanceType.passed) {
print("A restriction just passed.");
}
// One of the following restrictions applies ahead, if more restrictions apply at the same time,
// they are part of another TruckRestrictionWarning element contained in the list.
if (truckRestrictionWarning.weightRestriction != null) {
// For now only one weight type (= truck) is exposed.
HERE.WeightRestrictionType type = truckRestrictionWarning.weightRestriction!.type;
int value = truckRestrictionWarning.weightRestriction!.valueInKilograms;
print("TruckRestriction for weight (kg): ${type.toString()}: $value");
}
if (truckRestrictionWarning.dimensionRestriction != null) {
// Can be either a length, width or height restriction of the truck. For example, a height
// restriction can apply for a tunnel. Other possible restrictions are delivered in
// separate TruckRestrictionWarning objects contained in the list, if any.
HERE.DimensionRestrictionType type = truckRestrictionWarning.dimensionRestriction!.type;
int value = truckRestrictionWarning.dimensionRestriction!.valueInCentimeters;
print("TruckRestriction for dimension: ${type.toString()}: $value");
}
}
});
// Notifies whenever any textual attribute of the current road changes, i.e., the current road texts differ
// from the previous one. This can be useful during tracking mode, when no maneuver information is provided.
_visualNavigator.roadTextsListener = HERE.RoadTextsListener((HERE.RoadTexts roadTexts) {
// See _getRoadName() how to get the current road name from the provided RoadTexts.
});}
发布于 2022-04-21 17:03:28
这里的SDK本身不提供任何机制来播放TTS声音。它只提示文本消息,然后可以用来“说话”文本。如果您的应用程序收到了这些提示,那么这是一个与您的TTS实现相关的问题。
如果你使用一个颤振的TTS插件,试着创建一个孤立的例子,听它是否会说任何文字。
设备的设置也可能出现问题。如果有疑问,请在这里执行SDK 示例应用程序:如果设备设置正确,您将听到语音消息。
https://stackoverflow.com/questions/71935811
复制相似问题