Need Help with Piezo Buzzer and Ultrasonic Sensor code

Sure, that sounds like a good idea.
You can use a delay that is changed with distance.
Look into blink without delay examples.