forked from schollz/musicsaur
/
mp3s.go
105 lines (93 loc) · 1.92 KB
/
mp3s.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
94
95
96
97
98
99
100
101
102
103
104
105
package main
import (
"log"
"os"
"path/filepath"
"time"
id3 "github.com/bobertlo/go-id3/id3"
mp3 "github.com/tcolgate/mp3"
)
func loadMp3s(path string) {
defer timeTrack(time.Now(), "loadMp3s")
searchDir, _ := filepath.Abs(path)
fileList := []string{}
err := filepath.Walk(searchDir, func(path string, f os.FileInfo, err error) error {
fileList = append(fileList, path)
return nil
})
if err != nil {
panic(err)
}
for _, file := range fileList {
if filepath.Ext(file) == ".mp3" {
if !statevar.PathList[file] {
log.Println(file)
s, err := getMp3Info(file)
if err != nil {
log.Println("Couldn't get ID3 for " + file + ", skipping...")
} else {
statevar.PathList[file] = true
statevar.SongMap[s.Path] = s
}
}
}
}
}
func getMp3Info(path string) (Song, error) {
defer timeTrack(time.Now(), "getMp3Info")
file, err := os.Open(path)
if err != nil {
panic(err)
}
defer file.Close()
// duration, err := mp3.Length(file)
// if err != nil {
// log.Println(err)
// duration = time.Duration(10000)
// }
tags, err := id3.ReadFile(file)
if err != nil {
return Song{
Fullname: "none",
Title: "none",
Artist: "none",
Album: "none",
Path: "none",
Length: 0,
}, err
}
title := tags["title"]
artist := tags["artist"]
album := tags["album"]
fullname := artist + " - " + album + " - " + title
if title == "" {
title = path
fullname = title
}
return Song{
Fullname: fullname,
Title: title,
Artist: artist,
Album: album,
Path: path,
Length: getMp3Length(path),
}, nil
}
func getMp3Length(path string) (totalTime int64) {
// Returns length in milliseconds
r, err := os.Open(path)
if err != nil {
//fmt.Println(err)
return
}
d := mp3.NewDecoder(r)
var f mp3.Frame
totalTime = 0
for {
if err := d.Decode(&f); err != nil {
//fmt.Println(err)
return
}
totalTime += f.Duration().Nanoseconds() / 1000000
}
}