// Encode encodes an Opus frame. // // pcm: the 16-bit PCM input signal (interleaved if 2 channels). Whose length is // frameSize*channels. // // frameSize: the number of samples per channel in the input signal. This must // be an Opus frame size for the encoder's sampling rate. For example at 48kHz // the permitted values are 120, 240, 480, 960, 1920, and 2880. Passing in a // duration of less than 10 ms (480 samples at 48 kHz) will prevent the encoder // from using the LPC or hybrid modes. // // data: the slice to store the output payload in, containing len(data) bytes // of space. The length of the slice may be used to impose an upper limit on // the instant bitrate, but should not be used as the only bitrate control. Use // SET_BITRATE to control the bitrate. // // returns: a slice of the data slice representing the encoded packet, OR nil // and an error. func (e *Encoder) Encode(pcm []int16, frameSize int, data []byte) ([]byte, error) { n := C.opus_encode( e.cptr(), (*C.opus_int16)(unsafe.Pointer(&pcm[0])), C.int(frameSize), (*C.uchar)(unsafe.Pointer(&data[0])), C.opus_int32(len(data)), ) if n > 0 { return data[:n], nil } return nil, opusError(C.int(-n)) }
func (e *Encoder) Encode(pcm []int16, frameSize, maxDataBytes int) ([]byte, error) { pcmPtr := (*C.opus_int16)(unsafe.Pointer(&pcm[0])) data := make([]byte, maxDataBytes) dataPtr := (*C.uchar)(unsafe.Pointer(&data[0])) encodedC := C.opus_encode(e.cEncoder, pcmPtr, C.int(frameSize), dataPtr, C.opus_int32(len(data))) encoded := int(encodedC) if encoded < 0 { return nil, getErr(C.int(encodedC)) } return data[0:encoded], nil }
// Encode raw PCM data and store the result in the supplied buffer. On success, // returns the number of bytes used up by the encoded data. func (enc *Encoder) Encode(pcm []int16, data []byte) (int, error) { if enc.p == nil { return 0, errEncUninitialized } if len(pcm) == 0 { return 0, fmt.Errorf("opus: no data supplied") } if len(data) == 0 { return 0, fmt.Errorf("opus: no target buffer") } n := int(C.opus_encode( enc.p, (*C.opus_int16)(&pcm[0]), C.int(len(pcm)), (*C.uchar)(&data[0]), C.opus_int32(cap(data)))) if n < 0 { return 0, opuserr(n) } return n, nil }