1Sa_16:13 Then Samuel took the horn of oil, and anointed him in the midst of his brethren: and THE SPIRIT OF THE LORD CAME UPON DAVID from that day forward. So Samuel rose up, and went to Ramah.
Many people hear the Lord, but do not have a heart to obey and follow Him.
Cain heard the Lord, but rejected God's words. (Gen 4:6-7)
Moses, Peter, Paul, Isaiah, Samuel, David and John heard the voice of the Lord. So did the Israelites, but they perished in the wilderness, because they would not obey the Lord’s voice.
Samuel was taught to discern the Lord's voice by Eli (1 Sam 3:7-10). Later, David was taught to "enquire of the Lord" and discern what God was saying to Him, by Samuel's example.
There is a process in all of our lives to "discern the voice" of the Lord. Part of it is knowing and loving God's word above anything else in this world.
But, Samuel had a heart to love and obey God once the Word of the Lord was revealed to Him.
1Sam 3:7 Now Samuel did not yet know the LORD, NEITHER WAS THE WORD OF THE LORD YET REVEALED UNTO HIM.
1Sam 3:19 And Samuel grew, and the LORD was with him, and DID LET NONE OF HIS WORDS FALL TO THE GROUND. (In other words, he was obedient to the word of the Lord).
David also loved God's Word and was humble (teachable) and he had a "heart after God". If you read Psalm 119, you will get many clues as to why David could hear the Lord's voice and distinguish the Lord's voice from the Adversary's voice.