SE450: Midterm Practice: Music Example [3/28] Previous pageContentsNext page

For questions see the homework.

file:music/Music.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
package music;
class Music {
  private static double pitch = 440;
  /** play note at the current pitch for the given duration
      in milliseconds (the initial pitch is A = 440 Hz) */
  public static void play(int duration) {
    System.out.println("play for " + duration/1000.0 + ": " + pitch );
  }
  /** rest for given duration */
  public static void rest(int duration) {
    System.out.println("rest for " + duration/1000.0);
  }
  /** multiply the pitch frequency by the given factor
      (a factor less than one will lower the pitch) */
  public static void scalePitch(double factor) {
    pitch *= factor;
  }
  /** reset the pitch to note A = 440 Hz */
  public static void reset() {
    pitch = 440;
  }
}

file:music/Event.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package music;
interface Event {
  public void play();
}
class Note implements Event {
  int d;
  double f;
  public Note(int duration, double factor) {
    this.d = duration;
    this.f = factor;
  }
  public void play() {
    Music.scalePitch(f);
    Music.play(d);
    Music.scalePitch(1.0/f);
  }
}
class Rest implements Event {
  int d;
  public Rest(int duration) {
    d = duration;
  }
  public void play() {
    Music.rest(d);
  }
}

file:music/EventGroup.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
package music;
import java.util.List;
import java.util.LinkedList;
class EventGroup implements Event {
  List<Event> events = new LinkedList<Event>();
  public void add(Event e) {
    events.add(e);
  }

  public void play() {
    for (Event e : events) {
      e.play();
    }
  }
}

file:music/Transpose.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
package music;
class Transpose implements Event {
  Event e;
  double f;
  public Transpose(Event e, double factor) {
    this.e = e;
    this.f = factor;
  }
  public void play() {
    Music.scalePitch(f);
    e.play();
    Music.scalePitch(1.0/f);
  }
}

file:music/Main.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
package music;
class Main {
  public static void main(String[] args) {
    EventGroup eg1 = new EventGroup();
    eg1.add(new Note(250, 2.0));
    eg1.add(new Rest(250));
    eg1.add(new Note(500, 1.0));
    eg1.add(new Rest(500));
    eg1.add(new Note(1000, 0.5));

    EventGroup eg2 = new EventGroup();
    eg2.add(eg1);
    eg1.add(new Rest(1000));
    eg2.add(new Transpose(eg1, 2.0));

    eg2.play();
  }
}

Previous pageContentsNext page