Java read WAV file (waveform file) and draw a waveform diagram method _java

Source: Internet
Author: User

This article describes the Java read WAV file (waveform file) and the method of drawing waveform diagram. Share to everyone for your reference. Specifically as follows:

Because a lot of netizens recently asked me about the waveform file reading and writing problems, in order to make everyone more convenient and let the code can get better improvements, I will this part (waveform file read and write) code open source in the GitHub above.

The address is https://github.com/sintrb/WaveAccess/, the newest code, the example, the document is above that, I will maintain the project under the premise which my time energy allows, also hoped that has the interest the netizen to be able to add to this open source project.

The following is basically expired, you can go directly to GitHub read, download the project.

Because the project needs to read the. wav file (waveform file) and draw a waveform diagram, so simply do this aspect of the package.

In fact, mainly for the WAV file read package, the following is a WAV file Reader encapsulation:

Filename:WaveFileReader.java//Robintang//2012-08-23 import java.io.*; 
  public class Wavefilereader {private String filename = null; 
  Private int[][] data = null; 
  private int len = 0; 
  Private String chunkdescriptor = null; 
  static private int lenchunkdescriptor = 4; 
  Private long chunksize = 0; 
  static private int lenchunksize = 4; 
  Private String waveflag = null; 
  static private int lenwaveflag = 4; 
  Private String fmtubchunk = null; 
  static private int lenfmtubchunk = 4; 
  Private long subchunk1size = 0; 
  static private int lensubchunk1size = 4; 
  private int audioformat = 0; 
  static private int lenaudioformat = 2; 
  private int numchannels = 0; 
  static private int lennumchannels = 2; 
  Private long samplerate = 0; 
  static private int lensamplerate = 2; 
  Private long byterate = 0; 
  static private int lenbyterate = 4; 
  private int blockalign = 0; 
  static private int lenblockling = 2; 
  private int bitspersample = 0; Static Private int lenbitspersample = 2; 
  Private String datasubchunk = null; 
  static private int lendatasubchunk = 4; 
  Private long subchunk2size = 0; 
  static private int lensubchunk2size = 4; 
  Private FileInputStream FIS = null; 
  private Bufferedinputstream bis = null; 
  Private Boolean issuccess = false; 
  Public Wavefilereader (String filename) {this.initreader (filename); 
  //Decide whether to create a WAV reader Success public Boolean issuccess () {return issuccess; 
  //Get the encoded length of each sample, 8bit or 16bit public int getbitpersample () {return this.bitspersample; 
  //Get the sample rate public long getsamplerate () {return this.samplerate; 
  //Get the number of channels, 1 stands for mono 2 for stereo public int getnumchannels () {return this.numchannels; 
  //Get the data length, that is, how many public int Getdatalen () {return this.len are sampled altogether; 
  //Get Data//data is a two-dimensional array, [n][m] represents the nth channel's m sampling value public int[][] GetData () {return this.data; } private void Initreader (String filename) {this.filename = fiLename; 
      try {fis = new FileInputStream (this.filename); 
      bis = new Bufferedinputstream (FIS); 
      This.chunkdescriptor = readString (lenchunkdescriptor); if (!chunkdescriptor.endswith ("RIFF")) throw new IllegalArgumentException ("RIFF miss," + filename + "is not a WA 
      ve file. "); 
      This.chunksize = Readlong (); 
      This.waveflag = readString (Lenwaveflag); if (!waveflag.endswith ("wave")) throw new IllegalArgumentException ("Wave miss," + filename + "is not a WAVE file 
      ."); 
      This.fmtubchunk = readString (Lenfmtubchunk); if (!fmtubchunk.endswith ("FMT")) throw new IllegalArgumentException ("Fmt miss," + filename + "is not a wave fil 
      E. "); 
      This.subchunk1size = Readlong (); 
      This.audioformat = ReadInt (); 
      This.numchannels = ReadInt (); 
      This.samplerate = Readlong (); 
      This.byterate = Readlong (); 
      This.blockalign = ReadInt (); 
      This.bitspersample = ReadInt (); This.datasubcHunk = readString (lendatasubchunk); if (!datasubchunk.endswith ("data")) throw new IllegalArgumentException ("Data miss," + filename + "is not a wave 
      file. "); 
      This.subchunk2size = Readlong (); 
      This.len = (int) (this.subchunk2size/(THIS.BITSPERSAMPLE/8)/this.numchannels); 
       
      This.data = new Int[this.numchannels][this.len]; for (int i=0; i<this.len; ++i) {for (int n=0; n<this.numchannels; ++n) {if (This.bitspersample = 8 
          ) {This.data[n][i] = Bis.read (); 
          else if (This.bitspersample =) {This.data[n][i] = This.readint (); 
    }} issuccess = true; 
    catch (Exception e) {e.printstacktrace (); 
      } finally{try{if (bis!= null) bis.close (); 
      if (FIS!= null) fis.close (); 
      catch (Exception E1) {e1.printstacktrace (); }} private String readString (int len) {byte[] buf = new Byte[len]; 
    try {if (Bis.read (BUF)!=len) throw new IOException ("No more data!!!"); 
    catch (IOException e) {e.printstacktrace (); 
  Return to New String (BUF); 
    private int readInt () {byte[] buf = new byte[2]; 
    int res = 0; 
      try {if (Bis.read (BUF)!=2) throw new IOException ("No more data!!!"); res = (BUF[0]&AMP;0X000000FF) | 
    (((int) buf[1]) <<8); 
    catch (IOException e) {e.printstacktrace (); 
  return res; 
    Private Long Readlong () {Long res = 0; 
      try {long[] L = new long[4]; 
        for (int i=0; i<4; ++i) {L[i] = Bis.read (); 
        if (l[i]==-1) {throw new IOException ("No more data!!!"); } res = l[0] | (l[1]<<8) | (l[2]<<16) | 
    (l[3]<<24); 
    catch (IOException e) {e.printstacktrace (); 
  return res; Private byte[] Readbytes (int len) { 
    byte[] buf = new Byte[len]; 
    try {if (Bis.read (BUF)!=len) throw new IOException ("No more data!!!"); 
    catch (IOException e) {e.printstacktrace (); 
  return buf; 

 } 
}

To draw the waveform, so a wave drawing panel from the JPanel tutorial is made:

Filename:DrawPanel.java//Robintang//2012-08-23 import Java.awt.Color; 
Import Java.awt.Graphics; 
Import Javax.swing.JPanel; 
  @SuppressWarnings ("Serial") public class Drawpanel extends JPanel {private int[] data = null; 
  Public Drawpanel (int[] data) {this.data = data; 
    @Override protected void Paintcomponent (Graphics g) {int ww = getwidth (); 
    int hh = getheight (); 
    G.setcolor (Color.White); 
    G.fillrect (0, 0, WW, hh); 
    int len = data.length; 
    int step = LEN/WW; 
    if (step==0) step = 1; int Prex = 0, prey = 0; 
    last coordinate int x = 0, y = 0; 
    G.setcolor (color.red); 
    Double k = hh/2.0/32768.0; 
      for (int i=0; i<ww; ++i) {x = i; 
      Here is a three-point fetch and draw//In fact, the interval y = hh-(int) (DATA[I*3]*K+HH/2) should be set according to the sampling rate; 
      System.out.print (y); 
      System.out.print (""); 
      if (i!=0) {g.drawline (x, y, Prex, Prey); 
      } Prex = x; 
    Prey = y; 

 } 
  } 
}

With these you can invoke the drawn, simple:

Wavefilereaddemo.java 
//Robintang 
//2012-08-23 
import javax.swing.JFrame; 
public class Wavefilereaddemo { 
  /** 
   * @param args */public 
  static void Main (string[] args) { 
    //TODO auto-generated method Stub 
    String filename = "file.wav"; 
    JFrame frame = new JFrame (); 
    Wavefilereader reader = new Wavefilereader (filename); 
    if (reader.issuccess ()) { 
      int[] data = Reader.getdata () [0];//Get First channel 
      drawpanel drawpanel = new Drawpanel (data) ; Create a panel to draw the waveform 
      Frame.add (drawpanel); 
      Frame.settitle (filename); 
      Frame.setsize (a); 
      Frame.setlocationrelativeto (null); 
      Frame.setdefaultcloseoperation (jframe.exit_on_close); 
      Frame.setvisible (true); 
    else{ 
      System.err.println (filename + "is not a normal WAV file");}} 
 

Project source code can be found on my Baidu network, directly to open source Java

Put a picture of the effect:

I hope this article will help you with your Java programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.