wav-master/0000775000175000017500000000000013264634400011644 5ustar arunarunwav-master/.gitignore0000664000175000017500000000037413264634400013640 0ustar arunarun# Compiled Object files, Static and Dynamic libs (Shared Objects) *.o *.a *.so # Folders _obj _test # Architecture specific extensions/prefixes *.[568vq] [568vq].out *.cgo1.go *.cgo2.c _cgo_defun.c _cgo_gotypes.go _cgo_export.* _testmain.go *.exe wav-master/writer.go0000664000175000017500000000566013264634400013516 0ustar arunarunpackage wav import ( "bufio" "encoding/binary" "fmt" "io" "os" ) type output interface { io.Writer io.Seeker io.Closer } // Writer encapsulates a io.WriteSeeker and supplies Functions for writing samples type Writer struct { output options File sampleBuf *bufio.Writer bytesWritten int } // NewWriter creates a new WaveWriter and writes the header to it func (file File) NewWriter(out output) (wr *Writer, err error) { if file.Channels != 1 { err = fmt.Errorf("sorry, only mono currently") return } wr = &Writer{} wr.output = out wr.sampleBuf = bufio.NewWriter(out) wr.options = file // write header when close to get correct number of samples _, err = wr.Seek(12, os.SEEK_SET) if err != nil { return } // fmt.Fprintf(wr, "%s", tokenChunkFmt) n, err := wr.output.Write(tokenChunkFmt[:]) if err != nil { return } wr.bytesWritten += n chunkFmt := riffChunkFmt{ LengthOfHeader: 16, AudioFormat: 1, NumChannels: file.Channels, SampleRate: file.SampleRate, BytesPerSec: uint32(file.Channels) * file.SampleRate * uint32(file.SignificantBits) / 8, BytesPerBloc: file.SignificantBits / 8 * file.Channels, BitsPerSample: file.SignificantBits, } err = binary.Write(wr.output, binary.LittleEndian, chunkFmt) if err != nil { return } wr.bytesWritten += 20 //sizeof riffChunkFmt n, err = wr.output.Write(tokenData[:]) if err != nil { return } wr.bytesWritten += n // leave space for the data size _, err = wr.Seek(4, os.SEEK_CUR) if err != nil { return } return } // WriteInt32 writes the sample to the file using the binary package func (w *Writer) WriteInt32(sample int32) error { err := binary.Write(w.sampleBuf, binary.LittleEndian, sample) if err != nil { return err } w.bytesWritten += 4 return err } // WriteSample writes a []byte array to file without conversion func (w *Writer) WriteSample(sample []byte) error { if len(sample)*8 != int(w.options.SignificantBits) { return fmt.Errorf("incorrect Sample Length %d", len(sample)) } n, err := w.sampleBuf.Write(sample) if err != nil { return err } w.bytesWritten += n return nil } func (w *Writer) Write(data []byte) (int, error) { n, err := w.output.Write(data) w.bytesWritten += n return n, err } // Close corrects the filesize information in the header func (w *Writer) Close() error { if err := w.sampleBuf.Flush(); err != nil { return err } _, err := w.Seek(0, os.SEEK_SET) if err != nil { return err } header := riffHeader{ ChunkSize: uint32(w.bytesWritten + 8), } copy(header.Ftype[:], tokenRiff[:]) copy(header.ChunkFormat[:], tokenWaveFormat[:]) err = binary.Write(w.output, binary.LittleEndian, header) if err != nil { return err } // write data chunk size _, err = w.Seek(0x28, os.SEEK_SET) if err != nil { return err } // write chunk size err = binary.Write(w.output, binary.LittleEndian, int32(w.bytesWritten)) if err != nil { return err } return w.output.Close() } wav-master/fuzz.go0000664000175000017500000000054113264634400013171 0ustar arunarun// +build gofuzz package wav import ( "bytes" "io" ) func Fuzz(data []byte) int { rd, err := NewReader(bytes.NewReader(data), int64(len(data))) if err != nil { if rd != nil { panic("rd != nil on error") } return 0 } for { _, err = rd.ReadSample() if err != nil { if err == io.EOF { break } return 0 } } return 1 } wav-master/rw_test.go0000664000175000017500000000337013264634400013665 0ustar arunarunpackage wav import ( "io/ioutil" "math" "os" "testing" "github.com/cheekybits/is" ) func TestWriteRead_Int32(t *testing.T) { is := is.New(t) const ( bits = 32 rate = 44100 ) f, err := ioutil.TempFile("", "wavPkgtest") is.NoErr(err) testFname := f.Name() meta := File{ Channels: 1, SampleRate: rate, SignificantBits: bits, } writer, err := meta.NewWriter(f) is.NoErr(err) var freq float64 freq = 0.0001 // one second for n := 0; n < rate; n++ { y := int32(0.8 * math.Pow(2, bits-1) * math.Sin(freq*float64(n))) freq += 0.000002 err = writer.WriteInt32(y) if err != nil { t.Fatal(err) } } err = writer.Close() is.NoErr(err) f, err = os.Open(testFname) is.NoErr(err) stat, err := f.Stat() is.NoErr(err) _, err = NewReader(f, stat.Size()) is.NoErr(err) is.NoErr(os.Remove(testFname)) } func TestWriteRead_Sample(t *testing.T) { is := is.New(t) const ( bits = 16 rate = 44100 ) f, err := ioutil.TempFile("", "wavPkgtest") is.NoErr(err) testFname := f.Name() meta := File{ Channels: 1, SampleRate: rate, SignificantBits: bits, } writer, err := meta.NewWriter(f) is.NoErr(err) var freq float64 freq = 0.0001 var s = make([]byte, 2) // one second for n := 0; n < rate; n++ { y := int32(0.8 * math.Pow(2, bits-1) * math.Sin(freq*float64(n))) freq += 0.000002 // s[3] = byte((y >> 24) & 0xFF) // s[2] = byte((y >> 16) & 0xFF) s[1] = byte((y >> 8) & 0xFF) s[0] = byte(y & 0xFF) err = writer.WriteSample(s) if err != nil { t.Fatal(err) } } err = writer.Close() is.NoErr(err) f, err = os.Open(testFname) is.NoErr(err) stat, err := f.Stat() is.NoErr(err) _, err = NewReader(f, stat.Size()) is.NoErr(err) is.NoErr(os.Remove(testFname)) } wav-master/README.md0000664000175000017500000000076513264634400013133 0ustar arunarunwav === [![GoDoc](https://godoc.org/github.com/cryptix/wav?status.svg)](https://godoc.org/github.com/cryptix/wav) [![Build Status](https://travis-ci.org/cryptix/wav.png?branch=master)](https://travis-ci.org/cryptix/wav) [![wercker status](https://app.wercker.com/status/d23488f1a04c695b0ad57fe5a647d0ec "wercker status")](https://app.wercker.com/project/bykey/d23488f1a04c695b0ad57fe5a647d0ec) golang .wav reader and writer ## Todo * Use `type WavFile` for Reader * Implement Stereo interleaving wav-master/examples/0000775000175000017500000000000013264634400013462 5ustar arunarunwav-master/examples/simpleReadEvery/0000775000175000017500000000000013264634400016562 5ustar arunarunwav-master/examples/simpleReadEvery/main.go0000664000175000017500000000237713264634400020046 0ustar arunarunpackage main import ( "fmt" "log" "os" "github.com/cryptix/wav" ) func main() { if len(os.Args) != 2 { fmt.Fprintf(os.Stderr, "Usage: simpleReadEvery \n") os.Exit(1) } testInfo, err := os.Stat(os.Args[1]) checkErr(err) testWav, err := os.Open(os.Args[1]) checkErr(err) wavReader, err := wav.NewReader(testWav, testInfo.Size()) checkErr(err) fmt.Println("Hello, wav") fmt.Println(wavReader) // Load file meta var meta wav.File meta = wavReader.GetFile() // Every half a second read a sample readSampleRate := meta.SampleRate / uint32(4) fmt.Println("Read a sample every", readSampleRate) // Number of samples to average together (if any) var averageBy int averageBy = 20 // 10, 40, 345, 1000, etc... samples, err := wavReader.ReadSampleEvery(readSampleRate, averageBy) if err != nil { log.Fatal(err) } fmt.Printf("Samples found %d, Estimated: %d\n", len(samples), meta.NumberOfSamples/readSampleRate+1) var second uint32 for i, sample := range samples { pos := uint32(i) // What second of audio are we on? second = readSampleRate * pos / meta.SampleRate fmt.Printf("Second %d\tSample: %d\tAmplitude: %d\n", second, pos*readSampleRate, sample) } } func checkErr(err error) { if err != nil { panic(err) } } wav-master/examples/simpleRead/0000775000175000017500000000000013264634400015547 5ustar arunarunwav-master/examples/simpleRead/main.go0000664000175000017500000000122713264634400017024 0ustar arunarunpackage main import ( "fmt" "io" "os" "github.com/cryptix/wav" ) func main() { if len(os.Args) != 2 { fmt.Fprintf(os.Stderr, "Usage: simpleRead \n") os.Exit(1) } testInfo, err := os.Stat(os.Args[1]) checkErr(err) testWav, err := os.Open(os.Args[1]) checkErr(err) wavReader, err := wav.NewReader(testWav, testInfo.Size()) checkErr(err) fmt.Println("Hello, wav") fmt.Println(wavReader) sampleLoop: for { s, err := wavReader.ReadRawSample() if err == io.EOF { break sampleLoop } else if err != nil { panic(err) } fmt.Printf("Sample: <%v>\n", s) } } func checkErr(err error) { if err != nil { panic(err) } } wav-master/examples/plotWav/0000775000175000017500000000000013264634400015116 5ustar arunarunwav-master/examples/plotWav/main.go0000664000175000017500000000253013264634400016371 0ustar arunarunpackage main import ( "fmt" "io" "os" "path" "strings" "github.com/cryptix/wav" "gonum.org/v1/plot" "gonum.org/v1/plot/plotter" "gonum.org/v1/plot/plotutil" "gonum.org/v1/plot/vg" ) func main() { if len(os.Args) != 2 { fmt.Fprintf(os.Stderr, "Usage: plotWav \n") os.Exit(1) } // open file testInfo, err := os.Stat(os.Args[1]) checkErr(err) testWav, err := os.Open(os.Args[1]) checkErr(err) wavReader, err := wav.NewReader(testWav, testInfo.Size()) checkErr(err) // File informations fmt.Println(wavReader) // limit sample count sampleCnt := wavReader.GetSampleCount() if sampleCnt > 10000 { sampleCnt = 10000 } // setup plotter p, err := plot.New() checkErr(err) p.Title.Text = "Waveplot" p.X.Label.Text = "t" p.Y.Label.Text = "Ampl" pts := make(plotter.XYs, sampleCnt) // read samples and construct points for plot for i := range pts { n, err := wavReader.ReadSample() if err == io.EOF { break } checkErr(err) pts[i].X = float64(i) pts[i].Y = float64(n) } err = plotutil.AddLinePoints(p, "", pts) checkErr(err) // construct output filename inputFname := path.Base(os.Args[1]) plotFname := strings.Split(inputFname, ".")[0] + ".pdf" if err := p.Save(10*vg.Inch, 4*vg.Inch, plotFname); err != nil { panic(err) } } func checkErr(err error) { if err != nil { panic(err) } } wav-master/examples/simpleSweep/0000775000175000017500000000000013264634400015757 5ustar arunarunwav-master/examples/simpleSweep/main.go0000664000175000017500000000133513264634400017234 0ustar arunarunpackage main import ( "fmt" "math" "os" "time" "github.com/cryptix/wav" ) const ( bits = 32 rate = 44100 ) func main() { wavOut, err := os.Create("Test.wav") checkErr(err) defer wavOut.Close() meta := wav.File{ Channels: 1, SampleRate: rate, SignificantBits: bits, } writer, err := meta.NewWriter(wavOut) checkErr(err) defer writer.Close() start := time.Now() var freq float64 freq = 0.0001 for n := 0; n < 50*rate; n += 1 { y := int32(0.8 * math.Pow(2, bits-1) * math.Sin(freq*float64(n))) freq += 0.000002 err = writer.WriteInt32(y) checkErr(err) } fmt.Printf("Simulation Done. Took:%v\n", time.Since(start)) } func checkErr(err error) { if err != nil { panic(err) } } wav-master/examples/demux/0000775000175000017500000000000013264634400014604 5ustar arunarunwav-master/examples/demux/main.go0000664000175000017500000000360113264634400016057 0ustar arunarunpackage main import ( "encoding/json" "fmt" "log" "os" "github.com/cryptix/wav" ) // Demux a 2 channel audio file and save the left channel as a mono file // http://blog.bjornroche.com/2013/05/the-abcs-of-pcm-uncompressed-digital.html func main() { if len(os.Args) != 2 { fmt.Fprintf(os.Stderr, "Usage: demux \n") os.Exit(1) } testInfo, err := os.Stat(os.Args[1]) checkErr(err) testWav, err := os.Open(os.Args[1]) checkErr(err) wavReader, err := wav.NewReader(testWav, testInfo.Size()) checkErr(err) fileMeta := wavReader.GetFile() fmt.Println(dump(fileMeta)) if fileMeta.Channels != 2 { log.Fatal("Please use a 2-channel audio file") } // A slice of many 1-4 byte samples var left [][]byte left = make([][]byte, fileMeta.NumberOfSamples/2) var i uint32 var buf []byte for i = 0; i < fileMeta.NumberOfSamples/2; i++ { buf, err = wavReader.ReadRawSample() checkErr(err) left[i] = buf // Throw the right-channel away _, err = wavReader.ReadRawSample() checkErr(err) } filename := "mono-" + testInfo.Name() os.Remove(filename) f, err := os.Create(filename) checkErr(err) // Create the headers for our new mono file meta := wav.File{ Channels: 1, SampleRate: fileMeta.SampleRate, SignificantBits: fileMeta.SignificantBits, } writer, err := meta.NewWriter(f) checkErr(err) // Write to file for _, sample := range left { err = writer.WriteSample(sample) checkErr(err) } err = writer.Close() checkErr(err) fmt.Println("Created Mono File", f.Name()) f, err = os.Open(f.Name()) checkErr(err) stat, err := f.Stat() checkErr(err) wavReader, err = wav.NewReader(f, stat.Size()) checkErr(err) fileMeta = wavReader.GetFile() fmt.Println(dump(fileMeta)) } func checkErr(err error) { if err != nil { panic(err) } } func dump(v interface{}) string { b, _ := json.MarshalIndent(v, "", " ") return string(b) } wav-master/wercker.yml0000664000175000017500000000002413264634400014025 0ustar arunarunbox: wercker/golang wav-master/.travis.yml0000664000175000017500000000015013264634400013751 0ustar arunarunlanguage: go install: - go get -d -v ./... - go get github.com/cheekybits/is - go build -v ./... wav-master/LICENSE0000664000175000017500000004315213264634400012656 0ustar arunarunGNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {description} Copyright (C) {year} {fullname} This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. {signature of Ty Coon}, 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. wav-master/corpus/0000775000175000017500000000000013264634400013157 5ustar arunarunwav-master/corpus/headers_zerosamples.wav0000664000175000017500000000040613264634400017735 0ustar arunarunRIFFWAVEfmt DXLISTHINFOINAMtestIARTtestICMTtestICRD2015IGNRestdataid3 ID3@x   Gg%mTCONestTRCKtestTALBtestTIT2testTDRC2015COMM testTPE1testwav-master/corpus/24_50samples.wav0000664000175000017500000000030213264634400016007 0ustar arunarunRIFFWAVEfmt DdataMP 2$g*o/48M:W5"0$2*#Y~+n+<""r?q붼2, :-,mzR`Yq6wav-master/corpus/16_50samples.wav0000664000175000017500000000022013264634400016007 0ustar arunarunRIFFWAVEfmt DXdatadM $i*/48<@@CE~FGFFGDAa>Q:5(0.*#(16@p070nz\8wav-master/corpus/24bit.wav0000664000175000017500000000005713264634400014624 0ustar arunarunRIFF'WAVEfmt Ddatawav-master/corpus/16bit.wav0000664000175000017500000000005613264634400014624 0ustar arunarunRIFF&WAVEfmt DXdatawav-master/corpus/u8bit.wav0000664000175000017500000000005513264634400014731 0ustar arunarunRIFF%WAVEfmt DDdatawav-master/writer_test.go0000664000175000017500000000614313264634400014552 0ustar arunarunpackage wav import ( "bytes" "io/ioutil" "os" "testing" "github.com/cheekybits/is" ) var wf = File{ SampleRate: 44100, Channels: 1, SignificantBits: 16, } func TestNewWriter_Header(t *testing.T) { t.Parallel() is := is.New(t) f, err := ioutil.TempFile("", "wavPkgtest") is.NoErr(err) wr, err := wf.NewWriter(f) is.NoErr(err) is.Nil(wr.Close()) f, err = os.Open(f.Name()) is.NoErr(err) b, err := ioutil.ReadAll(f) is.NoErr(err) is.Equal(len(b), 44) is.True(bytes.Contains(b, riff)) is.True(bytes.Contains(b, wave)) is.True(bytes.Contains(b, fmt20)) is.Nil(os.Remove(f.Name())) } func TestNewWriter_1Sample(t *testing.T) { t.Parallel() is := is.New(t) f, err := ioutil.TempFile("", "wavPkgtest") is.NoErr(err) wr, err := wf.NewWriter(f) is.NoErr(err) err = wr.WriteSample([]byte{1, 1}) is.NoErr(err) is.Nil(wr.Close()) f, err = os.Open(f.Name()) is.NoErr(err) b, err := ioutil.ReadAll(f) is.NoErr(err) is.Equal(len(b), 46) is.True(bytes.Contains(b, riff)) is.True(bytes.Contains(b, wave)) is.True(bytes.Contains(b, fmt20)) is.Nil(os.Remove(f.Name())) } func bWriteByteSlice(sample []byte, samples int, b *testing.B) { b.StopTimer() is := is.New(b) f, err := ioutil.TempFile("", "wavPkgtest") is.NoErr(err) defer os.Remove(f.Name()) wr, err := wf.NewWriter(f) defer wr.Close() is.NoErr(err) b.SetBytes(int64(2 * samples)) b.StartTimer() for i := 0; i < b.N; i++ { for i := 0; i < samples; i++ { if err := wr.WriteSample(sample); err != nil { b.Fatal(err) } } } } func BenchmarkWriteBuf_16sample(b *testing.B) { bWriteByteSlice([]byte{0, 0}, 16, b) } func BenchmarkWriteBuf_32sample(b *testing.B) { bWriteByteSlice([]byte{0, 0}, 32, b) } func BenchmarkWriteBuf_64sample(b *testing.B) { bWriteByteSlice([]byte{0, 0}, 64, b) } func BenchmarkWriteBuf_10thSec(b *testing.B) { bWriteByteSlice([]byte{0, 0}, 44100/10, b) } func BenchmarkWriteBuf_HalfSec(b *testing.B) { bWriteByteSlice([]byte{0, 0}, 44100/2, b) } func BenchmarkWriteBuf_1Sec(b *testing.B) { bWriteByteSlice([]byte{0, 0}, 44100, b) } func BenchmarkWriteBuf_2Sec(b *testing.B) { bWriteByteSlice([]byte{0, 0}, 2*44100, b) } func benchWriteInt(sample int32, samples int, b *testing.B) { b.StopTimer() is := is.New(b) f, err := ioutil.TempFile("", "wavPkgtest") is.NoErr(err) defer os.Remove(f.Name()) wr, err := wf.NewWriter(f) defer wr.Close() is.NoErr(err) b.SetBytes(int64(2 * samples)) b.StartTimer() for i := 0; i < b.N; i++ { for i := 0; i < samples/2; i++ { if err := wr.WriteInt32(sample); err != nil { b.Fatal(err) } } } } func BenchmarkWriteInt32_16sample(b *testing.B) { benchWriteInt(0, 16, b) } func BenchmarkWriteInt32_32sample(b *testing.B) { benchWriteInt(0, 32, b) } func BenchmarkWriteInt32_64sample(b *testing.B) { benchWriteInt(0, 64, b) } func BenchmarkWriteInt32_10thSec(b *testing.B) { benchWriteInt(0, 44100/10, b) } func BenchmarkWriteInt32_HalfSec(b *testing.B) { benchWriteInt(0, 44100/2, b) } func BenchmarkWriteInt32_1Sec(b *testing.B) { benchWriteInt(0, 44100, b) } func BenchmarkWriteInt32_2Sec(b *testing.B) { benchWriteInt(0, 2*44100, b) } wav-master/reader_test.go0000664000175000017500000001676013264634400014506 0ustar arunarunpackage wav import ( "bytes" "io" "strings" "testing" "github.com/cheekybits/is" ) var ( riff = []byte{0x52, 0x49, 0x46, 0x46} // "RIFF" chunkSize24 = []byte{0x24, 0x00, 0x00, 0x00} // chunkSize wave = []byte{0x57, 0x41, 0x56, 0x45} // "WAVE" fmt20 = []byte{0x66, 0x6d, 0x74, 0x20} // "fmt " testRiffChunkFmt = []byte{ 0x10, 0x00, 0x00, 0x00, // LengthOfHeader 0x01, 0x00, // AudioFormat 0x01, 0x00, // NumOfChannels 0x44, 0xac, 0x00, 0x00, // SampleRate 0x88, 0x58, 0x01, 0x00, // BytesPerSec 0x02, 0x00, // BytesPerBloc 0x10, 0x00, // BitsPerSample 0x64, 0x61, 0x74, 0x61, // "data" } wavWithOneSample []byte ) func init() { var b bytes.Buffer b.Write(riff) b.Write([]byte{0x26, 0x00, 0x00, 0x00}) // chunkSize b.Write(wave) b.Write(fmt20) b.Write(testRiffChunkFmt) b.Write([]byte{0x02, 0x00, 0x00, 0x00}) // 2 bytes of samples - this part of the header is why wav length is capped at 32bit b.Write([]byte{0x01, 0x01}) wavWithOneSample = b.Bytes() } func TestNewReader_inputTooLarge(t *testing.T) { t.Parallel() is := is.New(t) _, err := NewReader( bytes.NewReader([]byte{}), 99999999999999999) is.Equal(err, ErrInputToLarge) } func TestParseHeaders_complete(t *testing.T) { t.Parallel() is := is.New(t) // Parsing the header of an wav with 0 samples var b bytes.Buffer b.Write(riff) b.Write(chunkSize24) b.Write(wave) b.Write(fmt20) b.Write(testRiffChunkFmt) b.Write([]byte{0x00, 0x00, 0x00, 0x00}) wavFile := bytes.NewReader(b.Bytes()) wavReader, err := NewReader(wavFile, int64(b.Len())) is.NoErr(err) is.Equal(uint32(0), wavReader.GetSampleCount()) is.Equal(File{ SampleRate: 44100, Channels: 1, SignificantBits: 16, AudioFormat: 1, Canonical: true, BytesPerSecond: 88200, }, wavReader.GetFile()) } func TestParseHeaders_tooShort(t *testing.T) { t.Parallel() is := is.New(t) wavData := append(riff, 0x08, 0x00) wavFile := bytes.NewReader(wavData) _, err := NewReader(wavFile, int64(len(wavData))) is.Err(err) is.Equal(err, io.ErrUnexpectedEOF) } func TestParseHeaders_chunkFmtMissing(t *testing.T) { t.Parallel() is := is.New(t) var b bytes.Buffer b.Write(riff) b.Write([]byte{0x04, 0x00, 0x00, 0x00}) // chunkSize b.Write(wave) wavFile := bytes.NewReader(b.Bytes()) _, err := NewReader(wavFile, int64(b.Len())) is.Err(err) is.Equal(err, io.ErrUnexpectedEOF) } func TestParseHeaders_chunkFmtTooShort(t *testing.T) { t.Parallel() is := is.New(t) var b bytes.Buffer b.Write(riff) b.Write([]byte{0x08, 0x00, 0x00, 0x00}) // chunkSize b.Write(wave) b.Write(fmt20) wavFile := bytes.NewReader(b.Bytes()) _, err := NewReader(wavFile, int64(b.Len())) is.Err(err) is.Equal(err, io.ErrUnexpectedEOF) } func TestParseHeaders_chunkFmtTooShort2(t *testing.T) { t.Parallel() is := is.New(t) var b bytes.Buffer b.Write(riff) b.Write([]byte{0x0a, 0x00, 0x00, 0x00}) // chunkSize b.Write(wave) b.Write(fmt20) b.Write([]byte{0, 0}) wavFile := bytes.NewReader(b.Bytes()) _, err := NewReader(wavFile, int64(b.Len())) is.Err(err) is.Equal(err, io.ErrUnexpectedEOF) } func TestParseHeaders_corruptRiff(t *testing.T) { t.Parallel() is := is.New(t) var b bytes.Buffer b.Write([]byte{0x52, 0, 0x46, 0x46}) // "R\0FF" b.Write(chunkSize24) b.Write(wave) wavFile := bytes.NewReader(b.Bytes()) _, err := NewReader(wavFile, int64(b.Len())) is.Err(err) is.Equal(ErrNotRiff, err) } func TestParseHeaders_chunkSizeNull(t *testing.T) { t.Parallel() is := is.New(t) var b bytes.Buffer b.Write(riff) b.Write([]byte{0x00, 0x00, 0x00, 0x00}) // chunkSize b.Write(wave) b.Write(fmt20) wavFile := bytes.NewReader(b.Bytes()) _, err := NewReader(wavFile, int64(b.Len())) is.Err(err) is.Equal(ErrIncorrectChunkSize{8, 16}, err) is.Equal("Incorrect ChunkSize. Got[8] Wanted[16]", err.Error()) } func TestParseHeaders_notWave(t *testing.T) { t.Parallel() is := is.New(t) var b bytes.Buffer b.Write(riff) b.Write([]byte{0x09, 0x00, 0x00, 0x00}) // chunkSize b.Write([]byte{0x57, 0x42, 0x56, 0x45}) // "WBVE" b.Write(fmt20) b.Write([]byte{0}) wavFile := bytes.NewReader(b.Bytes()) _, err := NewReader(wavFile, int64(b.Len())) is.Err(err) is.Equal(ErrNotWave, err) } func TestParseHeaders_fmtNotSupported(t *testing.T) { t.Parallel() is := is.New(t) var b bytes.Buffer b.Write(riff) b.Write(chunkSize24) b.Write(wave) b.Write(fmt20) b.Write(testRiffChunkFmt) b.Write([]byte{0x00, 0x00, 0x00, 0x00}) buf := b.Bytes() buf[21] = 2 // change byte 5 of riffChunk wavFile := bytes.NewReader(buf) _, err := NewReader(wavFile, int64(b.Len())) is.Err(err) is.Equal(ErrFormatNotSupported, err) } func TestReadSample_Raw(t *testing.T) { t.Parallel() is := is.New(t) wavFile := bytes.NewReader(wavWithOneSample) wavReader, err := NewReader(wavFile, int64(len(wavWithOneSample))) is.NoErr(err) is.Equal(uint32(1), wavReader.GetSampleCount()) rawSample, err := wavReader.ReadRawSample() is.NoErr(err) is.Equal([]byte{1, 1}, rawSample) } func TestReadSample(t *testing.T) { t.Parallel() is := is.New(t) wavFile := bytes.NewReader(wavWithOneSample) wavReader, err := NewReader(wavFile, int64(len(wavWithOneSample))) is.NoErr(err) is.Equal(uint32(1), wavReader.GetSampleCount()) sample, err := wavReader.ReadSample() is.NoErr(err) is.Equal(257, sample) } // panic: runtime error: invalid memory address or nil pointer dereference // [signal 0xb code=0x1 addr=0x4 pc=0x4399fb] // // goroutine 1 [running]: // github.com/cryptix/wav.(*Reader).parseHeaders(0xc208033720, 0x0, 0x0) // /tmp/go-fuzz-build857960013/src/github.com/cryptix/wav/reader.go:191 +0xe3b // github.com/cryptix/wav.NewReader(0x7f23a9550bd8, 0xc208037c80, 0x2d, 0xc208033720, 0x0, 0x0) // /tmp/go-fuzz-build857960013/src/github.com/cryptix/wav/reader.go:64 +0x177 // github.com/cryptix/wav.Fuzz(0x7f23a92cf000, 0x2d, 0x100000, 0x2) // /tmp/go-fuzz-build857960013/src/github.com/cryptix/wav/fuzz.go:12 +0x167 // github.com/dvyukov/go-fuzz/go-fuzz-dep.Main(0x570c60, 0x5d4200, 0x5f6, 0x5f6) // /home/cryptix/go/src/github.com/dvyukov/go-fuzz/go-fuzz-dep/main.go:64 +0x309 // main.main() // /tmp/go-fuzz-build857960013/src/go-fuzz-main/main.go:10 +0x4e // exit status 2 func TestReadFuzzed_panic1(t *testing.T) { t.Parallel() is := is.New(t) wavFile := strings.NewReader("RIFF%\x00\x00\x00WAVE0000\x10\x00\x00\x000000000000000000data00000") _, err := NewReader(wavFile, int64(wavFile.Len())) is.Err(err) is.Equal(ErrBrokenChunkFmt, err) } // panic: runtime error: integer divide by zero // [signal 0x8 code=0x1 addr=0x439ae9 pc=0x439ae9] // // goroutine 1 [running]: // github.com/cryptix/wav.(*Reader).parseHeaders(0xc208032cd0, 0x0, 0x0) // /tmp/go-fuzz-build857960013/src/github.com/cryptix/wav/reader.go:200 +0xf29 // github.com/cryptix/wav.NewReader(0x7fbca32b6bd8, 0xc208037ef0, 0x2d, 0xc208032cd0, 0x0, 0x0) // /tmp/go-fuzz-build857960013/src/github.com/cryptix/wav/reader.go:64 +0x177 // github.com/cryptix/wav.Fuzz(0x7fbca3035000, 0x2d, 0x100000, 0x2) // /tmp/go-fuzz-build857960013/src/github.com/cryptix/wav/fuzz.go:12 +0x167 // github.com/dvyukov/go-fuzz/go-fuzz-dep.Main(0x570c60, 0x5d4200, 0x5f6, 0x5f6) // /home/cryptix/go/src/github.com/dvyukov/go-fuzz/go-fuzz-dep/main.go:64 +0x309 // main.main() // /tmp/go-fuzz-build857960013/src/go-fuzz-main/main.go:10 +0x4e // exit status 2 func TestReadFuzzed_panic2(t *testing.T) { t.Parallel() is := is.New(t) wavFile := strings.NewReader("RIFF%\x00\x00\x00WAVEfmt \x10\x00\x00\x00\x01\x00000000000000\a\x00data00000") _, err := NewReader(wavFile, int64(wavFile.Len())) is.Err(err) is.Equal(ErrBrokenChunkFmt, err) } wav-master/reader.go0000664000175000017500000002256613264634400013450 0ustar arunarunpackage wav import ( "encoding/binary" "fmt" "io" "os" "sort" "time" ) // Reader wraps WAV stream type Reader struct { input io.ReadSeeker size int64 header *riffHeader chunkFmt *riffChunkFmt canonical bool extraChunk bool firstSamplePos uint32 dataBlocSize uint32 bytesPerSample uint32 duration time.Duration samplesRead uint32 numSamples uint32 } func (wav Reader) String() string { msg := fmt.Sprintln("File informations") msg += fmt.Sprintln("=================") msg += fmt.Sprintf("File size : %d bytes\n", wav.size) msg += fmt.Sprintf("Canonical format : %v\n", wav.canonical && !wav.extraChunk) // chunk fmt msg += fmt.Sprintf("Audio format : %d\n", wav.chunkFmt.AudioFormat) msg += fmt.Sprintf("Number of channels: %d\n", wav.chunkFmt.NumChannels) msg += fmt.Sprintf("Sampling rate : %d Hz\n", wav.chunkFmt.SampleRate) msg += fmt.Sprintf("Sample size : %d bits\n", wav.chunkFmt.BitsPerSample) // calculated msg += fmt.Sprintf("Number of samples : %d\n", wav.numSamples) msg += fmt.Sprintf("Sound size : %d bytes\n", wav.dataBlocSize) msg += fmt.Sprintf("Sound duration : %v\n", wav.duration) return msg } // NewReader returns a new WAV reader wrapper func NewReader(rd io.ReadSeeker, size int64) (wav *Reader, err error) { if size > maxSize { return nil, ErrInputToLarge } wav = new(Reader) wav.input = rd wav.size = size err = wav.parseHeaders() if err != nil { return nil, err } wav.samplesRead = 0 return wav, nil } func (wav *Reader) parseHeaders() (err error) { wav.header = &riffHeader{} var ( chunk [4]byte chunkSize uint32 ) // decode header if err = binary.Read(wav.input, binary.LittleEndian, wav.header); err != nil { return err } if wav.header.Ftype != tokenRiff { return ErrNotRiff } if wav.header.ChunkSize+8 != uint32(wav.size) { return ErrIncorrectChunkSize{wav.header.ChunkSize + 8, uint32(wav.size)} } if wav.header.ChunkFormat != tokenWaveFormat { return ErrNotWave } readLoop: for { // Read next chunkID err = binary.Read(wav.input, binary.BigEndian, &chunk) if err == io.EOF { return io.ErrUnexpectedEOF } else if err != nil { return err } // and it's size in bytes err = binary.Read(wav.input, binary.LittleEndian, &chunkSize) if err == io.EOF { return io.ErrUnexpectedEOF } else if err != nil { return err } switch chunk { case tokenChunkFmt: // seek 4 bytes back because riffChunkFmt reads the chunkSize again if _, err = wav.input.Seek(-4, os.SEEK_CUR); err != nil { return err } wav.canonical = chunkSize == 16 // canonical format if chunklen == 16 if err = wav.parseChunkFmt(); err != nil { return err } case tokenData: size, _ := wav.input.Seek(0, os.SEEK_CUR) wav.firstSamplePos = uint32(size) wav.dataBlocSize = uint32(chunkSize) break readLoop default: //fmt.Fprintf(os.Stderr, "Skip unused chunk \"%s\" (%d bytes).\n", chunk, chunkSize) wav.extraChunk = true if _, err = wav.input.Seek(int64(chunkSize), os.SEEK_CUR); err != nil { return err } } } if wav.chunkFmt == nil { return ErrBrokenChunkFmt } wav.bytesPerSample = uint32(wav.chunkFmt.BitsPerSample / 8) if wav.bytesPerSample == 0 { return ErrNoBitsPerSample } wav.numSamples = wav.dataBlocSize / wav.bytesPerSample wav.duration = time.Duration(float64(wav.numSamples)/float64(wav.chunkFmt.SampleRate)) * time.Second return nil } // parseChunkFmt func (wav *Reader) parseChunkFmt() (err error) { wav.chunkFmt = new(riffChunkFmt) if err = binary.Read(wav.input, binary.LittleEndian, wav.chunkFmt); err != nil { return err } if wav.canonical == false { var extraparams uint32 // Get extra params size if err = binary.Read(wav.input, binary.LittleEndian, &extraparams); err != nil { return err } // Skip them if _, err = wav.input.Seek(int64(extraparams), os.SEEK_CUR); err != nil { return err } } // Is audio supported ? if wav.chunkFmt.AudioFormat != 1 { return ErrFormatNotSupported } return nil } // GetSampleCount returns the number of samples func (wav *Reader) GetSampleCount() uint32 { return wav.numSamples } // GetAudioFormat returns the audio format. A value of 1 indicates uncompressed PCM. // Any other value indicates a compressed format func (wav *Reader) GetAudioFormat() uint16 { return wav.chunkFmt.AudioFormat } // GetNumChannels returns the number of audio channels func (wav *Reader) GetNumChannels() uint16 { return wav.chunkFmt.NumChannels } // GetSampleRate returns the sample rate func (wav *Reader) GetSampleRate() uint32 { return wav.chunkFmt.SampleRate } // GetBitsPerSample returns the number of bits per sample func (wav *Reader) GetBitsPerSample() uint16 { return wav.chunkFmt.BitsPerSample } // GetBytesPerSec returns the number of bytes per second of audio. ie: byte rate func (wav *Reader) GetBytesPerSec() uint32 { return wav.chunkFmt.BytesPerSec } // GetDuration returns the length of audio func (wav *Reader) GetDuration() time.Duration { return wav.duration } // GetFile returns File func (wav Reader) GetFile() File { return File{ SampleRate: wav.chunkFmt.SampleRate, Channels: wav.chunkFmt.NumChannels, SignificantBits: wav.chunkFmt.BitsPerSample, BytesPerSecond: wav.chunkFmt.BytesPerSec, AudioFormat: wav.chunkFmt.AudioFormat, NumberOfSamples: wav.numSamples, SoundSize: wav.dataBlocSize, Duration: wav.duration, Canonical: wav.canonical && !wav.extraChunk, } } // FirstSampleOffset in the WAV stream func (wav Reader) FirstSampleOffset() uint32 { return wav.firstSamplePos } // Reset the wavReader func (wav *Reader) Reset() (err error) { _, err = wav.input.Seek(int64(wav.firstSamplePos), os.SEEK_SET) if err == nil { wav.samplesRead = 0 } return } // GetDumbReader gives you a std io.Reader, starting from the first sample. usefull for piping data. func (wav Reader) GetDumbReader() (r io.Reader, err error) { // move reader to the first sample _, err = wav.input.Seek(int64(wav.firstSamplePos), os.SEEK_SET) if err != nil { return nil, err } return wav.input, nil } // ReadRawSample returns the raw []byte slice func (wav *Reader) ReadRawSample() ([]byte, error) { if wav.samplesRead > wav.numSamples { return nil, io.EOF } buf := make([]byte, wav.bytesPerSample) n, err := wav.input.Read(buf) if err != nil { return nil, err } if n != int(wav.bytesPerSample) { return nil, fmt.Errorf("Read %d bytes, should have read %d", n, wav.bytesPerSample) } wav.samplesRead++ return buf, nil } // ReadSample returns the parsed sample bytes as integers func (wav *Reader) ReadSample() (n int32, err error) { s, err := wav.ReadRawSample() if err != nil { return 0, err } switch wav.bytesPerSample { case 1: n = int32(s[0]) case 2: n = int32(s[0]) + int32(s[1])<<8 case 3: n = int32(s[0]) + int32(s[1])<<8 + int32(s[2])<<16 case 4: n = int32(s[0]) + int32(s[1])<<8 + int32(s[2])<<16 + int32(s[3])<<24 default: n = 0 err = fmt.Errorf("Unhandled bytesPerSample! b:%d", wav.bytesPerSample) } return } // ReadSampleEvery returns the parsed sample bytes as integers every X samples func (wav *Reader) ReadSampleEvery(every uint32, average int) (samples []int32, err error) { // Reset any other readers err = wav.Reset() if err != nil { return } var n int32 var total int total = int(wav.numSamples / every) for total >= 0 { total = total - 1 n, err = wav.ReadSample() if err != nil { return } // lets average the samples for better accuracy // if average > 0 { // var sum = n // fmt.Println(n) // for i := 1; i < average; i++ { // n, err = wav.ReadSample() // if err != nil { // return // } // fmt.Println(n) // sum += n // } // fmt.Println("Sum:", sum, "/", int32(average), sum/int32(average)) // n = sum / int32(average) // } // Median seems to reflect better than average if average > 0 { var sum = make([]int, average) sum[0] = int(n) for i := 1; i < average; i++ { n, err = wav.ReadSample() if err != nil { return } sum[i] = int(n) } sort.Ints(sum) // fmt.Println("Sum:", sum, "[", average/2, "] = ", sum[average/2]) n = int32(sum[average/2]) } samples = append(samples, n) _, err = wav.input.Seek(int64(every), os.SEEK_CUR) if err != nil { return } } return } /* // Sample of WAV type Sample struct { Offset uint32 Value int32 Second uint32 } // ReadSampleChannelEvery X samples delivered over a channel func (wav *Reader) ReadSampleChannelEvery(every uint32) (c chan *Sample, e chan error) { // Save resources by making a channel to range over c = make(chan *Sample, 100) e = make(chan error) go func() { var err error // Reset any other readers wav.samplesRead = 0 // Start from the begining _, err = wav.input.Seek(int64(wav.firstSamplePos), os.SEEK_SET) if err != nil { close(c) e <- err return } var n int32 var total int var pos uint32 total = int(wav.numSamples / every) for total >= 0 { total = total - 1 pos += every // Read a sample n, err = wav.ReadSample() if err != nil { close(c) e <- err return } c <- &Sample{ Offset: pos, Second: pos / wav.chunkFmt.SampleRate, Value: n, } _, err = wav.input.Seek(int64(every), os.SEEK_CUR) if err != nil { close(c) e <- err return } } // Reset any other readers wav.samplesRead = 0 }() return } */ wav-master/errors.go0000664000175000017500000000141713264634400013512 0ustar arunarunpackage wav import ( "errors" "fmt" ) var ( // ErrInputToLarge error ErrInputToLarge = errors.New("Input too large") // ErrNotRiff error ErrNotRiff = errors.New("Not a RIFF file") // ErrNotWave error ErrNotWave = errors.New("Not a WAVE file") // ErrBrokenChunkFmt error ErrBrokenChunkFmt = errors.New("could not decode chunkFmt") // ErrNoBitsPerSample error ErrNoBitsPerSample = errors.New("could not decode chunkFmt") // ErrFormatNotSupported error ErrFormatNotSupported = errors.New("Format not supported - Only uncompressed PCM currently") ) // ErrIncorrectChunkSize struct type ErrIncorrectChunkSize struct { Got, Wanted uint32 } func (e ErrIncorrectChunkSize) Error() string { return fmt.Sprintf("Incorrect ChunkSize. Got[%d] Wanted[%d]", e.Got, e.Wanted) } wav-master/headers.go0000664000175000017500000000153313264634400013610 0ustar arunarunpackage wav import "time" const ( maxSize = 2 << 31 ) var ( tokenRiff = [4]byte{'R', 'I', 'F', 'F'} tokenWaveFormat = [4]byte{'W', 'A', 'V', 'E'} tokenChunkFmt = [4]byte{'f', 'm', 't', ' '} tokenData = [4]byte{'d', 'a', 't', 'a'} ) // File describes the WAV file type File struct { SampleRate uint32 SignificantBits uint16 Channels uint16 NumberOfSamples uint32 Duration time.Duration AudioFormat uint16 SoundSize uint32 Canonical bool BytesPerSecond uint32 } // 12 byte header type riffHeader struct { Ftype [4]byte ChunkSize uint32 ChunkFormat [4]byte } // 20 type riffChunkFmt struct { LengthOfHeader uint32 AudioFormat uint16 // 1 = PCM not compressed NumChannels uint16 SampleRate uint32 BytesPerSec uint32 BytesPerBloc uint16 BitsPerSample uint16 }