-
-
Save faiface/d701781da1d65617ab1d75a1bb2a0462 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"math" | |
"time" | |
"github.com/faiface/pixel" | |
"github.com/faiface/pixel/audio" | |
"github.com/faiface/pixel/audio/speaker" | |
"github.com/faiface/pixel/pixelgl" | |
) | |
func sin(freq, volume float64) audio.Streamer { | |
t := 0.0 | |
dt := 1.0 / audio.SampleRate | |
return audio.StreamerFunc(func(samples [][2]float64) (n int, ok bool) { | |
for i := range samples { | |
val := math.Sin(math.Pi*freq*t) * volume | |
samples[i][0] = val | |
samples[i][1] = val | |
t += dt | |
} | |
return len(samples), true | |
}) | |
} | |
func run() { | |
speaker.Init(time.Second / 20) | |
go func() { | |
for { | |
speaker.Update() | |
} | |
}() | |
cfg := pixelgl.WindowConfig{ | |
Title: "Piano", | |
Bounds: pixel.R(0, 0, 800, 600), | |
VSync: true, | |
} | |
win, err := pixelgl.NewWindow(cfg) | |
if err != nil { | |
panic(err) | |
} | |
keysTones := map[pixelgl.Button]float64{ | |
pixelgl.KeyA: 523.25, | |
pixelgl.KeyS: 554.37, | |
pixelgl.KeyD: 587.33, | |
pixelgl.KeyF: 622.25, | |
pixelgl.KeyG: 659.25, | |
pixelgl.KeyH: 698.46, | |
pixelgl.KeyJ: 739.99, | |
pixelgl.KeyK: 783.99, | |
pixelgl.KeyL: 830.61, | |
} | |
prevKey := pixelgl.Button(-1) | |
for !win.Closed() { | |
newKey := pixelgl.Button(-1) | |
for key := range keysTones { | |
if win.Pressed(key) { | |
newKey = key | |
} | |
} | |
if prevKey != newKey { | |
if newKey == -1 { | |
speaker.Play(nil) | |
} else { | |
speaker.Play(sin(keysTones[newKey], 0.3)) | |
} | |
prevKey = newKey | |
} | |
win.Update() | |
} | |
} | |
func main() { | |
pixelgl.Run(run) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment