Simply, because it makes NBA games more fun to watch.
There are times during a basketball game when the arena DJ feels that the crowd is zoning out or is getting bored because the style of play has slowed, so they decide to try and bring back the energy in the fans. Other times, right before clutch possessions, the DJ wants to get the fans loud and the players on the floor hype.
Other times, music is used to go with what's happening on the court. For example in Toronto, when a nice assist is made, Drake's voice is heard on the speakers singing "I was running through the six with my..." and the crowd finishes with "woes." Just another example of how music is used to enhance the fan experience.
To answer if this distracts the players, I wouldn't say so. Players have become so used to playing in arenas in front of thousands of screaming fans since college that it's easy for them to block out the surrounding noise, especially when they're so focused on the task of scoring the ball. In addition, it's against the rules to play music when referees are assessing a call or during free throws, so the game isn't affected that way.
In regards to the other sports, music isn't played during periods at hockey games because the action is already intense enough: there's no need to engage the fans when they're already at the edge of their seats. In baseball it's the opposite; the whole point of the fan experience is to relax, drink a beer and watch a lot of balls being thrown but few being hit. No need to wake the sleeping fans up.