声网 java app视频录制_java 声音的播放与录制

该博客介绍了如何使用Java进行声音的录制和播放。通过创建AudioFormat对象,获取TargetDataLine进行录音,然后利用SourceDataLine实现播放。示例代码详细展示了整个过程,包括文件的保存和读取。
摘要由CSDN通过智能技术生成

简单总结了下, 就是format, info, line, 把这三个对象获得就可以了.

package com.file;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.IOException;

import javax.management.BadAttributeValueExpException;

import javax.sound.sampled.AudioFileFormat;

import javax.sound.sampled.AudioFormat;

import javax.sound.sampled.AudioInputStream;

import javax.sound.sampled.AudioSystem;

import javax.sound.sampled.DataLine;

import javax.sound.sampled.LineUnavailableException;

import javax.sound.sampled.SourceDataLine;

import javax.sound.sampled.TargetDataLine;

import javax.sound.sampled.DataLine.Info;

/**

* 测试声音的播放和录制

*/

public class MyAudio

{

public static void main ( String args [] )

{

a1 ();

}

public static void a1 ()

{

// 5秒后要录音停止

Thread t = new StopThread ();

t.start ();

try

{

// format

AudioFormat format = new AudioFormat ( 8000f, 8, 2, true, false );

// info, 使用一次就不用了.

DataLine.Info info = new Info ( TargetDataLine.class, format );

// line

TargetDataLine line = (TargetDataLine) AudioSystem.getLine ( info );

line.open ();

line.start ();

// 长度为 format * line 个位

byte [] buf = new byte [ format.getFrameSize () * line.getBufferSize () / 8 ];

int readBytes = 0;

ByteArrayOutputStream out = new ByteArrayOutputStream ();

while ( recording )

{

readBytes = line.read ( buf, 0, buf.length );

out.write ( buf );

}

line.stop ();

line.close ();

ByteArrayInputStream bais = new ByteArrayInputStream ( out.toByteArray () );

// 三参 = 一参长度 / 二参帧大小

AudioInputStream audioIs = new AudioInputStream ( bais, format

, out.toByteArray ().length / format.getFrameSize () );

AudioSystem.write ( audioIs, AudioFileFormat.Type.WAVE, new File ( "F:/mywav2.wav" ));

// 放音

// format 前面有

// info

DataLine.Info info2 = new Info ( SourceDataLine.class, format );

// line

SourceDataLine line2 = (SourceDataLine ) AudioSystem.getLine ( info2 );

line2.open ();

line2.start ();

readBytes = 0;

audioIs.reset (); // 因为在上面用过一次了, 所以要reset

while ( readBytes != -1 )

{

readBytes = audioIs.read ( buf, 0, buf.length );

line2.write ( buf, 0, readBytes );

}

line2.stop ();

line2.close ();

} catch ( Exception e )

{

e.printStackTrace();

}

}

public static boolean recording = true;

}

class StopThread extends Thread

{

@Override

public void run ()

{

try

{

Thread.sleep ( 5000 );

MyAudio.recording = false;

} catch ( Exception e )

{

// TODO: handle exception

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值