Example #1
0
func (ab AudioBuffer) writeTo(client *Client, w io.Writer) (int64, error) {
	var written int64

	// Create Opus buffer
	opus, err := client.audioEncoder.Encode(ab, AudioDefaultFrameSize, AudioMaximumFrameSize)
	if err != nil {
		return 0, err
	}

	// Create audio header
	var header bytes.Buffer
	var targetID int
	if target := client.audioTarget; target != nil {
		targetID = target.id
	}
	formatTarget := byte(4)<<5 | byte(targetID)
	if err := header.WriteByte(formatTarget); err != nil {
		return 0, err
	}
	if _, err := varint.WriteTo(&header, int64(client.audioSequence)); err != nil {
		return 0, err
	}
	if _, err := varint.WriteTo(&header, int64(len(opus))); err != nil {
		return 0, err
	}

	// Write packet header
	ni, err := writeTcpHeader(w, 1, header.Len()+len(opus))
	if err != nil {
		return int64(ni), err
	}
	written += int64(ni)

	// Write audio header
	n, err := header.WriteTo(w)
	if err != nil {
		return (written + n), err
	}
	written += n

	// Write audio data
	ni, err = w.Write(opus)
	if err != nil {
		return (written + int64(ni)), err
	}
	written += int64(ni)

	client.audioSequence = (client.audioSequence + 1) % math.MaxInt32
	return written, nil
}
Example #2
0
// WriteAudio writes an audio packet to the connection.
func (c *Conn) WriteAudio(format, target, sequence int, data []byte, X, Y, Z *float32) error {
	var header bytes.Buffer
	formatTarget := byte(format)<<5 | byte(target)
	if err := header.WriteByte(formatTarget); err != nil {
		return err
	}
	if _, err := varint.WriteTo(&header, int64(sequence)); err != nil {
		return err
	}
	if _, err := varint.WriteTo(&header, int64(len(data))); err != nil {
		return err
	}

	var positionalLength int
	if X != nil {
		positionalLength = 3 * 4
	}

	c.Lock()
	defer c.Unlock()

	if err := c.writeHeader(1, uint32(header.Len()+len(data)+positionalLength)); err != nil {
		return err
	}
	if _, err := header.WriteTo(c.Conn); err != nil {
		return err
	}
	if _, err := c.Conn.Write(data); err != nil {
		return err
	}

	if positionalLength > 0 {
		if err := binary.Write(c.Conn, binary.LittleEndian, *X); err != nil {
			return err
		}
		if err := binary.Write(c.Conn, binary.LittleEndian, *Y); err != nil {
			return err
		}
		if err := binary.Write(c.Conn, binary.LittleEndian, *Z); err != nil {
			return err
		}
	}

	return nil
}