read_files.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package read
  2. import (
  3. "os"
  4. "fmt"
  5. tag "github.com/dhowden/tag"
  6. duration "github.com/felamaslen/go-music-player/pkg/read/duration"
  7. )
  8. type Song struct {
  9. title, artist, album string
  10. length int
  11. }
  12. func ReadFile(fileName string) (song *Song, err error) {
  13. file, errFile := os.Open(fileName)
  14. if errFile != nil {
  15. return &Song{}, errFile
  16. }
  17. defer file.Close()
  18. tags, errTags := tag.ReadFrom(file)
  19. if errTags != nil {
  20. return &Song{}, errTags
  21. }
  22. result := Song{
  23. title: tags.Title(),
  24. artist: tags.Artist(),
  25. album: tags.Album(),
  26. length: duration.GetSongDuration(file, tags),
  27. }
  28. return &result, nil
  29. }
  30. func ReadMultipleFiles(files chan string, doneChan chan bool) (chan *Song, chan bool) {
  31. songs := make(chan *Song)
  32. processed := make(chan bool)
  33. done := false
  34. go func() {
  35. for !done {
  36. select {
  37. case file := <- files:
  38. song, err := ReadFile(file)
  39. if err == nil {
  40. songs <- song
  41. } else {
  42. fmt.Printf("Error reading file (%s): %s", file, err)
  43. }
  44. case <- doneChan:
  45. done = true
  46. }
  47. }
  48. processed <- true
  49. }()
  50. return songs, processed
  51. }