-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfile.go
93 lines (85 loc) · 1.9 KB
/
file.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package audiotools
import (
"errors"
"os"
"path/filepath"
"strings"
"github.com/go-audio/aiff"
"github.com/go-audio/wav"
)
var (
// ErrInvalidPath indicates that the path is... wait for it... invalid!
ErrInvalidPath = errors.New("invalid path")
)
// Format is the audio format canonical name
type Format string
var (
// Unknown means that this library couldn't detect the format type
Unknown Format = "unknown"
// Wav is the Waveform Audio File Format (WAVE, or more commonly known
// as WAV due to its filename extension)
Wav Format = "wav"
// Aiff is the Audio Interchange File Format
Aiff Format = "aiff"
// VideoMP4 is the video mp4 format
VideoMP4 Format = "video/mp4"
// VideoAvi is the video avi format
VideoAvi Format = "video/avi"
// VideoWebm is the video webm format
VideoWebm Format = "video/webm"
// Mp3 is the audio mpeg/3 format
Mp3 Format = "mp3"
// MIDI is the MIDI format
MIDI Format = "midi"
)
// FileFormat returns the known format of the passed path.
func FileFormat(path string) (Format, error) {
if !fileExists(path) {
return "", ErrInvalidPath
}
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
var triedWav bool
var triedAif bool
ext := strings.ToLower(filepath.Ext(path))
switch ext {
case ".wav", ".wave":
triedWav = true
d := wav.NewDecoder(f)
if d.IsValidFile() {
return Wav, nil
}
case ".aif", ".aiff":
triedAif = true
d := aiff.NewDecoder(f)
if d.IsValidFile() {
return Aiff, nil
}
}
// extension doesn't match, let's try again
f.Seek(0, 0)
if !triedWav {
wd := wav.NewDecoder(f)
if wd.IsValidFile() {
return Wav, nil
}
f.Seek(0, 0)
}
if !triedAif {
ad := aiff.NewDecoder(f)
if ad.IsValidFile() {
return Aiff, nil
}
}
return Unknown, nil
}
// helper checking if a file exists
func fileExists(path string) bool {
if _, err := os.Stat(path); os.IsNotExist(err) {
return false
}
return true
}