Morph subclass: #LSStepSequencer instanceVariableNames: 'pattern tempo playhead playing audioEnabled nextTick status stage' classVariableNames: '' poolDictionaries: '' category: 'LearnSqueak-Sequencer'! !LSStepSequencer class methodsFor: 'tutorial'! open ^ self new openInWorld ! ! !LSStepSequencer methodsFor: 'tutorial'! initialize super initialize. self color: (Color r: 0.08 g: 0.11 b: 0.17); extent: 820@450. pattern := (1 to: 4) collect: [:row | Array new: 16 withAll: false]. tempo := 120. playhead := 0. playing := false. audioEnabled := false. status := 'Ready. Sound is off; enable it explicitly.'. stage := 9. self installButtons ! ! !LSStepSequencer methodsFor: 'tutorial'! installButtons self submorphs do: [:each | each delete]. stage >= 5 ifTrue: [self button: 'Play / pause' action: #togglePlay x: 25. self button: 'Reset' action: #resetPlayhead x: 145]. stage >= 6 ifTrue: [self button: 'Tempo -' action: #slower x: 235. self button: 'Tempo +' action: #faster x: 325]. stage >= 7 ifTrue: [self button: 'Sound on/off' action: #toggleAudio x: 415]. stage >= 8 ifTrue: [self button: 'Save new' action: #saveDialog x: 540. self button: 'Load' action: #loadDialog x: 645]. stage >= 9 ifTrue: [self button: 'Clear' action: #clearPattern x: 725] ! ! !LSStepSequencer methodsFor: 'tutorial'! button: label action: selector x: x | b | b := SimpleButtonMorph new label: label; target: self; actionSelector: selector; yourself. b position: self position + (x@380). self addMorph: b ! ! !LSStepSequencer methodsFor: 'tutorial'! stage: number stage := number. self installButtons; changed. ^ self ! ! !LSStepSequencer methodsFor: 'tutorial'! drawOn: canvas | origin box textColor | super drawOn: canvas. origin := self position. textColor := Color white. canvas drawString: 'STEP SEQUENCER / 4 NOTES x 16 STEPS' at: origin + (25@22) font: (TextStyle defaultFont) color: textColor. canvas drawString: ('Tempo: ', tempo printString, ' BPM Step: ', playhead printString, ' Sound: ', audioEnabled printString) at: origin + (25@54) font: TextStyle defaultFont color: Color lightGray. stage >= 2 ifTrue: [1 to: 4 do: [:r | canvas drawString: (#('C4 / A' 'D4 / S' 'E4 / D' 'G4 / F') at: r) at: origin + (22@(115 + ((r-1)*52))) font: TextStyle defaultFont color: textColor. 1 to: 16 do: [:c | box := self cellAtRow: r column: c. canvas fillRectangle: box color: (((pattern at: r) at: c) ifTrue: [Color r: 0.15 g: 0.7 b: 0.65] ifFalse: [Color r: 0.2 g: 0.25 b: 0.34]). c = playhead ifTrue: [canvas frameRectangle: box width: 3 color: Color yellow]]]]. stage >= 4 ifTrue: [1 to: 4 do: [:r | box := self keyAt: r. canvas fillRectangle: box color: Color veryLightGray. canvas drawString: (#('C4 (A)' 'D4 (S)' 'E4 (D)' 'G4 (F)') at: r) at: box origin + (30@10) font: TextStyle defaultFont color: Color black]]. canvas drawString: status at: origin + (25@425) font: TextStyle defaultFont color: textColor ! ! !LSStepSequencer methodsFor: 'tutorial'! cellAtRow: row column: column ^ (self position + ((120 + ((column-1)*41))@(102 + ((row-1)*52)))) extent: 35@42 ! ! !LSStepSequencer methodsFor: 'tutorial'! keyAt: row ^ (self position + ((120 + ((row-1)*155))@322)) extent: 145@38 ! ! !LSStepSequencer methodsFor: 'tutorial'! handlesMouseDown: event ^ true ! ! !LSStepSequencer methodsFor: 'tutorial'! mouseDown: event event hand newKeyboardFocus: self. stage >= 3 ifTrue: [1 to: 4 do: [:r | 1 to: 16 do: [:c | ((self cellAtRow: r column: c) containsPoint: event position) ifTrue: [self toggleRow: r column: c. ^ self]]]]. stage >= 4 ifTrue: [1 to: 4 do: [:r | ((self keyAt: r) containsPoint: event position) ifTrue: [self playNote: r. ^ self]]] ! ! !LSStepSequencer methodsFor: 'tutorial'! handlesKeyboard: event ^ true ! ! !LSStepSequencer methodsFor: 'tutorial'! keyStroke: event | index | stage < 4 ifTrue: [^ self]. index := 'asdf' indexOf: event keyCharacter asLowercase. index > 0 ifTrue: [self playNote: index] ! ! !LSStepSequencer methodsFor: 'tutorial'! toggleRow: row column: column (row between: 1 and: 4) & (column between: 1 and: 16) ifFalse: [self error: 'Cell outside pattern']. (pattern at: row) at: column put: ((pattern at: row) at: column) not. status := 'Pattern edited. Each column is a sixteenth note'. self changed ! ! !LSStepSequencer methodsFor: 'tutorial'! samplesForNote: note | samples frequency rate count | (note between: 1 and: 4) ifFalse: [self error: 'Note outside keyboard']. rate := 22050. count := 3308. frequency := #(261.6256 293.6648 329.6276 391.9954) at: note. samples := SoundBuffer newMonoSampleCount: count. 1 to: count do: [:i | | envelope | envelope := (i / 150.0 min: 1.0) * (1.0 - (i / count)). samples at: i put: ((Float pi * 2 * frequency * i / rate) sin * envelope * 6000) rounded]. ^ samples ! ! !LSStepSequencer methodsFor: 'tutorial'! playNote: note | sound | status := 'Note ', note printString, (audioEnabled ifTrue: [' played'] ifFalse: [' selected (sound off)']). audioEnabled ifTrue: [sound := SampledSound samples: (self samplesForNote: note) samplingRate: 22050. sound play]. self changed ! ! !LSStepSequencer methodsFor: 'tutorial'! toggleAudio audioEnabled := audioEnabled not. status := audioEnabled ifTrue: ['Sound enabled. Lower device volume before playing.'] ifFalse: ['Sound off. Previously started notes decay in 150 ms.']. self changed ! ! !LSStepSequencer methodsFor: 'tutorial'! togglePlay playing := playing not. playing ifTrue: [nextTick := Time millisecondClockValue. self advance. self startStepping] ifFalse: [self stopStepping]. self changed ! ! !LSStepSequencer methodsFor: 'tutorial'! stepTime ^ 15 ! ! !LSStepSequencer methodsFor: 'tutorial'! step playing ifFalse: [^ self]. (Time millisecondsSince: nextTick) >= self tickMilliseconds ifTrue: [ self advance. nextTick := Time millisecondClockValue] ! ! !LSStepSequencer methodsFor: 'tutorial'! tickMilliseconds ^ (15000 / tempo) rounded ! ! !LSStepSequencer methodsFor: 'tutorial'! advance playhead := playhead = 16 ifTrue: [1] ifFalse: [playhead + 1]. 1 to: 4 do: [:r | ((pattern at: r) at: playhead) ifTrue: [self playNote: r]]. self changed ! ! !LSStepSequencer methodsFor: 'tutorial'! tempo: number ((number isInteger) and: [number between: 40 and: 240]) ifFalse: [self error: 'Tempo must be an integer from 40 to 240']. tempo := number. self changed ! ! !LSStepSequencer methodsFor: 'tutorial'! slower self tempo: (tempo - 10 max: 40) ! ! !LSStepSequencer methodsFor: 'tutorial'! faster self tempo: (tempo + 10 min: 240) ! ! !LSStepSequencer methodsFor: 'tutorial'! resetPlayhead playing := false. playhead := 0. self stopStepping; changed ! ! !LSStepSequencer methodsFor: 'tutorial'! clearPattern self resetPlayhead. pattern do: [:row | row atAllPut: false]. status := 'Pattern cleared'. self changed ! ! !LSStepSequencer methodsFor: 'tutorial'! pattern ^ pattern collect: [:row | row copy] ! ! !LSStepSequencer methodsFor: 'tutorial'! tempo ^ tempo ! ! !LSStepSequencer methodsFor: 'tutorial'! playing ^ playing ! ! !LSStepSequencer methodsFor: 'tutorial'! playhead ^ playhead ! ! !LSStepSequencer methodsFor: 'tutorial'! audioEnabled ^ audioEnabled ! ! !LSStepSequencer methodsFor: 'tutorial'! status ^ status ! ! !LSStepSequencer methodsFor: 'tutorial'! patternText ^ Json render: {tempo. pattern} ! ! !LSStepSequencer methodsFor: 'tutorial'! validatePatternText: text | tokens depth | tokens := text findTokens: ('[], ', String crlf, (String with: Character tab)). tokens do: [:token | (#('true' 'false') includes: token) ifFalse: [ (token size <= 3 and: [token allSatisfy: [:ch | ch isDigit]]) ifFalse: [self error: 'Pattern accepts only a small integer tempo and Boolean cells']]]. depth := 0. text do: [:ch | ch = $[ ifTrue: [depth := depth+1. depth > 3 ifTrue: [self error: 'Pattern nesting exceeds three arrays']]. ch = $] ifTrue: [depth := depth-1]]. ^ true ! ! !LSStepSequencer methodsFor: 'tutorial'! loadText: text | data rows newTempo | text size > 8192 ifTrue: [self error: 'Pattern file too large']. self validatePatternText: text. data := Json readFromString: text. ((data isArray) and: [data size = 2]) ifFalse: [self error: 'Expected tempo and rows']. newTempo := data first. rows := data second. ((newTempo isInteger) and: [newTempo between: 40 and: 240]) ifFalse: [self error: 'Invalid tempo']. ((rows isArray) and: [rows size = 4 and: [rows allSatisfy: [:row | row isArray and: [row size = 16 and: [row allSatisfy: [:v | v == true or: [v == false]]]]]]]) ifFalse: [self error: 'Expected 4 by 16 Boolean cells']. self resetPlayhead. tempo := newTempo. pattern := rows collect: [:row | row copy]. status := 'Pattern loaded. Playback remains stopped'. self changed ! ! !LSStepSequencer methodsFor: 'tutorial'! saveNewTo: path | stream | (FileDirectory default fileExists: path) ifTrue: [self error: 'File already exists; choose a new name']. stream := FileStream newFileNamed: path. [stream nextPutAll: self patternText] ensure: [stream close]. status := 'Saved pattern to a new file'. self changed ! ! !LSStepSequencer methodsFor: 'tutorial'! loadFrom: path | stream text | stream := FileStream readOnlyFileNamed: path. [stream size > 8192 ifTrue: [self error: 'Pattern file too large']. text := stream contentsOfEntireFile] ensure: [stream close]. self loadText: text ! ! !LSStepSequencer methodsFor: 'tutorial'! saveDialog | path | path := UIManager default request: 'Save NEW pattern file (existing files are refused)' initialAnswer: 'my-pattern.json'. path isEmpty ifTrue: [^ self]. [self saveNewTo: path] on: Error do: [:e | status := e messageText. self changed] ! ! !LSStepSequencer methodsFor: 'tutorial'! loadDialog | path | path := UIManager default request: 'Load a pattern created by this tutorial' initialAnswer: 'my-pattern.json'. path isEmpty ifTrue: [^ self]. [self loadFrom: path] on: Error do: [:e | status := e messageText. self changed] ! ! !LSStepSequencer methodsFor: 'tutorial'! delete self resetPlayhead. World hands do: [:hand | hand keyboardFocus == self ifTrue: [hand newKeyboardFocus: nil]]. super delete ! ! !LSStepSequencer methodsFor: 'tutorial'! renderSamples "One loop, including release tails. Same notes as interactive playback." | output length spacing samples | spacing := (22050 * 15 / tempo) rounded. length := spacing * 16 + 3308. output := SoundBuffer newMonoSampleCount: length. 1 to: 16 do: [:c | 1 to: 4 do: [:r | ((pattern at: r) at: c) ifTrue: [samples := self samplesForNote: r. 1 to: samples monoSampleCount do: [:i | | index value | index := ((c-1)*spacing)+i. value := (output at: index) + (samples at: i). output at: index put: ((value max: -32767) min: 32767)]]]]. ^ output ! ! !LSStepSequencer methodsFor: 'tutorial'! writeWAVNewTo: path | samples stream le | (FileDirectory default fileExists: path) ifTrue: [self error: 'Choose a new file name']. samples := self renderSamples. stream := (FileStream newFileNamed: path) binary. le := [:number :bytes | 0 to: bytes-1 do: [:i | stream nextPut: ((number bitShift: i * -8) bitAnd: 255)]]. [stream nextPutAll: 'RIFF' asByteArray. le value: 36 + (samples monoSampleCount*2) value: 4. stream nextPutAll: 'WAVEfmt ' asByteArray. le value: 16 value: 4. le value: 1 value: 2. le value: 1 value: 2. le value: 22050 value: 4. le value: 44100 value: 4. le value: 2 value: 2. le value: 16 value: 2. stream nextPutAll: 'data' asByteArray. le value: samples monoSampleCount*2 value: 4. 1 to: samples monoSampleCount do: [:i | le value: ((samples at: i) bitAnd: 65535) value: 2]] ensure: [stream close] ! !