The best way to learn this is by doing. Take a very familiar melody and try to figure out chords that work. Start with something simple like "Happy Birthday". The melody starts on the dominant note of whatever key you're in. (For example, if you're in C major, the melody starts on G.) The first chord of a piece of music in a major key is usually the I
chord. No exception here. Happy Birthday can be done with just the I
, IV
, and V7
chords. If you do the work of experimenting around, you'll probably come up with this:
I V7 V7 I
Happy birthday to you. Happy birthday to you.
I IV
Happy birthday dear person.
I V7 I
Happy birthday to you.
This isn't the only right answer, of course. It could potentially be this:
I iii V7 I
Happy birthday to you. Happy birthday to you.
vi7 ii6
Happy birthday dear person.
iv6 I vii° I
Happy birthday to you.
...or any number of variations. (Note the 6s are meant to indicate 6th chords, not 1st inversion.) It's a skill that comes with practice. Do so by trying to figure out the chord progressions of songs you like. A great deal of music has been analyzed and can be found online. If you're stumped on a particular chord, you can look it up. You can also check your work against it (knowing that what you find online is sometimes wrong).
When it comes to composing your own music, there is no established harmony for your melody, so you can try different chords until you find a progression which both fits the melody and is pleasing to you. (Remember music is an art form and there is a lot of subjectivity to it.) Another way to go about it is to come up with a chord progression first and then improvise a melody over it.
If you do this enough, you'll find that progressions commonly fall into these formulas.
Major - Start with I, go to any other chord and jump in:
┌──>── I ──>───┐
iii ─> vi ─> [ii or IV] ─> [V or vii°] ─> I ─> any chord
└────────────────<──────────────────┘
Minor - Start with i, go to any other chord and jump in:
VII ─> III ─> VI ─> [ii° or iv] ─> [V or vii°] ─> i ─> any chord
└────────────────<───────────────┘
Notice the first version of "Happy Birthday" falls into the formula for major keys. It begins with I
, goes to any, which happens to be V
, which leads back to I
. I
goes to any, which is IV
this time. It takes the upper path from IV
to I
to V
and lands back at I
. It's not always this simple, of course, but this is the basis of a lot of music.