forked from iFaceless/godub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
loader.go
77 lines (65 loc) · 1.36 KB
/
loader.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
68
69
70
71
72
73
74
75
76
77
package godub
import (
"fmt"
"os"
"bytes"
"io"
"github.com/skit-ai/go-dub/converter"
"github.com/skit-ai/go-dub/wav"
)
type Loader struct {
converter *converter.Converter
buf io.Writer
}
func NewLoader() *Loader {
var buf bytes.Buffer
return &Loader{
converter: converter.NewConverter(&buf),
buf: &buf,
}
}
func (l *Loader) WithParams(params ...string) *Loader {
l.converter.WithParams(params...)
return l
}
func (l *Loader) Load(src interface{}) (*AudioSegment, error) {
var buf []byte
switch r := src.(type) {
case io.Reader:
result, err := io.ReadAll(r)
if err != nil {
return nil, err
}
buf = result
case string:
result, err := os.ReadFile(r)
if err != nil {
return nil, err
}
buf = result
case []byte:
buf = r
default:
return nil, fmt.Errorf("expected `io.Reader` or file path to original audio")
}
// Empty buffer
if len(buf) == 0 {
return nil, nil
}
// Try to decode it as wave audio
waveAudio, err := wav.DecodeFromBytes(buf)
if err != nil {
// Try to convert to wave audio, and decode it again!
var tmpWavBuf bytes.Buffer
conv := converter.NewConverter(&tmpWavBuf).WithDstFormat("wav")
e := conv.Convert(bytes.NewReader(buf))
if e != nil {
return nil, e
}
waveAudio, e = wav.Decode(&tmpWavBuf)
if e != nil {
return nil, err
}
}
return NewAudioSegmentFromWaveAudio(waveAudio)
}