11package audioplayer
22
33import (
4- "bytes"
54 "errors"
65 "fmt"
76 "io/ioutil"
@@ -37,29 +36,27 @@ func init() {
3736 Volume = & effects.Volume {Base : 2 }
3837}
3938
40- func getContent (URL string , filename string , directory string ) ([]byte , error ) {
41- filename = url .PathEscape (path .Clean (strings .ReplaceAll (filename , ":" , "" )))
42- filepath := path .Join (directory , filename )
43- content , err := ioutil .ReadFile (filepath )
39+ func fetchContent (URL string , filepath string , directory string ) error {
40+
41+ _ , err := ioutil .ReadFile (filepath )
4442 if err == nil {
45- return content , nil
43+ return nil
4644 }
4745 response , err := http .Get (URL )
4846 if err != nil {
49- return nil , err
47+ return err
5048 }
5149 audio , err := ioutil .ReadAll (response .Body )
5250 if err != nil {
53- return nil , err
51+ return err
5452 }
5553 os .MkdirAll (directory , 0755 )
5654 // download content if not in .cache
5755 err = ioutil .WriteFile (filepath , audio , 0755 )
5856 if err != nil {
59- // If we don't have the permissions, we run the audio without caching
60- return audio , err
57+ return err
6158 }
62- return audio , nil
59+ return nil
6360}
6461
6562// PlaySound play the given audio url, supported Formats: mp3, wav
@@ -72,14 +69,22 @@ func PlaySound(e *itunesapi.Episode) error {
7269 URL := e .AudioURL
7370 filename := fmt .Sprintf ("%s.mp3" , e .Id )
7471 directory := config .CachePath
75- audioFile , err := getContent (URL , filename , directory )
76- audioReadCloser := ioutil .NopCloser (bytes .NewReader (audioFile ))
77- if audioFile == nil {
72+ filename = url .PathEscape (path .Clean (strings .ReplaceAll (filename , ":" , "" )))
73+ filepath := path .Join (directory , filename )
74+ file , err := os .Open (filepath )
75+ if err != nil {
76+ err = fetchContent (URL , filepath , directory )
77+ if err != nil {
78+ return err
79+ }
80+ }
81+ file , err = os .Open (filepath )
82+ if err != nil {
7883 return err
7984 }
80- Streamer , Format , err = mp3 .Decode (audioReadCloser )
85+ Streamer , Format , err = mp3 .Decode (file )
8186 if err != nil {
82- Streamer , Format , err = wav .Decode (audioReadCloser )
87+ Streamer , Format , err = wav .Decode (file )
8388 }
8489 if err != nil {
8590 return errors .New ("Unsupported audio format" )
0 commit comments