Files
zhaoyupeng.elqbandTRAE CLI 81deca8c8e feat: initialize Eino examples and ADK applications
Include chat, weather, image, travel, streaming ASR and text examples,
shared model initialization, documentation, and existing tests.

Co-authored-by: TRAE CLI <traecli@bytedance.com>
2026-11-19 11:08:03 +08:00

118 lines
3.0 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package internal
import (
"bufio"
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"os"
"os/exec"
"runtime"
"sync/atomic"
"github.com/cloudwego/eino/schema"
)
// Record 从 macOS 默认示例设备采集 PCM,回车停止录音并结束音频流。
func Record(ctx context.Context) (*schema.StreamReader[[]byte], func(), error) {
if runtime.GOOS != "darwin" {
return nil, nil, fmt.Errorf("麦克风示例只支持 macOS")
}
if _, err := exec.LookPath("ffmpeg"); err != nil {
return nil, nil, fmt.Errorf("请先安装 ffmpeg:brew install ffmpeg")
}
cmd := exec.CommandContext(ctx, "ffmpeg", "-nostdin", "-hide_banner", "-loglevel", "error",
"-f", "avfoundation", "-i", ":0", "-t", "15",
"-ac", "1", "-ar", "24000", "-c:a", "pcm_s16le", "-f", "s16le", "pipe:1")
cmd.Stderr = os.Stderr
return record(cmd, os.Stdin)
}
func record(cmd *exec.Cmd, input io.Reader) (*schema.StreamReader[[]byte], func(), error) {
pcm, err := cmd.StdoutPipe()
if err != nil {
return nil, nil, err
}
if err := cmd.Start(); err != nil {
return nil, nil, fmt.Errorf("启动录音失败: %w", err)
}
fmt.Println("开始录音,连续静音 1 秒或按回车结束,最长 15 秒。")
var stopped atomic.Bool
finish := func() {
if stopped.CompareAndSwap(false, true) {
// 只停止 ffmpeg,让 Chain 读完音频并提交 ASR。
_ = cmd.Process.Signal(os.Interrupt)
}
}
go func() {
if _, err := bufio.NewReader(input).ReadString('\n'); err == nil {
finish()
}
}()
audio, writer := schema.Pipe[[]byte](150)
// Chain 和退出清理都可能关闭输入,允许重复 Close。
audio.SetAutomaticClose()
done := make(chan struct{})
go func() {
defer close(done)
defer writer.Close()
silent := 0
for {
chunk := make([]byte, pcmChunkSize)
n, readErr := io.ReadFull(pcm, chunk)
if n == pcmChunkSize {
if isQuiet(chunk) {
silent++
if silent == 10 {
fmt.Println("检测到连续静音,结束录音。")
finish()
}
} else {
silent = 0
}
}
if n > 0 && writer.Send(chunk[:n], nil) {
_ = cmd.Process.Kill()
_ = cmd.Wait()
return
}
if readErr == nil {
continue
}
if err := cmd.Wait(); err != nil {
var exitErr *exec.ExitError
if !stopped.Load() || !errors.As(err, &exitErr) || exitErr.ExitCode() != 255 {
writer.Send(nil, fmt.Errorf("录音失败: %w", err))
return
}
}
if readErr != io.EOF && readErr != io.ErrUnexpectedEOF {
writer.Send(nil, fmt.Errorf("读取录音失败: %w", readErr))
}
return
}
}()
return audio, func() {
audio.Close()
_ = cmd.Process.Kill()
<-done
}, nil
}
// isQuiet 用 PCM 的均方能量判断静音,不把普通静音当成设备断流。
func isQuiet(chunk []byte) bool {
const threshold = 300 // 约 -41 dBFS。
var energy int64
for i := 0; i+1 < len(chunk); i += 2 {
sample := int64(int16(binary.LittleEndian.Uint16(chunk[i:])))
energy += sample * sample
}
return energy < int64(len(chunk)/2)*threshold*threshold
}