2019-01-21 08:11:49 +03:00
|
|
|
package flac
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"errors"
|
|
|
|
"io"
|
2019-01-21 10:04:15 +03:00
|
|
|
"io/ioutil"
|
2019-01-21 08:11:49 +03:00
|
|
|
|
|
|
|
"github.com/go-audio/audio"
|
|
|
|
"github.com/go-audio/wav"
|
|
|
|
"github.com/mewkiz/flac"
|
2019-01-21 10:04:15 +03:00
|
|
|
"github.com/orcaman/writerseeker"
|
2019-01-21 08:11:49 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
const wavAudioFormat = 1
|
|
|
|
|
|
|
|
// Decode takes a slice of flac and decodes to wav
|
|
|
|
func Decode(buf []byte) ([]byte, error) {
|
|
|
|
r := bytes.NewReader(buf)
|
|
|
|
stream, err := flac.Parse(r)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.New("Could not parse FLAC")
|
|
|
|
}
|
2019-01-21 10:04:15 +03:00
|
|
|
ws := &writerseeker.WriterSeeker{}
|
|
|
|
enc := wav.NewEncoder(ws, int(stream.Info.SampleRate), int(stream.Info.BitsPerSample), int(stream.Info.NChannels), wavAudioFormat)
|
2019-01-21 08:11:49 +03:00
|
|
|
defer enc.Close()
|
|
|
|
var data []int
|
2019-01-21 10:04:15 +03:00
|
|
|
var out []byte
|
|
|
|
var d []byte
|
2019-01-21 08:11:49 +03:00
|
|
|
for {
|
|
|
|
// Decode FLAC audio samples.
|
|
|
|
frame, err := stream.ParseNext()
|
|
|
|
if err != nil {
|
|
|
|
if err == io.EOF {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Encode WAV audio samples.
|
|
|
|
data = data[:0]
|
|
|
|
for i := 0; i < frame.Subframes[0].NSamples; i++ {
|
|
|
|
for _, subframe := range frame.Subframes {
|
|
|
|
data = append(data, int(subframe.Samples[i]))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
buf := &audio.IntBuffer{
|
|
|
|
Format: &audio.Format{
|
|
|
|
NumChannels: int(stream.Info.NChannels),
|
|
|
|
SampleRate: int(stream.Info.SampleRate),
|
|
|
|
},
|
|
|
|
Data: data,
|
|
|
|
SourceBitDepth: int(stream.Info.BitsPerSample),
|
|
|
|
}
|
|
|
|
if err := enc.Write(buf); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2019-01-21 10:04:15 +03:00
|
|
|
d, err = ioutil.ReadAll(ws.Reader())
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
out = append(out, d...)
|
2019-01-21 08:11:49 +03:00
|
|
|
}
|
2019-01-21 10:04:15 +03:00
|
|
|
|
|
|
|
return d, nil
|
2019-01-21 08:11:49 +03:00
|
|
|
}
|