These sorts of questions pop up pretty commonly and they all share an underlying misconception of how war was fought. More simply I imagine you are forcing a modern concept of how war is fought and applying it back in time wholesale. We look at war as it is fought in the late 20th and 21st centuries and we see a style which is focused on low level initiative, small unit tactics, infiltration and deception, so on and so forth. There is so much sheer firepower now and throughout the 20th century that masking ones position provides more use than making ones position clear. Even more so much firepower ensures that the men to hold, say, a mile front, is a fraction of what was necessary prior. A platoon in 2015 can hold what required a company was needed for in 1915 and a company in 1915 could hold what an entire battalion was needed for in 1815.
So this brings is right back to the point: Why did armies play music? Because war had a significantly lesser threshold of dying 'in yesteryear'; the firepower was not nearly as potent. In fact the firepower of musketry was more useful in creating a bunch of smoke and noise to scare the piss out of the enemy than the actual killing it provided. As the 18th century in particular developed we see the bayonet being the decisive tool with the musket itself being the support rather than what you would imagine it being in the opposite way round.
So here we are in the 18th or early 19th centuries. We have tens of thousands of men on a battlefield and they're all shooting the loudest guns you've ever heard. I don't even know how to compare it to someone who has never heard a smoothbore musket fired -- it's louder than any modern gun you've ever heard by a mile. Try shooting a shotgun indoors and that'll give you an idea. With this noise and a crap ton of smoke comes a mass amount of potential confusion. Doubling this confusion is the fact that most men who made up ranks in armies are, to be frank, the dregs of society. Criminals in particular along with forced conscripts. They require strict drill and order to not fall into chaos.
Thus in the loudest battlefields ever up to that point with the most men on the fields in history (at times hundreds of thousands in the Napoleonic Wars) the best marker for keeping men in track is an even closer and louder noise along with bright colors. They're wearing bright red, we're reading blue with white trousers. We know who is who in the smokey chaos. In general, and this is the TL;DR: music was used to make an audible sign of pacing. In otherwords men march to the beat. It's very hard to get a bunch of rabble to march lockstep but if they're taught to march to the beat as the beat picks up so does their pace. As the beat slows down as do they. It's a very intuitive way of keeping men in line actually.