2020 Swift
Swan’s Quest, Chapter 2: A time for tones
Swift Playgrounds presents "Swan’s Quest,” an interactive adventure in four chapters for all ages. In this chapter, our Hero needs your help decoding the Swan’s scroll. Call forth the best of your audio abilities on this one — you’re going to need them. Discover how to convert Swift Playgrounds into a tone generator, and you just might help our Hero find the missing message… and move onto the next part of their quest. Swan’s Quest was created for Swift Playgrounds on iPad and Mac, combining frameworks and resources which power the educational experiences in many of our playgrounds, including Sonic Workshop, Sensor Arcade, and Augmented Reality. To learn more about building your own playgrounds, be sure to watch "Create Swift Playgrounds content for iPad and Mac". And don’t forget to stop by the Developer Forums and share your solution for our side quest.
Watch at developer.apple.com ↗Code shown on screen · 5 snippets
ToneOutput.swift
// ToneOutput.swift
public class ToneOutput : AURenderCallbackDelegate {
let sampleRate = 44100.0
public func play(tone: Tone) { /**/ }
public func stopTones() { /**/ }
// ...
} Inside the Tone type
// ToneOutput.swift
public struct Tone: Codable {
public var pitch: Double
public var volume: Double
// ...
} Play a middle A
// Play a middle A
import SPCAudio
let toneOutput = ToneOutput()
let middleA = Tone(pitch: 440.0, volume: 0.3)
toneOutput.play(tone: middleA) Play a middle A for 0.5 seconds
// Play a middle A
import SPCAudio
let toneOutput = ToneOutput()
let a4 = Tone(pitch: 440.0, volume: 0.3)
toneOutput.play(tone: a4)
DispatchQueue.main.asyncAfter(deadline: .now() + DispatchTimeInterval.milliseconds(400)) {
toneOutput.stopTones()
} Play more than one tone
// Play more than one tone
let toneOutput = ToneOutput()
let tones = [
Tone(pitch: 440.00, volume: 0.3),
Tone(pitch: 493.88, volume: 0.3),
Tone(pitch: 523.25, volume: 0.3)
]
var toneIndex = 0
Timer.scheduledTimer(withTimeInterval: 0.4, repeats: true) { timer in
guard toneIndex < tones.count else {
toneOutput.stopTones()
timer.invalidate()
owner.endPerformance()
return
}
toneOutput.play(tone: tones[toneIndex])
toneIndex += 1
} Resources
Related sessions
-
14 min -
8 min -
15 min -
6 min -
8 min