Last active
November 27, 2024 10:01
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Does not include protobuf definition and reading from the microphone is sadly left as an exercise for the reader