gobot.io/x/gobot/v2@v2.1.0/platforms/audio/audio_adaptor.go (about) 1 // Package audio is based on aplay audio adaptor written by @colemanserious (https://github.com/colemanserious) 2 package audio 3 4 import ( 5 "errors" 6 "log" 7 "os" 8 "os/exec" 9 "path" 10 11 "gobot.io/x/gobot/v2" 12 ) 13 14 // Adaptor is gobot Adaptor connection to audio playback 15 type Adaptor struct { 16 name string 17 } 18 19 // NewAdaptor returns a new audio Adaptor 20 func NewAdaptor() *Adaptor { 21 return &Adaptor{name: gobot.DefaultName("Audio")} 22 } 23 24 // Name returns the Adaptor Name 25 func (a *Adaptor) Name() string { return a.name } 26 27 // SetName sets the Adaptor Name 28 func (a *Adaptor) SetName(n string) { a.name = n } 29 30 // Connect establishes a connection to the Audio adaptor 31 func (a *Adaptor) Connect() error { return nil } 32 33 // Finalize terminates the connection to the Audio adaptor 34 func (a *Adaptor) Finalize() error { return nil } 35 36 // Sound plays a sound and accepts: 37 // 38 // string: The filename of the audio to start playing 39 func (a *Adaptor) Sound(fileName string) []error { 40 var errorsList []error 41 42 if fileName == "" { 43 log.Println("Requires filename for audio file.") 44 errorsList = append(errorsList, errors.New("Requires filename for audio file.")) 45 return errorsList 46 } 47 48 _, err := os.Stat(fileName) 49 if err != nil { 50 log.Println(err) 51 errorsList = append(errorsList, err) 52 return errorsList 53 } 54 55 // command to play audio file based on file type 56 commandName, err := CommandName(fileName) 57 if err != nil { 58 log.Println(err) 59 errorsList = append(errorsList, err) 60 return errorsList 61 } 62 63 err = RunCommand(commandName, fileName) 64 if err != nil { 65 log.Println(err) 66 errorsList = append(errorsList, err) 67 return errorsList 68 } 69 70 // Need to return to fulfill function sig, even though returning an empty 71 return nil 72 } 73 74 // CommandName defines the playback command for a sound and accepts: 75 // 76 // string: The filename of the audio that needs playback 77 func CommandName(fileName string) (commandName string, err error) { 78 fileType := path.Ext(fileName) 79 if fileType == ".mp3" { 80 return "mpg123", nil 81 } else if fileType == ".wav" { 82 return "aplay", nil 83 } else { 84 return "", errors.New("Unknown filetype for audio file.") 85 } 86 } 87 88 var execCommand = exec.Command 89 90 // RunCommand executes the playback command for a sound file and accepts: 91 // 92 // string: The audio command to be use for playback 93 // string: The filename of the audio that needs playback 94 func RunCommand(audioCommand string, filename string) error { 95 cmd := execCommand(audioCommand, filename) 96 err := cmd.Start() 97 return err 98 }