How can I set the tangents of Keyframes in an AnimationCurve through scripting?

I want to set both tangents of a Keyframe in an AnimationCurve through scripting, just like it is possible to do in the Animation view in Unity. How can I do it in code?

If you have an AnimationCurve called myAnimationCurve, you can get a Keyframe from this curve and set the tangents of that Keyframe like this:

// Get the fourth key in the curve
Keyframe key = myAnimationCurve[3];

// Set both tangents to something
key.inTangent = 1;
key.outTangent = 0;

// Put the modified key back into the curve
myAnimationCurve.MoveKey(3, key);

You can also smooth out the tangents of a Keyframe by using SmoothTangents on the AnimationCurve:

// Smooth the tangents of the fourth key in the curve
myAnimationCurve.SmoothTangents(3, 0);

The second parameter, weight, controls the contribution of the two tangents in the smoothed result. -1 makes the smooth result equal to what the inTangent was before; 1 makes it equal to what the outTangent was, and 0 produces an average.

Ok, this is epic @runevision