Seal any openings around the edges of the window using caulking. Make sure there is no air draft around the window; where air gets through, sound also gets through. If the window is already well-sealed, you may skip this step.
Measure the height and width of the window frame. Be as precise as possible.
Use a blade to cut your foam to the exact dimensions of the window frame. Again, be as precise as possible, and cut as straight as possible. The goal here is to plug the window frame completely with the foam, so it must fit snugly.
Insert the foam into the window frame, leaving as much space as possible between the foam and the windowpane. Do not put the foam flush against the window; the air pocket between them forms an additional sound barrier. Make sure the foam fits snugly in the frame.
Use adhesive glue or strong adhesive tape to seal around the edges of the foam. This is an optional step, but provides added sound dampening. The idea is to treat the foam as if it were now the window, and use the glue or tape to "caulk" the edges. Glue is permanent; tape is less so. If you need to be able to remove the foam, you may skip this step as long as the foam is very snug in the window frame, with no gaps.