ebiten/examples/piano/main.go

263 lines
5.7 KiB
Go
Raw Normal View History

2015-01-25 16:09:14 +01:00
// Copyright 2015 Hajime Hoshi
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// +build example
2015-01-25 16:09:14 +01:00
package main
import (
"fmt"
"image/color"
"io/ioutil"
"log"
"math"
"github.com/golang/freetype/truetype"
"golang.org/x/image/font"
2015-01-25 16:09:14 +01:00
"github.com/hajimehoshi/ebiten"
2016-04-18 18:24:44 +02:00
"github.com/hajimehoshi/ebiten/audio"
2015-01-25 16:09:14 +01:00
"github.com/hajimehoshi/ebiten/ebitenutil"
"github.com/hajimehoshi/ebiten/text"
)
var (
arcadeFont font.Face
)
func init() {
f, err := ebitenutil.OpenFile("_resources/fonts/arcade_n.ttf")
if err != nil {
log.Fatal(err)
}
defer f.Close()
b, err := ioutil.ReadAll(f)
if err != nil {
log.Fatal(err)
}
tt, err := truetype.Parse(b)
if err != nil {
log.Fatal(err)
}
2018-01-29 18:54:34 +01:00
const (
arcadeFontSize = 8
dpi = 72
)
arcadeFont = truetype.NewFace(tt, &truetype.Options{
Size: arcadeFontSize,
DPI: dpi,
Hinting: font.HintingFull,
})
}
2015-01-25 16:09:14 +01:00
const (
screenWidth = 320
screenHeight = 240
2016-02-09 15:04:00 +01:00
sampleRate = 44100
2018-01-29 18:54:34 +01:00
baseFreq = 220
2015-01-25 16:09:14 +01:00
)
2016-03-02 16:48:59 +01:00
var audioContext *audio.Context
func init() {
var err error
audioContext, err = audio.NewContext(sampleRate)
if err != nil {
log.Fatal(err)
}
2016-03-02 16:48:59 +01:00
}
2018-01-29 18:54:34 +01:00
// pianoAt returns an i-th sample of piano with the given frequency.
func pianoAt(i int, freq float64) float64 {
// Create piano-like waves with multiple sin waves.
2015-01-25 16:09:14 +01:00
amp := []float64{1.0, 0.8, 0.6, 0.4, 0.2}
x := []float64{4.0, 2.0, 1.0, 0.5, 0.25}
2018-01-29 18:54:34 +01:00
v := 0.0
for j := 0; j < len(amp); j++ {
// Decay
a := amp[j] * math.Exp(-5*float64(i)*freq/baseFreq/(x[j]*sampleRate))
v += a * math.Sin(2.0*math.Pi*float64(i)*freq*float64(j+1)/sampleRate)
2015-01-25 16:09:14 +01:00
}
2018-01-29 18:54:34 +01:00
return v / 5.0
2015-01-25 16:09:14 +01:00
}
2018-01-29 18:54:34 +01:00
// toBytes returns the 2ch little endian 16bit byte sequence with the given left/right sequence.
func toBytes(l, r []int16) []byte {
if len(l) != len(r) {
panic("len(l) must equal to len(r)")
}
2015-06-13 20:27:02 +02:00
b := make([]byte, len(l)*4)
2016-05-13 17:25:11 +02:00
for i := range l {
2015-06-13 20:27:02 +02:00
b[4*i] = byte(l[i])
b[4*i+1] = byte(l[i] >> 8)
b[4*i+2] = byte(r[i])
b[4*i+3] = byte(r[i] >> 8)
}
2015-06-13 20:27:02 +02:00
return b
}
2018-01-29 18:54:34 +01:00
var (
pianoNoteSamples = map[int][]byte{}
pianoNoteSamplesInited = false
pianoNoteSamplesInitCh = make(chan struct{})
)
2015-01-25 16:09:14 +01:00
2018-01-29 18:54:34 +01:00
func init() {
// Initialize piano data.
// This takes a little long time (especially on browsers),
// so run this asynchronously and notice the progress.
go func() {
// Create a reference data and use this for other frequency.
const refFreq = 110
length := 4 * sampleRate * baseFreq / refFreq
refData := make([]int16, length)
for i := 0; i < length; i++ {
refData[i] = int16(pianoAt(i, refFreq) * math.MaxInt16)
}
2015-01-25 16:09:14 +01:00
2018-01-29 18:54:34 +01:00
for i := range keys {
freq := baseFreq * math.Exp2(float64(i-1)/12.0)
2015-01-25 16:09:14 +01:00
2018-01-29 18:54:34 +01:00
// Clculate the wave data for the freq.
length := 4 * sampleRate * baseFreq / int(freq)
l := make([]int16, length)
r := make([]int16, length)
for i := 0; i < length; i++ {
idx := int(float64(i) * freq / refFreq)
if len(refData) <= idx {
break
}
l[i] = refData[idx]
}
copy(r, l)
n := toBytes(l, r)
pianoNoteSamples[int(freq)] = n
}
close(pianoNoteSamplesInitCh)
}()
2015-01-25 16:09:14 +01:00
}
2018-01-29 18:54:34 +01:00
// playNote plays piano sound with the given frequency.
func playNote(freq float64) {
f := int(freq)
p, _ := audio.NewPlayerFromBytes(audioContext, pianoNoteSamples[f])
p.Play()
2015-01-25 16:09:14 +01:00
}
var (
2018-01-29 18:54:34 +01:00
pianoImage *ebiten.Image
)
2015-01-28 19:22:36 +01:00
2015-02-16 02:33:27 +01:00
func init() {
2018-01-29 18:54:34 +01:00
pianoImage, _ = ebiten.NewImage(screenWidth, screenHeight, ebiten.FilterNearest)
const (
keyWidth = 24
y = 48
)
2015-01-28 19:22:36 +01:00
whiteKeys := []string{"A", "S", "D", "F", "G", "H", "J", "K", "L"}
for i, k := range whiteKeys {
2018-01-29 18:54:34 +01:00
x := i*keyWidth + 36
2015-01-28 19:22:36 +01:00
height := 112
2018-01-29 18:54:34 +01:00
ebitenutil.DrawRect(pianoImage, float64(x), float64(y), float64(keyWidth-1), float64(height), color.White)
text.Draw(pianoImage, k, arcadeFont, x+8, y+height-8, color.Black)
2015-01-28 19:22:36 +01:00
}
blackKeys := []string{"Q", "W", "", "R", "T", "", "U", "I", "O"}
for i, k := range blackKeys {
if k == "" {
continue
}
2018-01-29 18:54:34 +01:00
x := i*keyWidth + 24
2015-01-28 19:22:36 +01:00
height := 64
2018-01-29 18:54:34 +01:00
ebitenutil.DrawRect(pianoImage, float64(x), float64(y), float64(keyWidth-1), float64(height), color.Black)
text.Draw(pianoImage, k, arcadeFont, x+8, y+height-8, color.White)
2015-01-28 19:22:36 +01:00
}
2015-02-16 02:33:27 +01:00
}
2018-01-29 18:54:34 +01:00
var (
keys = []ebiten.Key{
ebiten.KeyQ,
ebiten.KeyA,
ebiten.KeyW,
ebiten.KeyS,
ebiten.KeyD,
ebiten.KeyR,
ebiten.KeyF,
ebiten.KeyT,
ebiten.KeyG,
ebiten.KeyH,
ebiten.KeyU,
ebiten.KeyJ,
ebiten.KeyI,
ebiten.KeyK,
ebiten.KeyO,
ebiten.KeyL,
}
keyStates = map[ebiten.Key]int{}
)
// updateInput updates the input state.
func updateInput() {
for _, key := range keys {
if !ebiten.IsKeyPressed(key) {
keyStates[key] = 0
2015-02-16 02:33:27 +01:00
continue
}
2018-01-29 18:54:34 +01:00
keyStates[key]++
}
}
func update(screen *ebiten.Image) error {
// The piano data is still being initialized.
// Get the progress if available.
if !pianoNoteSamplesInited {
select {
case <-pianoNoteSamplesInitCh:
pianoNoteSamplesInited = true
default:
}
2015-02-16 02:33:27 +01:00
}
2018-01-29 18:54:34 +01:00
if pianoNoteSamplesInited {
updateInput()
for i, key := range keys {
if keyStates[key] != 1 {
continue
}
playNote(baseFreq * math.Exp2(float64(i-1)/12.0))
}
}
2017-05-16 03:35:58 +02:00
if ebiten.IsRunningSlowly() {
return nil
}
2018-01-29 18:54:34 +01:00
screen.Fill(color.RGBA{0x80, 0x80, 0xc0, 0xff})
2018-01-29 18:54:34 +01:00
screen.DrawImage(pianoImage, nil)
2015-01-28 19:22:36 +01:00
ebitenutil.DebugPrint(screen, fmt.Sprintf("FPS: %0.2f", ebiten.CurrentFPS()))
2015-01-25 16:09:14 +01:00
return nil
}
func main() {
if err := ebiten.Run(update, screenWidth, screenHeight, 2, "Piano (Ebiten Demo)"); err != nil {
log.Fatal(err)
}
}