Wikipedia is basically correct on this one, but doesn’t include the dating or details of the semantic development. It started out as a performer’s variation or improvisation on an existing piece, then a freely chosen tune or improvised prelude, and then, a century or so later, the church sense developed.
From the OED:
2.†a. Music added at the will of the performer to a piece played or sung. Obs.
1565 J. Jewel Replie Hardinges Answeare (1611) 113 This is the plaine song, and may well stand for the ground: the rest is altogether descant and vaine voluntary, and the most part out of tune.
b. A musical piece or movement played or sung spontaneously or of one’s free choice, esp. by way of prelude to a more elaborate piece, song, etc.
1598 J. Florio Worlde of Wordes, Preludio, a proheme in musicke, a voluntary before the song.
c. esp. A piece or solo, usu. consisting of two or more movements, played upon the organ before, during, or after any office of the Church; also, the music for this.
in-voluntary, out-voluntary, those respectively played at the beginning and close of a religious service.
1712 R. Steele Spectator No. 503. ⁋2 Now the Organ was to play a Voluntary, and she..kept time..with some Motion of her Head.