2016-05-14 07:09:36 +08:00
|
|
|
// Based on aplay audio adaptor written by @colemanserious (https://github.com/colemanserious)
|
|
|
|
package audio
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"log"
|
|
|
|
"os"
|
|
|
|
"os/exec"
|
2016-05-16 01:46:35 +08:00
|
|
|
"path"
|
|
|
|
|
|
|
|
"github.com/hybridgroup/gobot"
|
2016-05-14 07:09:36 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
var _ gobot.Adaptor = (*AudioAdaptor)(nil)
|
|
|
|
|
|
|
|
type AudioAdaptor struct {
|
|
|
|
name string
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewAudioAdaptor(name string) *AudioAdaptor {
|
|
|
|
return &AudioAdaptor{
|
|
|
|
name: name,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (a *AudioAdaptor) Name() string { return a.name }
|
|
|
|
|
|
|
|
func (a *AudioAdaptor) Connect() []error { return nil }
|
|
|
|
|
|
|
|
func (a *AudioAdaptor) Finalize() []error { return nil }
|
|
|
|
|
|
|
|
func (a *AudioAdaptor) Sound(fileName string) []error {
|
|
|
|
|
|
|
|
var errorsList []error
|
|
|
|
|
|
|
|
if fileName == "" {
|
2016-05-16 01:46:35 +08:00
|
|
|
log.Println("Require filename for audio file.")
|
|
|
|
errorsList = append(errorsList, errors.New("Requires filename for audio file."))
|
2016-05-14 07:09:36 +08:00
|
|
|
return errorsList
|
|
|
|
}
|
|
|
|
|
2016-05-16 01:46:35 +08:00
|
|
|
_, err := os.Stat(fileName)
|
2016-05-14 07:09:36 +08:00
|
|
|
if err != nil {
|
|
|
|
log.Println(err)
|
|
|
|
errorsList = append(errorsList, err)
|
|
|
|
return errorsList
|
|
|
|
}
|
|
|
|
|
2016-05-16 01:46:35 +08:00
|
|
|
// command to play audio file based on file type
|
|
|
|
fileType := path.Ext(fileName)
|
|
|
|
var commandName string
|
|
|
|
if fileType == ".mp3" {
|
2016-05-16 02:08:48 +08:00
|
|
|
commandName = "mpg123"
|
2016-05-16 01:46:35 +08:00
|
|
|
} else if fileType == ".wav" {
|
2016-05-16 02:08:48 +08:00
|
|
|
commandName = "aplay"
|
2016-05-16 01:46:35 +08:00
|
|
|
} else {
|
|
|
|
log.Println("Unknown filetype for audio file.")
|
|
|
|
errorsList = append(errorsList, errors.New("Unknown filetype for audio file."))
|
|
|
|
return errorsList
|
|
|
|
}
|
2016-05-14 07:09:36 +08:00
|
|
|
|
2016-05-16 01:46:35 +08:00
|
|
|
cmd := exec.Command(commandName, fileName)
|
|
|
|
err = cmd.Start()
|
2016-05-14 07:09:36 +08:00
|
|
|
if err != nil {
|
|
|
|
log.Println(err)
|
|
|
|
errorsList = append(errorsList, err)
|
|
|
|
return errorsList
|
|
|
|
}
|
|
|
|
|
|
|
|
// Need to return to fulfill function sig, even though returning an empty
|
|
|
|
return nil
|
|
|
|
}
|