简体   繁体   English

如何在Golang中使用gobuffalo / packr

[英]How to Use gobuffalo/packr with Golang

I'm trying to play a sound from Golang. 我正试图从Golang播放声音。 It's a .wav file. 这是一个.wav文件。 And I want to package the .wav file into the executable using packr 我想使用packr将.wav文件打包到可执行文件中

I have created a very small project here: packr-test repository with the code. 我在这里创建了一个非常小的项目:带有代码的packr-test存储库

When I run the executable (./packr-test) in it's default folder, the sound plays. 当我在其默认文件夹中运行可执行文件(./packr-test)时,会播放声音。 But the problem I'm having is that when I move the executable to another directory, I get an error trying to play the sound file. 但我遇到的问题是,当我将可执行文件移动到另一个目录时,我尝试播放声音文件时出错。 Which I think probably means the sound file isn't being bundled up with the executable. 我认为这可能意味着声音文件没有与可执行文件捆绑在一起。

This is on Ubuntu. 这是在Ubuntu上。 I'm using the 'play' command which is often installed by default, but if it's not there, can be done with: 我正在使用通常默认安装的'play'命令,但如果它不存在,可以使用:

sudo apt-get install sox
sudo apt-get install sox libsox-fmt-all

To use play command: 要使用播放命令:

play file_name.extension

To save you looking it up, here is my Go code: 为了节省您的查询,这是我的Go代码:

package main

import (
    "fmt"
    "os/exec"

    "github.com/gobuffalo/packr"
)

func main() {

    soundsBox := packr.NewBox("./sounds")
    if soundsBox.Has("IEEE_float_mono_32kHz.wav") {
        fmt.Println("It's there.")
    } else {
        fmt.Println("It's not there.")
    }

    args := []string{"-v20", "./sounds/IEEE_float_mono_32kHz.wav"}
    output, err := exec.Command("play", args...).Output()
    if err != nil {
        // Play command was not successful
        fmt.Println("Got an error.")
        fmt.Println(err.Error())
    } else {
        fmt.Println(string(output))
    }

}

Here is my output: 这是我的输出:

sudo ./packr-test 
It's there.
Got an error.
exit status 2

You're still referencing the file on the file system, even though you have it packed into the binary: 您仍然在文件系统上引用该文件,即使您将其打包到二进制文件中:

args := []string{"-v20", "./sounds/IEEE_float_mono_32kHz.wav"}
output, err := exec.Command("play", args...).Output()

You can grab the file data from your packr box like this: 您可以从包装箱中获取文件数据,如下所示:

bytes, err := soundsBox.FindBytes("IEEE_float_mono_32kHz.wav")

To execute the file with exec.Command() I think you'll have to write those bytes back to the file system: 要使用exec.Command()执行该文件,我认为您必须将这些字节写回文件系统:

err := ioutil.WriteFile("/tmp/IEEE_float_mono_32kHz.wav", bytes, 0755)
exec.Command("play", []string{"-v20", "/tmp/IEEE_float_mono_32kHz.wav"}

You might be able to pass your bytes to play via stdin, but that would depend on how the play binary works. 您可以通过stdin传递您的字节以进行play ,但这取决于play二进制文件的工作方式。

cmd.Stdin = bytes
cmd.Run()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM