1
0

audio.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package app
  2. import (
  3. "encoding/binary"
  4. "math"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. "git.monoexp.com/bajdev/mpckit/internal/project"
  9. "git.monoexp.com/bajdev/mpckit/internal/wav"
  10. )
  11. // AudioPrefix is the URL path the preview loads samples from:
  12. // /audio/<slot> serves the pad's source WAV as it is, and
  13. // /audio/<slot>?pcm=1 serves it decoded, for formats the webview cannot
  14. // decode (build plan 4.5 and section 9).
  15. const AudioPrefix = "/audio/"
  16. // AudioMiddleware serves AudioPrefix and passes every other request on.
  17. // It is for main.go's asset server, not the frontend.
  18. //
  19. //wails:ignore
  20. func (s *Service) AudioMiddleware(next http.Handler) http.Handler {
  21. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  22. if !strings.HasPrefix(r.URL.Path, AudioPrefix) {
  23. next.ServeHTTP(w, r)
  24. return
  25. }
  26. s.serveAudio(w, r)
  27. })
  28. }
  29. func (s *Service) serveAudio(w http.ResponseWriter, r *http.Request) {
  30. slot, err := strconv.Atoi(strings.TrimPrefix(r.URL.Path, AudioPrefix))
  31. if err != nil || slot < 0 || slot >= project.Pads {
  32. http.NotFound(w, r)
  33. return
  34. }
  35. s.mu.Lock()
  36. v, err := s.p.Pad(slot)
  37. src := s.p.Sources[v.File]
  38. s.mu.Unlock()
  39. if err != nil || v.Empty() || src == "" {
  40. http.NotFound(w, r)
  41. return
  42. }
  43. w.Header().Set("Cache-Control", "no-store")
  44. if r.URL.Query().Get("pcm") == "" {
  45. w.Header().Set("Content-Type", "audio/wav")
  46. http.ServeFile(w, r, src)
  47. return
  48. }
  49. // Decoded: a 12-byte header (sample rate, channels, frames as uint32
  50. // little-endian), then each channel's frames as float32 little-endian.
  51. info, chans, err := wav.DecodeFile(src)
  52. if err != nil {
  53. http.Error(w, err.Error(), http.StatusUnprocessableEntity)
  54. return
  55. }
  56. frames := len(chans[0])
  57. buf := make([]byte, 12+4*frames*len(chans))
  58. binary.LittleEndian.PutUint32(buf[0:], uint32(info.SampleRate))
  59. binary.LittleEndian.PutUint32(buf[4:], uint32(len(chans)))
  60. binary.LittleEndian.PutUint32(buf[8:], uint32(frames))
  61. off := 12
  62. for _, ch := range chans {
  63. for _, v := range ch {
  64. binary.LittleEndian.PutUint32(buf[off:], math.Float32bits(v))
  65. off += 4
  66. }
  67. }
  68. w.Header().Set("Content-Type", "application/octet-stream")
  69. w.Write(buf)
  70. }