这里使用Mp3库为:

https://github.com/faiface/beep

这个库可解析播放的文件有WAV, MP3, OGG和FLAC。

参考官方的Wiki文档可以写出如下测试文件:

package musicplayer
 
import (
	"fmt"
	"github.com/faiface/beep/mp3"
	"github.com/faiface/beep/speaker"
	"log"
	"os"
	"time"
)
 
type MusicEntry struct {
	Id         string   //编号
	Name       string   //歌名
	Artist     string   //作者
	Source     string   //位置
	Type       string   //类型
	Filestream *os.File // 文件流
}
 
func (me *MusicEntry) Open() {
	var err error
	me.Filestream, err = os.Open(me.Source)
	if err != nil {
		log.Fatal(err)
	}
}
 
func (me *MusicEntry) Play() {
	streamer, format, err := mp3.Decode(me.Filestream)
	if err != nil {
		log.Fatal(err)
	}
	defer streamer.Close()
 
	speaker.Init(format.SampleRate, format.SampleRate.N(time.Second/10))
	fmt.Println("music length :", streamer.Len())
	speaker.Play(streamer)
	select {}
}

上面的Play函数中考虑到speaker.Play(streamer)是异步调用,所以使用了select进行阻塞。如果要实现停止操作,则使用for语名再配合select对通信信号进行监听就好了。

我这里使用的Go语言版本为1.13.8,操作系统为macOS Catalina,所以在编译过程中会出现如下警告,但不影响使用:

# github.com/hajimehoshi/oto
../../go/pkg/mod/github.com/hajimehoshi/oto@v0.3.1/driver_openal.go:35:22: warning: 'alcOpenDevice' is deprecated: first deprecated in macOS 10.15 - OpenAL is deprecated in favor of AVAudioEngine [-Wdeprecated-declarations]
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/OpenAL.framework/Headers/alc.h:209:38: note: 'alcOpenDevice' has been explicitly marked deprecated here
../../go/pkg/mod/github.com/hajimehoshi/oto@v0.3.1/driver_openal.go:39:11: warning: 'alcCloseDevice' is deprecated: first deprecated in macOS 10.15 - OpenAL is deprecated in favor of AVAudioEngine [-Wdeprecated-declarations]