Home Backend Development Golang Golang implements voice chat

Golang implements voice chat

May 13, 2023 am 09:37 AM

With the continuous advancement of technology, voice communication has become an indispensable part of people's lives. Today, voice chat has become one of the most common communication methods on the Internet. Therefore, it is necessary to integrate voice chat functionality into the application so that users can easily communicate via voice. Golang is a very excellent programming language. It has the characteristics of efficiency, speed and reliability, so using golang to implement the voice chat function will be a very good choice. In this article, we will introduce how to use golang to implement voice chat function.

1. Environment Settings

Before starting to implement the voice chat function, you need to install the golang language development environment on your computer. After installation, you need to use the go get command to install some voice-related libraries, including:

  1. github.com/gordonklaus/portaudio: PortAudio audio library
  2. github.com/faiface /beep:beep audio library
  3. github.com/faiface/gui:gui user interface library
  4. github.com/gordonklaus/audiowaveform:Waveform waveform library

These libraries can be quickly installed using the go get command. For example, the command go get github.com/gordonklaus/portaudio can install the PortAudio audio library.

2. Implementation process

After the environment setting is completed, the next step is the specific process of implementing the voice chat function. First, you need to create a client and a server so that users can communicate with each other. After the connection is established, the client will be able to send audio data to the server, which will receive it and forward it to other clients. Then, other clients can receive the audio data from the client and play it.

  1. Create Server

The first step to create a server is to start the HTTP service and create a WebSocket connection. The code is as follows:

func main() {

    // 1. 启动HTTP服务
    http.HandleFunc("/", handleWebsocket)
    go http.ListenAndServe(":8080", nil)
    
}

func handleWebsocket(w http.ResponseWriter, r *http.Request) {

    // 2. 创建WebSocket连接
    ws, err := websocket.Upgrade(w, r, nil, 1024, 1024)
    if err != nil {
        log.Fatal(err)
    }
    
    // 3. 处理音频数据传输
    for {
        msgType, msg, err := ws.ReadMessage()
        if err != nil {
            log.Fatal(err)
        }
        ws.WriteMessage(msgType, msg)
    }
    
}
Copy after login

In the above In the code, an HTTP service is first started and listened on port 8080. Next, a WebSocket connection is created in the handleWebsocket function, which will be called every time a request is sent to the server. Finally, to handle the transmission of audio data, some simple WebSocket read and write operations are used.

  1. Create client

The first step to create a client is to join the server, the code is as follows:

func main() {

    // ...启动HTTP服务

    // 1. 创建WebSocket连接
    conn, _, err := websocket.DefaultDialer.Dial("ws://localhost:8080", nil)
    if err != nil {
        log.Fatal(err)
    }

    // 2. 加入服务器
    message := []byte("join")
    conn.WriteMessage(websocket.TextMessage, message)

    // 3. 处理音频数据传输
    for {
        _, message, err := conn.ReadMessage()
        if err != nil {
            log.Fatal(err)
        }
        // 处理接收到的音频数据
        // ...
    }

}
Copy after login

In the above code , first create a WebSocket connection using the DefaultDialer.Dial function and link it to the server. Next, the client uses a simple join message to tell the server that the client has joined the chat room. Finally, the client will loop to read the audio data sent by the server and process the data.

  1. Record and play audio

The next step is the most critical step, record and play audio. Golang uses the beep audio library for audio processing, which provides a large number of audio processors and effects. Here is a code example of how to record audio using the library:

func main() {

    // ...创建WebSocket连接并加入服务器

    // 1. 配置recorder
    format := beep.Format{
        SampleRate:  44100, //采样率
        NumChannels: 1,     //通道数
        Precision:   2,     //数据精度
    }
    speaker.Init(format.SampleRate, format.SampleRate.N(time.Second/10))

    streamer := &audioStreamer{}
    streamer.buf = new(bytes.Buffer)
    streamer.stream = beep.NewMixedStreamer(beep.StreamerFunc(streamer.Sample), beep.Callback(func() {}))

    resampler, err := resample.New(resample.SincMediumQuality, streamer.stream, streamer)

    // 2. 创建recorder
    stream, format, err := portaudio.OpenDefaultStream(1, 0, format.SampleRate, 0, resampler.Process)

    if err != nil {
        log.Fatal(err)
    }

    // 3. 启动recorder
    err = stream.Start()
    if err != nil {
        log.Fatal(err)
    }

    // 4. 启动播放器
    speaker.Play(beep.Seq(streamer, beep.Callback(func() {})))

    // 5. 处理音频数据传输
    for {
        _, message, err := conn.ReadMessage()
        if err != nil {
            log.Fatal(err)
        }
        // 处理接收到的音频数据
        // ...
    }

}

type audioStreamer struct {
    buf    *bytes.Buffer
    stream beep.Streamer
}

func (a *audioStreamer) Stream(samples [][2]float64) (n int, ok bool) {
    d := make([]byte, len(samples)*4)
    if a.buf.Len() >= len(d) {
        a.buf.Read(d)
        ok = true
    }

    for i, s := range samples {
        s[0] = float64(int16(binary.LittleEndian.Uint16(d[i*4 : i*4+2]))) / 0x8000
    }
    n = len(samples)
    return
}

func (a *audioStreamer) Err() error {
    return nil
}

func (a *audioStreamer) Sample(samples [][2]float64) (n int, ok bool) {
    n, ok = a.stream.Stream(samples)
    a.buf.Write(make([]byte, n*4))
    for i, s := range samples[:n] {
        x := int16(s[0] * 0x8000)
        binary.LittleEndian.PutUint16(a.buf.Bytes()[i*4:i*4+2], uint16(x))
    }
    return
}
Copy after login

In the above code, a beep audio stream is first created, and an audio input stream is created using the portaudio library, which will start from the default Get audio input from the audio input device. Next, use the resample library to resample the audio data obtained from the input stream to adapt to the audio sample rate used during playback. Finally, use the speaker library to start the player, which will buffer and play the audio data. Read the audio data in a loop and write it to the audio stream using the Sample function.

  1. Send the audio data to the server

Next, you will use the WriteMessage function to send the recorded audio data to the server, and divide the data into multiple parts, each part Sent to other clients respectively.

func main() {

    // ...录制音频并加入服务器

    // 1. 将音频数据分包(长度为4096)
    packSize := 4096
    maxPackCount := len(buf) / packSize
    for i := 0; i < maxPackCount+1; i++ {
        n := i * packSize
        l := min(len(buf)-n, packSize)
        if l > 0 {
            bufToWrite := buf[n : n+l]
            conn.WriteMessage(websocket.BinaryMessage, bufToWrite)
        }
    }

}

func min(a, b int) int {
    if a < b {
        return a
    }
    return b
}
Copy after login

In the above code, first divide the audio data in the buf variable into multiple parts, and the length of each part is 4096. Then, each piece of audio data is sent to other clients separately.

At this point, a simple voice chat program has been completed. However, if you want to make this program more complete and stable, more detailed debugging and testing are required. However, using golang to implement voice chat function is an interesting and worth trying learning project, and the above code sample can provide some basic reference for beginners.

The above is the detailed content of Golang implements voice chat. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang and C  : Concurrency vs. Raw Speed Golang and C : Concurrency vs. Raw Speed Apr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Getting Started with Go: A Beginner's Guide Getting Started with Go: A Beginner's Guide Apr 26, 2025 am 12:21 AM

Goisidealforbeginnersandsuitableforcloudandnetworkservicesduetoitssimplicity,efficiency,andconcurrencyfeatures.1)InstallGofromtheofficialwebsiteandverifywith'goversion'.2)Createandrunyourfirstprogramwith'gorunhello.go'.3)Exploreconcurrencyusinggorout

Golang vs. C  : Performance and Speed Comparison Golang vs. C : Performance and Speed Comparison Apr 21, 2025 am 12:13 AM

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Golang's Impact: Speed, Efficiency, and Simplicity Golang's Impact: Speed, Efficiency, and Simplicity Apr 14, 2025 am 12:11 AM

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

C   and Golang: When Performance is Crucial C and Golang: When Performance is Crucial Apr 13, 2025 am 12:11 AM

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Golang vs. Python: Key Differences and Similarities Golang vs. Python: Key Differences and Similarities Apr 17, 2025 am 12:15 AM

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

Golang and C  : The Trade-offs in Performance Golang and C : The Trade-offs in Performance Apr 17, 2025 am 12:18 AM

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

See all articles