Turtlegraphics with Java
HomeAufgabenDruckenJava-Online

Sound

The Turtle can play different tones. The playTone(frequency, duration) function is used for this purpose. The first parameter determines the tone frequency in Hz, the second parameter the playback duration in milliseconds. Here are some tone frequencies

Tone Frequency Tone Frequency    

h' 494 h'' 988    
a' 440 a'' 880    
g' 392 g'' 784    
f' 349 f'' 698    
e' 330 e'' 660    
d' 294 d'' 588    
c' 262 c'' 524 c''' 1048

These frequencies can be calculated. If you start from a fundamental tone (e.g. a' with f = 440 Hz), you obtain the frequency of the following semitone with the factor 1.05946 and the next whole tone with the factor 1.05946 * 1.05946 ≈ 1.122 (e.g. h' = 440 * 1.122 = 494). The frequencies in the table are rounded.

Why these factors? An octave is divided into twelve semitone steps. (ratio c'' : c' = 2 : 1).
Ein Halbton = 1/12·Oktave, dies entspricht dem Frequenzverhältnis.

 

Example 1: Playing a melody
Here, several notes are to be played in succession. The corresponding tone frequencies are summarised in a list. With a for loop, you can then go through the list and play the tones with the playTone() function.

// ToneEx1.java

import ch.aplu.turtle.*;

public class  ToneEx1
{
  public ToneEx1()
  {
    Turtle = new Turtle();

    int[]f = {262, 294, 330, 349, 392, 392, 392, 440, 440, 440, 440, 392};

    for (int = 0; i < 12; i++)
       t.sound(f[i], 300);
  }

  public static void main(String[] args)
  {
    new ToneEx1();
  }
}
 

Explanations of the programme code:

sound(f[i], 300)
Plays tone with the frequency f[i] for 200 milliseconds

 

Example 2: The Turtle draws a staircase and always plays higher notes. If you want to play a C major scale, you have to pay attention to the semitones between E' and F' and between B' and C''. After 3 whole tones, a semitone follows, then 3 whole tones and a semitone again.

// ToneEx2.java

import ch.aplu.turtle.*;

public class ToneEx2
{
  private Turtle = new Turtle();
  private double = 264;
  private double = 1.059463;

  public ToneEx2()
  {
    t.hideTurtle();
    t.setPos(-100-100);
    for (int = 0; i < 2; i++)
    {
      for (int = 0; j < 3; j++)
      {
        step();
        f = * * r;
        t.sound(f, 300);
        t.sleep(200);

      }
      step();
      f = * r;
      t.sound(f, 300);
        t.sleep(200);
    }
  }

  private void step()
  {
    t.forward(30);
    t.right(90);
    t.forward(30);
    t.left(90);
  }

  public static void main(String[] args)
  {
    new ToneEx2();
  }
}
 
 


Explanations of the programme code:

sound(f, 300)
Plays tone with the frequency f for 300 milliseconds