[audio] Allows playback of both MP3 or WAV files, as long as the needed player (mpg123 or aplay) is installed

Signed-off-by: deadprogram <ron@hybridgroup.com>
This commit is contained in:
deadprogram 2016-05-15 10:46:35 -07:00
parent 80adfcd8c3
commit eecb3d727f
1 changed files with 20 additions and 8 deletions

View File

@ -3,10 +3,12 @@ package audio
import ( import (
"errors" "errors"
"github.com/hybridgroup/gobot"
"log" "log"
"os" "os"
"os/exec" "os/exec"
"path"
"github.com/hybridgroup/gobot"
) )
var _ gobot.Adaptor = (*AudioAdaptor)(nil) var _ gobot.Adaptor = (*AudioAdaptor)(nil)
@ -30,25 +32,35 @@ func (a *AudioAdaptor) Finalize() []error { return nil }
func (a *AudioAdaptor) Sound(fileName string) []error { func (a *AudioAdaptor) Sound(fileName string) []error {
var errorsList []error var errorsList []error
var err error
if fileName == "" { if fileName == "" {
log.Println("Require filename for MP3 file.") log.Println("Require filename for audio file.")
errorsList = append(errorsList, errors.New("Requires filename for MP3 file.")) errorsList = append(errorsList, errors.New("Requires filename for audio file."))
return errorsList return errorsList
} }
_, err = os.Open(fileName) _, err := os.Stat(fileName)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
errorsList = append(errorsList, err) errorsList = append(errorsList, err)
return errorsList return errorsList
} }
// command to play a MP3 file // command to play audio file based on file type
cmd := exec.Command("mpg123", fileName) fileType := path.Ext(fileName)
err = cmd.Start() var commandName string
if fileType == ".mp3" {
commandName = "mpg123"
} else if fileType == ".wav" {
commandName = "aplay"
} else {
log.Println("Unknown filetype for audio file.")
errorsList = append(errorsList, errors.New("Unknown filetype for audio file."))
return errorsList
}
cmd := exec.Command(commandName, fileName)
err = cmd.Start()
if err != nil { if err != nil {
log.Println(err) log.Println(err)
errorsList = append(errorsList, err) errorsList = append(errorsList, err)