Skip to content

Commit

Permalink
fix(birdweather): fixed PCM to WAV encoding
Browse files Browse the repository at this point in the history
  • Loading branch information
tphakala committed Apr 27, 2024
1 parent 15354f3 commit 79ae3f4
Showing 1 changed file with 23 additions and 19 deletions.
42 changes: 23 additions & 19 deletions internal/birdweather/audio.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,30 +24,34 @@ func encodePCMtoWAV(pcmData []byte) (*bytes.Buffer, error) {
// Initialize a buffer to build the WAV file
buffer := bytes.NewBuffer(nil)

// Writing the RIFF header
binary.Write(buffer, binary.LittleEndian, []byte("RIFF"))
binary.Write(buffer, binary.LittleEndian, chunkSize)
binary.Write(buffer, binary.LittleEndian, []byte("WAVE"))

// Writing the fmt sub-chunk
binary.Write(buffer, binary.LittleEndian, []byte("fmt "))
binary.Write(buffer, binary.LittleEndian, uint32(16)) // Sub-chunk1 size for PCM
binary.Write(buffer, binary.LittleEndian, uint16(1)) // Audio format 1 is PCM
binary.Write(buffer, binary.LittleEndian, uint16(numChannels))
binary.Write(buffer, binary.LittleEndian, uint32(sampleRate))
binary.Write(buffer, binary.LittleEndian, uint32(byteRate))
binary.Write(buffer, binary.LittleEndian, uint16(blockAlign))
binary.Write(buffer, binary.LittleEndian, uint16(bitDepth))

// Writing the data sub-chunk
binary.Write(buffer, binary.LittleEndian, []byte("data"))
binary.Write(buffer, binary.LittleEndian, subChunk2Size)
binary.Write(buffer, binary.LittleEndian, pcmData)
// List of data elements to write sequentially to the buffer
elements := []interface{}{
[]byte("RIFF"), chunkSize, []byte("WAVE"),
[]byte("fmt "), uint32(16), uint16(1), uint16(numChannels),
uint32(sampleRate), uint32(byteRate), uint16(blockAlign), uint16(bitDepth),
[]byte("data"), subChunk2Size, pcmData,
}

// Sequential write operation handling errors
for _, elem := range elements {
if b, ok := elem.([]byte); ok {
// Ensure all byte slices are properly converted before writing
if err := binary.Write(buffer, binary.LittleEndian, b); err != nil {
return nil, err
}
} else {
// Handle all other data types
if err := binary.Write(buffer, binary.LittleEndian, elem); err != nil {
return nil, err
}
}
}

return buffer, nil
}

// saveBufferToDisk writes a bytes.Buffer to a file, this is only used for debugging.
// golangci-lint:ignore unused for now
func saveBufferToDisk(buffer *bytes.Buffer, filename string) error {
file, err := os.Create(filename)
if err != nil {
Expand Down

0 comments on commit 79ae3f4

Please sign in to comment.