java显示声音波形图示例

 更新时间:2014年05月01日 08:27:47   作者:  
这篇文章主要介绍了java显示声音波形图示例,需要的朋友可以参考下

复制代码 代码如下:

package _tmp;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Timer;
import java.util.TimerTask;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.SourceDataLine;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class SoundTest {

 public static class WaveformGraph extends JFrame {

  private Deque<Short> deque = new LinkedList<Short>();
  private Timer timer;
  private Image buffered;
  private Image showing;

  public WaveformGraph(int width, int height) {
   setSize(width, height);
   timer = new Timer();
   buffered = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
   timer.schedule(new TimerTask() {
    @Override public void run() {

     Graphics g = buffered.getGraphics();
     g.setColor(Color.WHITE);
     g.fillRect(0, 0, getWidth(), getHeight());
     g.setColor(Color.BLACK);

     g.translate(10, getHeight()/2);

     synchronized (deque) {
      float heightRate = 1;
      if(deque.size() > 1) {
       Iterator<Short> iter = deque.iterator();
       Short p1 = iter.next();
       Short p2 = iter.next();
       int x1 = 0, x2 = 0;
       while(iter.hasNext()) {
        g.drawLine(x1, (int)(p1*heightRate), x2, (int)(p2*heightRate));

        p1 = p2;
        p2 = iter.next();
        x1 = x2;
        x2 += 1;
       }
      }
     }
     g.dispose();

     SwingUtilities.invokeLater(new Runnable() {
      @Override public void run() {
       showing = buffered;
       repaint();
       showing = null;
      }
     });
    }
   }, 100, 100);
  }

  @Override
  public void paint(Graphics g) {
   super.paint(g);
   if(buffered!=null) {
    g.drawImage(buffered, 0, 0, null);
   }
  }

  public void put(short v) {
   synchronized (deque) {
    deque.add(v);
    if(deque.size() > 500) {
     deque.removeFirst();
    }
   }
  }

  public void clear() {
   deque.clear();
  }
 }

 public static void main(String[] args) throws Exception {
//  record();
  WaveformGraph waveformGraph = new WaveformGraph(500, 300);
  waveformGraph.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  waveformGraph.setVisible(true);

  AudioInputStream ais = AudioSystem.getAudioInputStream(new File("C:\\Documents and Settings\\wml\\My Documents\\My Music\\苏仨 - 失眠症.wav"));
  printFormat(ais.getFormat());
  

  SourceDataLine player = AudioSystem.getSourceDataLine(ais.getFormat());

  player.open();
  player.start();

  byte[] buf = new byte[4];
  int len;
  while((len=ais.read(buf))!=-1) {

   if(ais.getFormat().getChannels() == 2) {
    if(ais.getFormat().getSampleRate() == 16) {
     waveformGraph.put((short) ((buf[1] << 8) | buf[0]));//左声道

//     waveformGraph.put((short) ((buf[3] << 8) | buf[2]));//右声道
    } else {
     waveformGraph.put(buf[1]);//左声道
     waveformGraph.put(buf[3]);//左声道

//     waveformGraph.put(buf[2]);//右声道
//     waveformGraph.put(buf[4]);//右声道
    }
   } else {
    if(ais.getFormat().getSampleRate() == 16) {
     waveformGraph.put((short) ((buf[1] << 8) | buf[0]));
     waveformGraph.put((short) ((buf[3] << 8) | buf[2]));
    } else {
     waveformGraph.put(buf[1]);
     waveformGraph.put(buf[2]);
     waveformGraph.put(buf[3]);
     waveformGraph.put(buf[4]);
    }
   }

   player.write(buf, 0, len);
  }

  player.close();
  ais.close();
 }

 public static void printFormat(AudioFormat format) {
  System.out.println(format.getEncoding() + " => "
    + format.getSampleRate()+" hz, "
    + format.getSampleSizeInBits() + " bit, "
    + format.getChannels() + " channel, "
    + format.getFrameRate() + " frames/second, "
    + format.getFrameSize() + " bytes/frame");
 }

// public static void record() throws LineUnavailableException,
//   InterruptedException {
//  AudioFormat audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 48000F, 16, 1, 2, 48000F, false);
//  Info recordDevInfo = new DataLine.Info(TargetDataLine.class, audioFormat);
//
//  final TargetDataLine recordLine = (TargetDataLine) AudioSystem.getLine(recordDevInfo);
//  final SourceDataLine playLine = AudioSystem.getSourceDataLine(audioFormat);
//  
//  recordLine.open(audioFormat, recordLine.getBufferSize());
//  playLine.open(audioFormat, recordLine.getBufferSize());
//  
//  Thread recorder = new Thread() {
//   public void run() {
//    recordLine.start();
//    playLine.start();
//    
//    FloatControl fc = (FloatControl) playLine.getControl(FloatControl.Type.MASTER_GAIN);
//    double value = 2;
//    float dB = (float) (Math.log(value == 0.0 ? 0.0001 : value) / Math.log(10.0) * 20.0);
//    fc.setValue(dB);
//    
//    try {
//     AudioInputStream in = new AudioInputStream(recordLine);
//     byte[] buf = new byte[recordLine.getBufferSize()];
//     int len;
//     while((len=in.read(buf)) != -1) {
//      playLine.write(buf, 0, len);
//     }
//    } catch (IOException e) {
//     e.printStackTrace();
//    } finally {
//     recordLine.stop();
//     playLine.stop();
//    }
//   };
//  };
//  recorder.start();
//  recorder.join();
// }
}

相关文章

  • SpringBootAdmin+actuator实现服务监控

    SpringBootAdmin+actuator实现服务监控

    这篇文章主要为大家详细介绍了SpringBootAdmin+actuator实现服务监控,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-01-01
  • java判断请求是来自PC端还是手机端小技巧

    java判断请求是来自PC端还是手机端小技巧

    这篇文章主要为大家介绍了java判断请求是来自PC端还是手机端小技巧,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-06-06
  • Java全面细致讲解类与对象

    Java全面细致讲解类与对象

    类和对象是两种以计算机为载体的计算机语言的合称。对象是对客观事物的抽象,类是对对象的抽象。类是一种抽象的数据类型;变量就是可以变化的量,存储在内存中—个可以拥有在某个范围内的可变存储区域
    2022-05-05
  • Java基于高精度整型实现fibonacci数列的方法

    Java基于高精度整型实现fibonacci数列的方法

    这篇文章主要介绍了Java基于高精度整型实现fibonacci数列的方法,是比较典型的算法,需要的朋友可以参考下
    2014-09-09
  • java多线程之线程,进程和Synchronized概念初解

    java多线程之线程,进程和Synchronized概念初解

    这篇文章主要介绍了java多线程之线程,进程和Synchronized概念初解,涉及进程与线程的简单概念,实现多线程的方式,线程安全问题,synchronized修饰符等相关内容,具有一定借鉴价值,需要的朋友可以参考下。
    2017-11-11
  • mybatis+lombok出现java.lang.IndexOutOfBoundsException错误及解决

    mybatis+lombok出现java.lang.IndexOutOfBoundsException错误及解决

    在使用MyBatis和Lombok时,如果遇到java.lang.IndexOutOfBoundsException问题,是因为MyBatis在尝试将查询结果封装成Java对象时,找不到构造函数中对应的字段,这通常是由于Lombok的@Builder注解生成了全参构造函数
    2025-02-02
  • Spring Boot热加载jar实现动态插件的思路

    Spring Boot热加载jar实现动态插件的思路

    本文主要介绍在 Spring Boot 工程中热加载 jar 包并注册成为 Bean 对象的一种实现思路,在动态扩展功能的同时支持在插件中注入主程序的 Bean 实现功能更强大的插件
    2021-10-10
  • 5分钟快速了解String.trim()到底做了什么事

    5分钟快速了解String.trim()到底做了什么事

    trim方法一般用来去除空格,但是根据JDK API的说明,该方法并不仅仅是去除空格,它能够去除从编码'\u0000'至'\u0020'的所有字符,这篇文章主要给大家介绍了如何通过5分钟快速了解String.trim()到底做了什么事,需要的朋友可以参考下
    2021-11-11
  • 深入学习SpringCloud之SpringCloud简介

    深入学习SpringCloud之SpringCloud简介

    Spring Cloud是一个一站式的开发分布式系统的框架,为开发者提供了一系列的构建分布式系统的工具集,本文给大家介绍springcloud的相关知识,感兴趣的朋友跟随一起看看吧
    2021-04-04
  • java基础学习笔记之反射

    java基础学习笔记之反射

    什么是反射?Java 程序在运行期间可以动态加载、解析和使用一些在编译阶段并不确定的类型数据,这一机制被称为反射(Reflection)。今天我们就来详细探讨下java中的反射
    2016-02-02

最新评论