grokify/mogo

View on GitHub
audio/ulaw/ulaw.go

Summary

Maintainability
A
0 mins
Test Coverage
package ulaw

import (
    "io"
    "os"
)

var wavHeaderThin = []byte{0x52, 0x49, 0x46, 0x46, 0x62, 0xb8, 0x00, 0x00, 0x57, 0x41, 0x56, 0x45, 0x66, 0x6d, 0x74, 0x20,
    0x12, 0x00, 0x00, 0x00, 0x07, 0x00, 0x01, 0x00, 0x40, 0x1f, 0x00, 0x00, 0x80, 0x3e, 0x00, 0x00,
    0x02, 0x00, 0x04, 0x00, 0x00, 0x00, 0x66, 0x61, 0x63, 0x74, 0x04, 0x00, 0x00, 0x00, 0xc5, 0x5b,
    0x00, 0x00, 0x64, 0x61, 0x74, 0x61}

var wavHeader = []byte{0x52, 0x49, 0x46, 0x46, 0x62, 0xb8, 0x00, 0x00, 0x57, 0x41, 0x56, 0x45, 0x66, 0x6d, 0x74, 0x20,
    0x12, 0x00, 0x00, 0x00, 0x07, 0x00, 0x01, 0x00, 0x40, 0x1f, 0x00, 0x00, 0x80, 0x3e, 0x00, 0x00,
    0x02, 0x00, 0x04, 0x00, 0x00, 0x00, 0x66, 0x61, 0x63, 0x74, 0x04, 0x00, 0x00, 0x00, 0xc5, 0x5b,
    0x00, 0x00, 0x64, 0x61, 0x74, 0x61, 0x00, 0x00, 0x00, 0x00}

func WAVHeader(inclLenBytes bool) []byte {
    if inclLenBytes {
        return wavHeader
    }
    return wavHeaderThin
}

func WriteFileWAVFromULAW(filename string, ulawBytes []byte) error {
    f, err := os.Create(filename)
    if err != nil {
        return err
    }
    defer f.Close()
    _, err = WriteWAVFromULAW(f, ulawBytes)
    if err != nil {
        return err
    }
    return f.Sync()
}

func WriteWAVFromULAW(w io.Writer, ulawBytes []byte) (n int, err error) {
    n1, err := w.Write(wavHeaderThin)
    if err != nil {
        return n, err
    }
    n += n1
    count := len(ulawBytes)
    n2, err := w.Write([]byte{
        byte(count % 256),
        byte((count >> 8) % 256),
        byte((count >> 16) % 256),
        byte((count >> 24) % 256)})
    if err != nil {
        return n, err
    }
    n += n2
    n3, err := w.Write(ulawBytes)
    if err != nil {
        return n, err
    }
    return n + n3, nil
}