go-roflcopter/roflcopter/roflcopter.go

108 lines
2.0 KiB
Go

package roflcopter
import (
"bytes"
_ "embed"
"io"
"log"
"sync"
"time"
"github.com/faiface/beep/mp3"
"github.com/faiface/beep/speaker"
)
//go:embed embed\swah.mp3
var swah []byte
var (
work bool = true
duration time.Duration
wg sync.WaitGroup
)
const (
frame1 = " ROFL:ROFL: \n _^____ \n L __/ [] \\ \n O ===__ \\ \n L \\________] \n I I \n --------/ \n"
frame2 = " :ROFL:ROFL\n _^____ \n __/ [] \\ \nLOL===__ \\ \n \\________] \n I I \n --------/ \n"
)
type Roflcopter struct {
output bool
work bool
count time.Duration
str *string
runner func()
}
func NewRoflcopter(amount time.Duration, outStr *string, out bool, funcrunner func()) *Roflcopter {
return &Roflcopter{
output: out,
work: true,
str: outStr,
count: amount,
runner: funcrunner,
}
}
func (b *Roflcopter) Start() {
*b.str = frame1 + b.count.String()
work = b.work
duration = b.count
if b.output {
go b.player()
}
go b.timecounter(500 * time.Millisecond)
go b.frameChanger(125 * time.Millisecond)
}
func (b *Roflcopter) timecounter(step time.Duration) {
for b.count >= 0 {
b.count -= step
time.Sleep(step)
}
work = false
}
func (b *Roflcopter) player() {
b.sound()
wg.Wait()
b.player()
}
func (b *Roflcopter) frameChanger(delay time.Duration) {
nextframe := 2
for work {
switch nextframe {
case 1:
{
*b.str = frame1 + "Ends in " + b.count.String()
time.Sleep(delay)
nextframe = 2
}
case 2:
{
*b.str = frame2 + "Ends in " + b.count.String()
time.Sleep(delay)
nextframe = 1
}
}
b.runner()
}
}
func (b *Roflcopter) sound() {
wg.Add(1)
t := 1*time.Second + 380*time.Millisecond
streamer, format, err := mp3.Decode(io.NopCloser(bytes.NewReader(swah)))
if err != nil {
log.Fatal(err)
}
defer streamer.Close()
speaker.Init(format.SampleRate, format.SampleRate.N(time.Second/10))
speaker.Play(streamer)
time.Sleep(t * 1)
wg.Done()
}