Construct the following circuit:

Here is the code for the pitch-controlled version:

// Pins
const int trig_pin = 7;
const int pw_pin = 7;
const int trig_delay = 5;
const int speaker_pin = 9;

void setup() {
  pinMode(speaker_pin, OUTPUT);
}

void loop() {

  // Find the distance
  float dist = measureDistance(); // In cm
  
  // Map to a frequency and play it
  float freq = 14.003 * dist - 15.01;
  tone(speaker_pin, freq);
  
  delay(100);
}

float measureDistance() {
  
  long duration;

  // Tell distance sensor to send a pulse
  pinMode(trig_pin, OUTPUT);
  digitalWrite(trig_pin, LOW);
  delayMicroseconds(10);
  digitalWrite(trig_pin, HIGH);
  delayMicroseconds(trig_delay);
  digitalWrite(trig_pin, LOW);

  // Measure time of pulse on PW pin
  pinMode(pw_pin, INPUT);
  duration = pulseIn(pw_pin, HIGH);

  // Convert time to distance
  return duration / 58.8;
}

Simulator: https://tinkercad.com/things/7sKjYIheGbR