-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathloader.go
71 lines (59 loc) · 1.31 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
package godub
import (
"fmt"
"bytes"
"io"
"io/ioutil"
"github.com/iFaceless/godub/converter"
"github.com/iFaceless/godub/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 := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
buf = result
case string:
result, err := ioutil.ReadFile(r)
if err != nil {
return nil, err
}
buf = result
default:
return nil, fmt.Errorf("expected `io.Reader` or file path to original audio")
}
// Try to decode it as wave audio
waveAudio, err := wav.Decode(bytes.NewReader(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)
}