Skip to content

Instantly share code, notes, and snippets.

@davesnowdon
Last active December 31, 2022 10:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davesnowdon/57d673f46472490486080651dbc6204d to your computer and use it in GitHub Desktop.
Save davesnowdon/57d673f46472490486080651dbc6204d to your computer and use it in GitHub Desktop.
ChatGPT: Write a go program that sends real-time audio using gRPC streaming
package main
import (
"context"
"fmt"
"io"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
pb "your-proto-package/your-proto-file"
)
const (
// Address of the gRPC server
address = "localhost:50051"
)
func main() {
// Set up a connection to the server
conn, err := grpc.Dial(address, grpc.WithInsecure())
if err != nil {
fmt.Printf("Failed to connect: %v\n", err)
return
}
defer conn.Close()
// Create a client for the streaming RPC
client := pb.NewAudioStreamClient(conn)
// Create a channel to receive audio data from the microphone
audioChan := make(chan []byte)
// Start a goroutine to read audio data from the microphone and send it over the channel
go func() {
for {
// Read a chunk of audio data from the microphone
audioData, err := readAudioFromMicrophone()
if err != nil {
fmt.Printf("Failed to read audio: %v\n", err)
return
}
// Send the audio data over the channel
audioChan <- audioData
}
}()
// Create a context with a timeout
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
// Create a stream for the RPC
stream, err := client.SendAudio(ctx)
if err != nil {
fmt.Printf("Failed to create stream: %v\n", err)
return
}
// Send the audio data from the channel to the stream
for {
select {
case audioData := <-audioChan:
// Send the audio data to the server
err = stream.Send(&pb.AudioPacket{Data: audioData})
if err != nil {
fmt.Printf("Failed to send audio: %v\n", err)
return
}
case <-ctx.Done():
// Check if the context has expired
if ctx.Err() == context.Canceled {
fmt.Printf("Stream canceled by client\n")
} else {
fmt.Printf("Stream canceled by server: %v\n", ctx.Err())
}
return
}
}
}
// readAudioFromMicrophone reads a chunk of audio data from the microphone
func readAudioFromMicrophone() ([]byte, error) {
// Replace this with your own code to read audio data from the microphone
}
@davesnowdon
Copy link
Author

Does not include protobuf definition and reading from the microphone is sadly left as an exercise for the reader

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment