How to control the volume of a buzzer while using the tone() function?

To do that, I will need to modify the code.

what makes you sure or think that code could change the volume when you use tone()?

Messing around with duty cycle could do but it’s limited and depends really on how your buzzer is built.

It's connected to pin 9, which is PWM???

Does tone allows you to modify the duty cycle?

Have a look here (never used it)

There is a family of Arduino libraries that can be used to control volume:

There is a table at the bottom of the readme that compares them.

I've used all three with success, but unfortunately there is a bug in arduino-volume2, so if you want to use arduino-volume2, I recommend you use this modified version of the library that has the bug fixed:
https://github.com/per1234/arduino-volume2/archive/volatile-toneMillis.zip

pert:
There is a family of Arduino libraries that can be used to control volume:
GitHub - connornishijima/arduino-volume1: Arduino tone() just got 8-bit volume control - with no extra components!
GitHub - connornishijima/arduino-volume2: Arduino tone() - with multiple waveforms and 8-bit volume control using only a speaker!
GitHub - connornishijima/arduino-volume3: Gives tone functionality with 10-bit volume control with no extra parts!
There is a table at the bottom of the readme that compares them.

I've used all three with success, but unfortunately there is a bug in arduino-volume2, so if you want to use arduino-volume2, I recommend you use this modified version of the library that has the bug fixed:
https://github.com/per1234/arduino-volume2/archive/volatile-toneMillis.zip

Thank you very much for those libraries!

You're welcome. I'm glad if I was able to be of assistance. Enjoy!
Per