audio/mp3: Add Decoder.SampleRate

This commit is contained in:
Hajime Hoshi 2017-06-18 22:36:56 +09:00
parent e9c6bec432
commit 6c0fa5e55f
2 changed files with 33 additions and 13 deletions

View File

@ -99,23 +99,32 @@ func (s *source) getFilepos() int {
type Decoder struct {
source *source
sampleRate int
length int64
buf []uint8
frame *frame
eof bool
}
func (d *Decoder) Read(buf []uint8) (int, error) {
for len(d.buf) == 0 && !d.eof {
func (d *Decoder) read() error {
var err error
d.frame, err = d.source.readNextFrame(d.frame)
if err != nil {
if err == io.EOF {
d.eof = true
}
return 0, err
return err
}
d.buf = append(d.buf, d.frame.decodeL3()...)
return nil
}
// Read is io.Reader's Read.
func (d *Decoder) Read(buf []uint8) (int, error) {
for len(d.buf) == 0 && !d.eof {
if err := d.read(); err != nil {
return 0, err
}
}
if d.eof {
return 0, io.EOF
@ -125,6 +134,13 @@ func (d *Decoder) Read(buf []uint8) (int, error) {
return n, nil
}
// SampleRate returns the sample rate like 44100.
//
// Note that the sample rate is retrieved from the first frame.
func (d *Decoder) SampleRate() int {
return d.sampleRate
}
// Length returns the total size in bytes.
//
// Length returns -1 when the total size is not available
@ -160,5 +176,9 @@ func decode(r io.Reader) (*Decoder, error) {
}
d.length = l
}
if err := d.read(); err != nil {
return nil, err
}
d.sampleRate = samplingFrequency[d.frame.header.sampling_frequency]
return d, nil
}

View File

@ -110,7 +110,7 @@ var mpeg1Bitrates = map[mpeg1Layer][15]int{
},
}
var samplingFrequency = [3]int{44100, 48000, 32000}
var samplingFrequency = []int{44100, 48000, 32000}
func (h *mpeg1FrameHeader) frameSize() int {
return (144*mpeg1Bitrates[h.layer][h.bitrate_index])/