Skip to content

Commit

Permalink
Add go bindings
Browse files Browse the repository at this point in the history
  • Loading branch information
nshmyrev committed Jul 10, 2021
1 parent 5965ea3 commit fee63d7
Show file tree
Hide file tree
Showing 2 changed files with 98 additions and 0 deletions.
36 changes: 36 additions & 0 deletions go/example/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package main

import (
"flag"
"os"
".."
)

func main() {
var filename string
flag.StringVar(&filename, "f", "", "file to transcribe")
flag.Parse()
model, err := vosk.NewModel("model")
rec, err := vosk.NewRecognizer(model)

file, err := os.Open(filename)
if err != nil {
panic(err)
}
defer file.Close()

fileinfo, err := file.Stat()
if err != nil {
panic(err)
}

filesize := fileinfo.Size()
buffer := make([]byte, filesize)

_, err = file.Read(buffer)
if err != nil {
panic(err)
}

println(vosk.VoskFinalResult(rec, buffer))
}
62 changes: 62 additions & 0 deletions go/vosk.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package vosk

// #cgo CPPFLAGS: -I ${SRCDIR}/../src
// #cgo LDFLAGS: -L ${SRCDIR}/../src -lvosk -ldl -lpthread
// #include <stdlib.h>
// #include <vosk_api.h>
import "C"

// VoskModel contains a reference to the C VoskModel
type VoskModel struct {
model *C.struct_VoskModel
}

// VoskSpkModel contains a reference to the C VoskSpkModel
type VoskSpkModel struct {
spkModel *C.struct_VoskSpkModel
}

// VoskRecognizer contains a reference to the C VoskRecognizer
type VoskRecognizer struct {
rec *C.struct_VoskRecognizer
}

func VoskFinalResult(recognizer *VoskRecognizer, buffer []byte) string {
cbuf := C.CBytes(buffer)
defer C.free(cbuf)
_ = C.vosk_recognizer_accept_waveform(recognizer.rec, (*C.char)(cbuf), C.int(len(buffer)))
result := C.GoString(C.vosk_recognizer_final_result(recognizer.rec))
return result
}

// NewModel creates a new VoskModel instance
func NewModel(modelPath string) (*VoskModel, error) {
var internal *C.struct_VoskModel
internal = C.vosk_model_new(C.CString(modelPath))
model := &VoskModel{model: internal}
return model, nil
}

// NewRecognizer creates a new VoskRecognizer instance
func NewRecognizer(model *VoskModel) (*VoskRecognizer, error) {
var internal *C.struct_VoskRecognizer
internal = C.vosk_recognizer_new(model.model, 16000.0)
rec := &VoskRecognizer{rec: internal}
return rec, nil
}

func freeModel(model *VoskModel) {
C.vosk_model_free(model.model)
}

func freeRecognizer(recognizer *VoskRecognizer) {
C.vosk_recognizer_free(recognizer.rec)
}

// NewSpkModel creates a new VoskSpkModel instance
func NewSpkModel(spkModelPath string) (*VoskSpkModel, error) {
var internal *C.struct_VoskSpkModel
internal = C.vosk_spk_model_new(C.CString(spkModelPath))
spkModel := &VoskSpkModel{spkModel: internal}
return spkModel, nil
}

0 comments on commit fee63d7

Please sign in to comment.