瀏覽代碼

feat: function to read multiple files through a channel

Fela Maslen 5 年之前
父節點
當前提交
3868b9d665
共有 3 個文件被更改,包括 82 次插入11 次删除
  1. 19 0
      music-player/pkg/read/duration/main.go
  2. 29 11
      music-player/pkg/read/read_files.go
  3. 34 0
      music-player/pkg/read/read_files_test.go

+ 19 - 0
music-player/pkg/read/duration/main.go

@@ -0,0 +1,19 @@
+package duration
+
+import (
+  "os"
+  "fmt"
+
+  tag "github.com/dhowden/tag"
+)
+
+func GetSongDuration(file *os.File, tags tag.Metadata) int {
+  switch tags.Format() {
+  case "VORBIS":
+    result, _ := GetSongDurationVorbis(file.Name())
+    return result
+  default:
+    fmt.Printf("Unrecognised format: %s\n", tags.Format())
+    return 0
+  }
+}

+ 29 - 11
music-player/pkg/read/read_files.go

@@ -2,6 +2,7 @@ package read
 
 import (
   "os"
+  "fmt"
 
   tag "github.com/dhowden/tag"
 
@@ -13,16 +14,6 @@ type Song struct {
   length int
 }
 
-func getSongDuration(file *os.File, tags tag.Metadata) int {
-  switch tags.Format() {
-  case "VORBIS":
-    result, _ := duration.GetSongDurationVorbis(file.Name())
-    return result
-  default:
-    return 0
-  }
-}
-
 func ReadFile(fileName string) (song *Song, err error) {
   file, errFile := os.Open(fileName)
   if errFile != nil {
@@ -39,8 +30,35 @@ func ReadFile(fileName string) (song *Song, err error) {
     title: tags.Title(),
     artist: tags.Artist(),
     album: tags.Album(),
-    length: getSongDuration(file, tags),
+    length: duration.GetSongDuration(file, tags),
   }
 
   return &result, nil
 }
+
+func ReadMultipleFiles(files chan string, doneChan chan bool) (chan *Song, chan bool) {
+  songs := make(chan *Song)
+  processed := make(chan bool)
+
+  done := false
+
+  go func() {
+    for !done {
+      select {
+      case file := <- files:
+        song, err := ReadFile(file)
+        if err == nil {
+          songs <- song
+        } else {
+          fmt.Printf("Error reading file (%s): %s", file, err)
+        }
+      case <- doneChan:
+        done = true
+      }
+    }
+
+    processed <- true
+  }()
+
+  return songs, processed
+}

+ 34 - 0
music-player/pkg/read/read_files_test.go

@@ -22,3 +22,37 @@ func TestReadFile(t *testing.T) {
   assert.Equal(t, result.album, testAlbum, "album must be correct")
   assert.Equal(t, result.length, testLengthSeconds, "length must be correct")
 }
+
+func TestReadMultipleFiles(t *testing.T) {
+  files := make(chan string, 1)
+  done := make(chan bool)
+
+  go func() {
+    files <- testFile
+    done <- true
+  }()
+
+  outputChan, doneChan := ReadMultipleFiles(files, done)
+
+  var results []*Song
+
+  outputDone := false
+
+  for !outputDone {
+    select {
+    case result := <- outputChan:
+      results = append(results, result)
+    case <- doneChan:
+      outputDone = true
+    }
+  }
+
+  assert.Len(t, results, 1)
+
+  assert.Equal(t, *results[0], Song{
+    title: testTitle,
+    artist: testArtist,
+    album: testAlbum,
+    length: testLengthSeconds,
+  })
+}