ebiten/examples/audio/main.go

304 lines
6.9 KiB
Go
Raw Normal View History

// Copyright 2016 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
2017-08-07 19:09:45 +02:00
// This is an example to implement an audio player.
2017-08-07 19:06:24 +02:00
// See examples/wav for a simpler example to play a sound file.
package main
import (
"fmt"
2016-03-17 14:59:29 +01:00
"image/color"
2016-06-26 20:11:10 +02:00
"io/ioutil"
"log"
2016-03-17 14:59:29 +01:00
"time"
"github.com/hajimehoshi/ebiten"
2016-04-18 18:24:44 +02:00
"github.com/hajimehoshi/ebiten/audio"
2017-06-11 11:12:12 +02:00
"github.com/hajimehoshi/ebiten/audio/mp3"
2016-04-18 18:24:44 +02:00
"github.com/hajimehoshi/ebiten/audio/wav"
"github.com/hajimehoshi/ebiten/ebitenutil"
)
const (
screenWidth = 320
screenHeight = 240
2017-06-03 16:23:02 +02:00
// This sample rate doesn't match with wav/mp3's sample rate,
2017-06-03 16:23:02 +02:00
// but decoders adjust them.
2017-06-18 15:50:58 +02:00
sampleRate = 48000
)
2016-03-17 14:59:29 +01:00
var (
2017-08-18 05:11:59 +02:00
playerBarColor = color.RGBA{0x80, 0x80, 0x80, 0xff}
playerCurrentColor = color.RGBA{0xff, 0xff, 0xff, 0xff}
2016-03-17 14:59:29 +01:00
)
2018-01-21 18:15:04 +01:00
// Input manages the current input state to detect keys 'just pressed'.
//
// Note: 'just pressed' is a very common idiom.
// There is a plan to create a new package for input utility.
// See https://github.com/hajimehoshi/ebiten/issues/415.
type Input struct {
mouseButtonStates map[ebiten.MouseButton]int
keyStates map[ebiten.Key]int
}
func (i *Input) update() {
for _, key := range []ebiten.Key{ebiten.KeyP, ebiten.KeyS, ebiten.KeyX, ebiten.KeyZ, ebiten.KeyB} {
if !ebiten.IsKeyPressed(key) {
i.keyStates[key] = 0
} else {
i.keyStates[key]++
}
}
if !ebiten.IsMouseButtonPressed(ebiten.MouseButtonLeft) {
i.mouseButtonStates[ebiten.MouseButtonLeft] = 0
} else {
i.mouseButtonStates[ebiten.MouseButtonLeft]++
}
}
2018-01-21 18:15:04 +01:00
func (i *Input) isKeyJustPressed(key ebiten.Key) bool {
return i.keyStates[key] == 1
}
func (i *Input) isKeyPressed(key ebiten.Key) bool {
return i.keyStates[key] > 0
}
2018-01-21 18:15:04 +01:00
func (i *Input) isMouseButtonJustPressed(mouseButton ebiten.MouseButton) bool {
return i.mouseButtonStates[mouseButton] == 1
}
2018-01-21 18:15:04 +01:00
// Player represents the current audio state.
type Player struct {
input *Input
audioContext *audio.Context
audioPlayer *audio.Player
current time.Duration
total time.Duration
2018-01-21 18:15:04 +01:00
seBytes []byte
seCh chan []byte
volume128 int
}
2016-03-19 17:40:10 +01:00
func playerBarRect() (x, y, w, h int) {
2017-08-18 05:11:59 +02:00
w, h = 300, 4
2016-03-19 17:40:10 +01:00
x = (screenWidth - w) / 2
y = screenHeight - h - 16
return
}
2017-06-03 16:23:02 +02:00
func NewPlayer(audioContext *audio.Context) (*Player, error) {
const bytesPerSample = 4 // TODO: This should be defined in audio package
wavF, err := ebitenutil.OpenFile("_resources/audio/jab.wav")
if err != nil {
return nil, err
}
mp3F, err := ebitenutil.OpenFile("_resources/audio/classic.mp3")
2017-06-03 16:23:02 +02:00
if err != nil {
return nil, err
}
2017-06-11 11:12:12 +02:00
s, err := mp3.Decode(audioContext, mp3F)
2017-06-03 16:23:02 +02:00
if err != nil {
return nil, err
}
p, err := audio.NewPlayer(audioContext, s)
if err != nil {
return nil, err
}
player := &Player{
input: &Input{
mouseButtonStates: map[ebiten.MouseButton]int{},
keyStates: map[ebiten.Key]int{},
},
audioContext: audioContext,
audioPlayer: p,
total: time.Second * time.Duration(s.Length()) / bytesPerSample / sampleRate,
volume128: 128,
2018-01-21 18:15:04 +01:00
seCh: make(chan []byte),
2017-06-03 16:23:02 +02:00
}
2017-06-11 11:12:12 +02:00
if player.total == 0 {
player.total = 1
}
2017-06-03 16:23:02 +02:00
player.audioPlayer.Play()
go func() {
s, err := wav.Decode(audioContext, wavF)
if err != nil {
log.Fatal(err)
return
}
b, err := ioutil.ReadAll(s)
if err != nil {
log.Fatal(err)
return
}
player.seCh <- b
}()
2017-06-03 16:23:02 +02:00
return player, nil
}
func (p *Player) update() error {
p.input.update()
2017-06-03 16:23:02 +02:00
select {
case p.seBytes = <-p.seCh:
close(p.seCh)
p.seCh = nil
2017-06-03 16:23:02 +02:00
default:
}
2018-01-21 18:15:04 +01:00
if p.audioPlayer.IsPlaying() {
p.current = p.audioPlayer.Current()
}
2018-01-21 18:15:04 +01:00
p.seekBarIfNeeded()
p.switchPlayStateIfNeeded()
p.playSEIfNeeded()
p.updateVolumeIfNeeded()
if p.input.isKeyJustPressed(ebiten.KeyB) {
b := ebiten.IsRunnableInBackground()
ebiten.SetRunnableInBackground(!b)
}
2017-06-03 16:23:02 +02:00
return nil
}
2018-01-21 18:15:04 +01:00
func (p *Player) playSEIfNeeded() {
if p.seBytes == nil {
2018-01-21 18:15:04 +01:00
// Bytes for the SE is not loaded yet.
return
2016-03-27 12:10:16 +02:00
}
2018-01-21 18:15:04 +01:00
if !p.input.isKeyJustPressed(ebiten.KeyP) {
return
2016-03-27 12:10:16 +02:00
}
sePlayer, _ := audio.NewPlayerFromBytes(p.audioContext, p.seBytes)
sePlayer.Play()
2016-03-27 12:10:16 +02:00
}
2018-01-21 18:15:04 +01:00
func (p *Player) updateVolumeIfNeeded() {
if p.input.isKeyPressed(ebiten.KeyZ) {
p.volume128--
2016-03-28 04:06:17 +02:00
}
if p.input.isKeyPressed(ebiten.KeyX) {
p.volume128++
2016-03-28 04:06:17 +02:00
}
if p.volume128 < 0 {
p.volume128 = 0
2016-03-28 04:06:17 +02:00
}
if 128 < p.volume128 {
p.volume128 = 128
2016-03-28 04:06:17 +02:00
}
p.audioPlayer.SetVolume(float64(p.volume128) / 128)
2016-03-28 04:06:17 +02:00
}
2018-01-21 18:15:04 +01:00
func (p *Player) switchPlayStateIfNeeded() {
if !p.input.isKeyJustPressed(ebiten.KeyS) {
return
2016-03-20 17:38:15 +01:00
}
if p.audioPlayer.IsPlaying() {
p.audioPlayer.Pause()
return
2016-03-20 17:38:15 +01:00
}
p.audioPlayer.Play()
2016-03-20 17:38:15 +01:00
}
2018-01-21 18:15:04 +01:00
func (p *Player) seekBarIfNeeded() {
if !p.input.isMouseButtonJustPressed(ebiten.MouseButtonLeft) {
return
2016-03-19 17:40:10 +01:00
}
2018-01-21 18:15:04 +01:00
// Calculate the next seeking position from the current cursor position.
2016-03-19 17:40:10 +01:00
x, y := ebiten.CursorPosition()
bx, by, bw, bh := playerBarRect()
2016-04-18 19:45:51 +02:00
const padding = 4
if y < by-padding || by+bh+padding <= y {
return
2016-03-19 17:40:10 +01:00
}
if x < bx || bx+bw <= x {
return
2016-03-19 17:40:10 +01:00
}
pos := time.Duration(x-bx) * p.total / time.Duration(bw)
p.current = pos
p.audioPlayer.Seek(pos)
2016-03-19 17:40:10 +01:00
}
2016-03-28 17:06:37 +02:00
func (p *Player) close() error {
return p.audioPlayer.Close()
}
2017-06-03 16:23:02 +02:00
func (p *Player) draw(screen *ebiten.Image) {
2018-01-21 18:15:04 +01:00
// Draw the bar.
2016-03-19 17:40:10 +01:00
x, y, w, h := playerBarRect()
2017-08-18 05:11:59 +02:00
ebitenutil.DrawRect(screen, float64(x), float64(y), float64(w), float64(h), playerBarColor)
2018-01-21 18:15:04 +01:00
// Draw the cursor on the bar.
c := p.current
2017-08-18 05:11:59 +02:00
cw, ch := 4, 10
2017-06-03 16:23:02 +02:00
cx := int(time.Duration(w)*c/p.total) + x - cw/2
cy := y - (ch-h)/2
2017-08-18 05:11:59 +02:00
ebitenutil.DrawRect(screen, float64(cx), float64(cy), float64(cw), float64(ch), playerCurrentColor)
2016-03-17 14:59:29 +01:00
2018-01-21 18:15:04 +01:00
// Compose the curren time text.
m := (c / time.Minute) % 100
s := (c / time.Second) % 60
currentTimeStr := fmt.Sprintf("%02d:%02d", m, s)
// Draw the debug message.
2016-03-19 15:45:36 +01:00
msg := fmt.Sprintf(`FPS: %0.2f
2016-03-20 17:38:15 +01:00
Press S to toggle Play/Pause
2016-03-27 12:10:16 +02:00
Press P to play SE
2016-03-28 04:06:17 +02:00
Press Z or X to change volume of the music
Press B to switch the run-in-background state
2018-01-21 18:15:04 +01:00
Current Time: %s`, ebiten.CurrentFPS(), currentTimeStr)
2017-06-03 16:23:02 +02:00
ebitenutil.DebugPrint(screen, msg)
}
2018-01-21 18:15:04 +01:00
var (
musicPlayer *Player
)
2017-06-03 16:23:02 +02:00
func update(screen *ebiten.Image) error {
if err := musicPlayer.update(); err != nil {
return err
}
2018-01-21 18:15:04 +01:00
2017-06-03 16:23:02 +02:00
if ebiten.IsRunningSlowly() {
return nil
}
2018-01-21 18:15:04 +01:00
2017-06-03 16:23:02 +02:00
musicPlayer.draw(screen)
return nil
}
func main() {
2017-06-03 16:23:02 +02:00
audioContext, err := audio.NewContext(sampleRate)
if err != nil {
log.Fatal(err)
}
2017-07-08 21:09:21 +02:00
2017-06-03 16:23:02 +02:00
musicPlayer, err = NewPlayer(audioContext)
if err != nil {
log.Fatal(err)
}
2016-03-09 19:02:55 +01:00
if err := ebiten.Run(update, screenWidth, screenHeight, 2, "Audio (Ebiten Demo)"); err != nil {
log.Fatal(err)
}
2018-01-21 18:15:04 +01:00
if err := musicPlayer.close(); err != nil {
log.Fatal(err)
2016-03-28 17:06:37 +02:00
}
}