yask.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package yask
  2. import (
  3. "encoding/binary"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "github.com/go-audio/audio"
  9. "github.com/go-audio/wav"
  10. )
  11. // EncodePCMToWav encode input stream of pcm audio format to wav and write to out stream
  12. func EncodePCMToWav(in io.Reader, out io.WriteSeeker, sampleRate, bitDepth, numChans int) error {
  13. encoder := wav.NewEncoder(out, sampleRate, bitDepth, numChans, 1)
  14. audioBuf := &audio.IntBuffer{
  15. Format: &audio.Format{
  16. NumChannels: numChans,
  17. SampleRate: sampleRate,
  18. },
  19. }
  20. for {
  21. var sample int16
  22. if err := binary.Read(in, binary.LittleEndian, &sample); err != nil {
  23. if err == io.EOF {
  24. break
  25. } else {
  26. return err
  27. }
  28. }
  29. audioBuf.Data = append(audioBuf.Data, int(sample))
  30. }
  31. if err := encoder.Write(audioBuf); err != nil {
  32. return err
  33. }
  34. return encoder.Close()
  35. }
  36. func unmarshallYaError(r io.Reader) (err error) {
  37. var data []byte
  38. if data, err = ioutil.ReadAll(r); err != nil {
  39. return
  40. }
  41. mErr := make(map[string]interface{})
  42. if err = json.Unmarshal(data, &mErr); err == nil {
  43. err = fmt.Errorf("Yandex request error: %v", mErr["error_message"])
  44. }
  45. return
  46. }
  47. // Voices returns slice of available vioces
  48. // lang: empty (all alngs) ru-RU, en-EN, tr-TR
  49. // sex: 0 - all, 1 - male, 2 - female
  50. // premium: 0 - all, 1 - standard only, 2 - premium only
  51. func Voices(lang string, sex, premium int) (res []Voice) {
  52. for _, voice := range voices {
  53. if len(lang) > 0 && voice.Lang != lang {
  54. continue
  55. }
  56. if sex != 0 && (sex == 1 && !voice.Male || sex == 2 && voice.Male) {
  57. continue
  58. }
  59. if premium != 0 && (voice.Premium && premium != 2 || !voice.Premium && premium != 1) {
  60. continue
  61. }
  62. res = append(res, voice)
  63. }
  64. return
  65. }