I want to duplicate an existing animation and bake it with visual transforms applied, something like what the default nla baker does. For simplicity's sake say I need to do this for a single bone. This is how I tried to do it.
sourceAction = bpy.data.actions["myAction"]
action = bpy.data.actions.new("newAction")
fcurves = action.fcurves
poseBone = object.pose.bones["bone"]
bone = object.data.bones["bone"]
curveLocX = fcurves.new('pose.bones["bone"].location', 0, "bone")
curveLocY = fcurves.new('pose.bones["bone"].location', 1, "bone")
curveLocZ = fcurves.new('pose.bones["bone"].location', 2, "bone")
curveRotX = fcurves.new('pose.bones["bone"].rotation_euler', 0, "bone")
curveRotY = fcurves.new('pose.bones["bone"].rotation_euler', 1, "bone")
curveRotZ = fcurves.new('pose.bones["bone"].rotation_euler', 2, "bone")
#iterate through each frame somehow
#get the matrix for current frame
matrix = bone.matrix_local.inverted()*poseBone.matrix
loc = matrix.translation
rot = matrix.to_euler()
curveLocX.keyframe_points.insert(frame, loc.x)
curveLocY.keyframe_points.insert(frame, loc.y)
curveLocZ.keyframe_points.insert(frame, loc.z)
curveRotX.keyframe_points.insert(frame, rot.x)
curveRotY.keyframe_points.insert(frame, rot.y)
curveRotZ.keyframe_points.insert(frame, rot.z)
I'm not sure how to iterate through the frames to get the correct matrix for that frame. Also I'm not sure if there's a better way to get the visual transform channels.