Ejemplo n.º 1
0
func readFile(filename string) []int16 {
	file, err := os.Open(filename)
	if err != nil {
		log.Fatal(err)
	}

	// Create a decoder for the audio source
	decoder, format, err := audio.NewDecoder(file)
	if err != nil {
		log.Fatal(err)
	}
	config := decoder.Config()
	log.Printf("Decoding a %s file.\n", format)
	log.Println(config)

	// Create a buffer that can hold 3 second of audio samples
	bufSize := duration * config.SampleRate * config.Channels
	buf := make(audio.F64Samples, bufSize)

	// Fill the buffer with as many audio samples as we can
	read, err := decoder.Read(buf)
	if err != nil {
		log.Fatal(err)
	}
	readBuf := buf.Slice(0, read)
	data := make([]int16, readBuf.Len())
	for i := 0; i < readBuf.Len(); i++ {
		data[i] = int16(audio.F64ToPCM16(readBuf.At(i)))
	}
	return data
}
Ejemplo n.º 2
0
func readFile(filename string) (data []audio.PCM16, duration float64, config audio.Config) {
	file, err := os.Open(filename)
	if err != nil {
		log.Panic(err)
	}

	fi, err := file.Stat()
	if err != nil {
		log.Panic(err)
	}

	// Create a decoder for the audio source
	decoder, format, err := audio.NewDecoder(file)
	if err != nil {
		log.Panic("err: %T %v %#v", err, err, err)
	}
	config = decoder.Config()
	log.Printf("Decoding a %s file.\n", format)
	log.Println(config)

	// guess (mostly accurate for WAVs)
	duration = float64(fi.Size()) / float64(config.SampleRate*config.Channels*16/8)

	// Create a buffer that can hold 3 second of audio samples
	bufSize := int(duration * float64(config.SampleRate*config.Channels)) // undersized for flac files
	// Most WAVs are PCM16
	samples := make(audio.PCM16Samples, 0, bufSize)

	// Fill our samples slice
	var read int
	buf := make(audio.PCM16Samples, 1024*1000)
	err = nil
	for err != audio.EOS {
		var r int
		r, err = decoder.Read(buf)
		if err != nil && err != audio.EOS {
			panic(err)
		}
		read += r
		samples = append(samples, buf[:r]...)
	}

	duration = 1 / float64(config.SampleRate) * float64(read)

	return []audio.PCM16(samples)[:read], duration, config
}