/
music.go
67 lines (55 loc) · 1.43 KB
/
music.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Copyright (c) 2022 Elias Daler
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 3 of the GNU General Public
// License as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package main
import (
"io/fs"
"github.com/hajimehoshi/ebiten/v2/audio"
"github.com/hajimehoshi/ebiten/v2/audio/vorbis"
)
type Music struct {
f fs.File
loop *audio.InfiniteLoop
player *audio.Player
}
func NewMusicFromFile(audioContext *audio.Context, path string) (*Music, error) {
m := &Music{}
f, err := OpenFile(path)
if err != nil {
return nil, err
}
m.f = f
s, err := vorbis.Decode(audioContext, m.f)
if err != nil {
return nil, err
}
m.loop = audio.NewInfiniteLoop(s, s.Length())
p, err := audio.NewPlayer(audioContext, m.loop)
if err != nil {
return nil, err
}
m.player = p
return m, nil
}
func (m *Music) Play() {
m.player.Play()
}
func (m *Music) Close() error {
if err := m.player.Close(); err != nil {
return err
}
if err := m.f.Close(); err != nil {
return err
}
return nil
}