The only time this has happened to me is with a certain set of headphones. This particular set covers the ears, but is lightweight and sounds good, yet will allow sound from around me to get through. So I really wanted to use this set for my phone.
It may be that the heaphone plug is a micron out of size, an impedence mismatch (the speakers and the device internals are a poor match electrically), or something else I haven't thought of.
The headphones that do this work great in other things I plug them into, but when plugged into a phone the volume goes bananas just as you describe. I have seen Google Assistant turn on, the music app quit and start, or change songs, and other annoying things.
It seems that when I wiggle the jack is when it occurs most often, although it also happens just by bending the cord near the end sometimes. Sometimes I don't know what sets it off.
It only happens with one headphone set, and that set has a three section plug- two plastic bands dividing up the metal segments of the plug.
I have other sets of headphones that work just fine in the same phone.
Some have three section plugs, others have two section plugs.
The extra segment on the three segment plugs is for a microphone.
I don't know if this has anything to do with it, as I have another set with the same set-up that works fine.
My guess is that the end of the cord is worn, probably internally so that it is not visable damage, and this is causing either a temporary short circuit or a temporary break in the connection. This can cause all sorts of things on a device like a phone.
If it is happening with a cheap set of headphones, try a better quality set. ($10-$20 USD)
If it is happening with a high quality set of headphones, then try a cheap set. ($5-$10 USD)
If both are doing it, then possibly the jack on the device is misaligned internally.