file.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package utils
  2. import (
  3. "encoding/base64"
  4. "io"
  5. "os"
  6. "os/exec"
  7. "strconv"
  8. "strings"
  9. "github.com/sirupsen/logrus"
  10. "gopkg.in/ini.v1"
  11. )
  12. // 缓存 timeZone 信息
  13. var timeZoneCache string
  14. // FileExists checks if a file exists and is not a directory before we
  15. // try using it to prevent further errors.
  16. func FileExists(filename string) bool {
  17. info, err := os.Stat(filename)
  18. if os.IsNotExist(err) {
  19. return false
  20. }
  21. return !info.IsDir()
  22. }
  23. // pbx 不能正确读取时区, 读取自定义文件 /etc/asterisk/ntp.conf
  24. func GetLocationName() string {
  25. if timeZoneCache != "" {
  26. return timeZoneCache
  27. }
  28. filePath := "/etc/asterisk/ntp.conf"
  29. _, err := os.Stat(filePath)
  30. if err != nil {
  31. logrus.Error(err)
  32. return ""
  33. }
  34. iniFile, err := ini.Load(filePath)
  35. if err != nil {
  36. logrus.Error(err)
  37. return ""
  38. }
  39. timeZoneCache = iniFile.Section("ntp").Key("TZNAME").Value()
  40. logrus.Infof("use location %s", timeZoneCache)
  41. return timeZoneCache
  42. }
  43. func GetDuration(filePath string) (int, error) {
  44. cmd := exec.Command("soxi", "-D", filePath)
  45. output, err := cmd.Output()
  46. if err != nil {
  47. return 0, err
  48. }
  49. durationStr := strings.TrimSpace(string(output))
  50. duration, err := strconv.ParseFloat(durationStr, 64)
  51. if err != nil {
  52. return 0, err
  53. }
  54. return int(duration), nil
  55. }
  56. func AudioFileEncode(dstFile, srcFile string) error {
  57. data := "sripis123"
  58. encoded := base64.StdEncoding.EncodeToString([]byte(data))
  59. // Step 2: 创建一个新文件,写入 Base64 编码结果
  60. outputFile, err := os.Create(dstFile)
  61. if err != nil {
  62. return err
  63. }
  64. defer outputFile.Close()
  65. _, err = outputFile.WriteString(encoded)
  66. if err != nil {
  67. return err
  68. }
  69. // Step 3: 打开 audio.wav 文件
  70. audioFile, err := os.Open(srcFile)
  71. if err != nil {
  72. return err
  73. }
  74. defer audioFile.Close()
  75. // Step 4: 将 audio.wav 的内容追加到 output.bin 文件末尾
  76. _, err = audioFile.Seek(0, io.SeekStart) // 确保从文件开头读取
  77. if err != nil {
  78. return err
  79. }
  80. _, err = io.Copy(outputFile, audioFile)
  81. if err != nil {
  82. return err
  83. }
  84. return err
  85. }