0

I'm writing a Go program that interfaces with libalsa. I have my PCM data stored in a []int16 slice, but to call libalsa I need that stored in a []byte slice.

How do I convert a []int16 slice to []byte to accomplish this?

user96931
  • 103
  • 7
  • 2
    Be aware that converting int16 data to bytes requires that you choose some byte order, since you have to break each 16-bit value into two eight-bit values. https://wiki.multimedia.cx/index.php/PCM#Byte_Order suggests that little-endian is the most common order. I have no idea whether the routines you're using need that order though. – torek May 14 '20 at 00:48
  • I would also add that the if you're interfacing with C code, you might want to not copy bytes but perform a type cast (via the package `unsafe`). That's because the libalsa'a code might expect `*char` merely because that's the lowest common denominator to define "an array of data of any type" in C—provided the function which accepts such an array also accepts a value telling which actual format the data in the array has. I'm hinting at this because typically when one deals with RT audio, reducing latency is paramount and copying the data in memory just for type compatibility might be unwise. – kostix May 16 '20 at 09:12
  • …so, if you really interfacing `libalsa` via` cgo`, you might ask a bit more broad question. – kostix May 16 '20 at 09:12

1 Answers1

3

You could try this :

package main

import "fmt"
import "bytes"
import "encoding/binary"

func main() {
    nums := [6]int16{2, 3, 5, 7, 11, 13}
    buf := new(bytes.Buffer)
    err := binary.Write(buf, binary.LittleEndian, nums)
    if(err==nil) {
        fmt.Printf("% x", buf.Bytes()) 
    }

}
vbhargav875
  • 837
  • 8
  • 15