「java播放录音」java 录音

博主:adminadmin 2022-12-24 23:09:05 64

今天给各位分享java播放录音的知识,其中也会对java 录音进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

如何在java应用程序中播放音频文件

在 applet 中播放声音文件非常简单,一般需要以下步骤:创建一个 AudioClip 对象

装入 .au 声音文件到 AudioClip 对象

一次播放或者不停循环播放声音

停止播放

下面是相应的代码:import java.applet.*;AudioClip ac = getAudioClip(getCodeBase(), soundFile);

ac.play(); //play once

ac.stop(); //stop playing

解决这个问题的窍门是利用由 Sun 及 其JDK 提供的某些 undocumented 的特征。先看看 Sun JDK 中的文件 classes.zip (使用任何解压工具即可),发现其中不仅包含标准的 Java 包如 java.applet 而且还存在包 sun.audio. (在 sun/audio 的目录下.)

包 sun.audio 中包含了用于播放声音文件所需的所有东西!下面是示例代码:import sun.audio.*; //import the sun.audio package

import java.io.*;//** add this into your application code as appropriate// Open an input stream to the audio file.

InputStream in = new FileInputStream(Filename);// Create an AudioStream object from the input stream.

AudioStream as = new AudioStream(in);// Use the static class member "player" from class AudioPlayer to play

// clip.

AudioPlayer.player.start(as);// Similarly, to stop the audio.

AudioPlayer.player.stop(as);如果要用一个 URL 做为声音流的源(source),则用下面的代码所示替换输入流来创建声音流:AudioStream as = new AudioStream (url.openStream());如果需要持续播放声音文件,则要稍稍复杂一点:// Create audio stream as discussed previously.

// Create AudioData source.

AudioData data = as.getData();// Create ContinuousAudioDataStream.

ContinuousAudioDataStream cas = new ContinuousAudioDataStream (data);// Play audio.

java可以做语音录音吗

可以。

需求:

1.实现可以从麦克风进行录音

2.可以停止录音

3.实现播放录音内容

4.并将所录的mp3文件全部存到F:/语音文件夹,语音的文件名以当前时间命名(java中是换算成秒),其中文件夹程序自己创建,不用担心出错

程序如下:

span style="font-size:18px;"import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

import java.io.*;

import javax.sound.sampled.*;

public class MyRecord extends JFrame implements ActionListener{

//定义录音格式

AudioFormat af = null;

//定义目标数据行,可以从中读取音频数据,该 TargetDataLine 接口提供从目标数据行的缓冲区读取所捕获数据的方法。

TargetDataLine td = null;

//定义源数据行,源数据行是可以写入数据的数据行。它充当其混频器的源。应用程序将音频字节写入源数据行,这样可处理字节缓冲并将它们传递给混频器。

SourceDataLine sd = null;

//定义字节数组输入输出流

ByteArrayInputStream bais = null;

ByteArrayOutputStream baos = null;

//定义音频输入流

AudioInputStream ais = null;

//定义停止录音的标志,来控制录音线程的运行

Boolean stopflag = false;

//定义所需要的组件

JPanel jp1,jp2,jp3;

JLabel jl1=null;

JButton captureBtn,stopBtn,playBtn,saveBtn;

public static void main(String[] args) {

//创造一个实例

MyRecord mr = new MyRecord();

}

//构造函数

public MyRecord()

{

//组件初始化

jp1 = new JPanel();

jp2 = new JPanel();

jp3 = new JPanel();

//定义字体

Font myFont = new Font("华文新魏",Font.BOLD,30);

jl1 = new JLabel("录音机功能的实现");

jl1.setFont(myFont);

jp1.add(jl1);

captureBtn = new JButton("开始录音");

//对开始录音按钮进行注册监听

captureBtn.addActionListener(this);

captureBtn.setActionCommand("captureBtn");

//对停止录音进行注册监听

stopBtn = new JButton("停止录音");

stopBtn.addActionListener(this);

stopBtn.setActionCommand("stopBtn");

//对播放录音进行注册监听

playBtn = new JButton("播放录音");

playBtn.addActionListener(this);

playBtn.setActionCommand("playBtn");

//对保存录音进行注册监听

saveBtn = new JButton("保存录音");

saveBtn.addActionListener(this);

saveBtn.setActionCommand("saveBtn");

this.add(jp1,BorderLayout.NORTH);

this.add(jp2,BorderLayout.CENTER);

this.add(jp3,BorderLayout.SOUTH);

jp3.setLayout(null);

jp3.setLayout(new GridLayout(1, 4,10,10));

jp3.add(captureBtn);

jp3.add(stopBtn);

jp3.add(playBtn);

jp3.add(saveBtn);

//设置按钮的属性

captureBtn.setEnabled(true);

stopBtn.setEnabled(false);

playBtn.setEnabled(false);

saveBtn.setEnabled(false);

//设置窗口的属性

this.setSize(400,300);

this.setTitle("录音机");

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.setLocationRelativeTo(null);

this.setVisible(true);

}

public void actionPerformed(ActionEvent e) {

if(e.getActionCommand().equals("captureBtn"))

{

//点击开始录音按钮后的动作

//停止按钮可以启动

captureBtn.setEnabled(false);

stopBtn.setEnabled(true);

playBtn.setEnabled(false);

saveBtn.setEnabled(false);

//调用录音的方法

capture();

}else if (e.getActionCommand().equals("stopBtn")) {

//点击停止录音按钮的动作

captureBtn.setEnabled(true);

stopBtn.setEnabled(false);

playBtn.setEnabled(true);

saveBtn.setEnabled(true);

//调用停止录音的方法

stop();

}else if(e.getActionCommand().equals("playBtn"))

{

//调用播放录音的方法

play();

}else if(e.getActionCommand().equals("saveBtn"))

{

//调用保存录音的方法

save();

}

}

//开始录音

public void capture()

{

try {

//af为AudioFormat也就是音频格式

af = getAudioFormat();

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

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

//打开具有指定格式的行,这样可使行获得所有所需的系统资源并变得可操作。

td.open(af);

//允许某一数据行执行数据 I/O

td.start();

//创建播放录音的线程

Record record = new Record();

Thread t1 = new Thread(record);

t1.start();

} catch (LineUnavailableException ex) {

ex.printStackTrace();

return;

}

}

//停止录音

public void stop()

{

stopflag = true;

}

//播放录音

public void play()

{

//将baos中的数据转换为字节数据

byte audioData[] = baos.toByteArray();

//转换为输入流

bais = new ByteArrayInputStream(audioData);

af = getAudioFormat();

ais = new AudioInputStream(bais, af, audioData.length/af.getFrameSize());

try {

DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, af);

sd = (SourceDataLine) AudioSystem.getLine(dataLineInfo);

sd.open(af);

sd.start();

//创建播放进程

Play py = new Play();

Thread t2 = new Thread(py);

t2.start();

} catch (Exception e) {

e.printStackTrace();

}finally{

try {

//关闭流

if(ais != null)

{

ais.close();

}

if(bais != null)

{

bais.close();

}

if(baos != null)

{

baos.close();

}

} catch (Exception e) {

e.printStackTrace();

}

}

}

//保存录音

public void save()

{

//取得录音输入流

af = getAudioFormat();

byte audioData[] = baos.toByteArray();

bais = new ByteArrayInputStream(audioData);

ais = new AudioInputStream(bais,af, audioData.length / af.getFrameSize());

//定义最终保存的文件名

File file = null;

//写入文件

try {

//以当前的时间命名录音的名字

//将录音的文件存放到F盘下语音文件夹下

File filePath = new File("F:/语音文件");

if(!filePath.exists())

{//如果文件不存在,则创建该目录

filePath.mkdir();

}

file = new File(filePath.getPath()+"/"+System.currentTimeMillis()+".mp3");

AudioSystem.write(ais, AudioFileFormat.Type.WAVE, file);

} catch (Exception e) {

e.printStackTrace();

}finally{

//关闭流

try {

if(bais != null)

{

bais.close();

}

if(ais != null)

{

ais.close();

}

} catch (Exception e) {

e.printStackTrace();

}

}

}

//设置AudioFormat的参数

public AudioFormat getAudioFormat()

{

//下面注释部分是另外一种音频格式,两者都可以

AudioFormat.Encoding encoding = AudioFormat.Encoding.

PCM_SIGNED ;

float rate = 8000f;

int sampleSize = 16;

String signedString = "signed";

boolean bigEndian = true;

int channels = 1;

return new AudioFormat(encoding, rate, sampleSize, channels,

(sampleSize / 8) * channels, rate, bigEndian);

// //采样率是每秒播放和录制的样本数

// float sampleRate = 16000.0F;

// // 采样率8000,11025,16000,22050,44100

// //sampleSizeInBits表示每个具有此格式的声音样本中的位数

// int sampleSizeInBits = 16;

// // 8,16

// int channels = 1;

// // 单声道为1,立体声为2

// boolean signed = true;

// // true,false

// boolean bigEndian = true;

// // true,false

// return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed,bigEndian);

}

//录音类,因为要用到MyRecord类中的变量,所以将其做成内部类

class Record implements Runnable

{

//定义存放录音的字节数组,作为缓冲区

byte bts[] = new byte[10000];

//将字节数组包装到流里,最终存入到baos中

//重写run函数

public void run() {

baos = new ByteArrayOutputStream();

try {

System.out.println("ok3");

stopflag = false;

while(stopflag != true)

{

//当停止录音没按下时,该线程一直执行

//从数据行的输入缓冲区读取音频数据。

//要读取bts.length长度的字节,cnt 是实际读取的字节数

int cnt = td.read(bts, 0, bts.length);

if(cnt 0)

{

baos.write(bts, 0, cnt);

}

}

} catch (Exception e) {

e.printStackTrace();

}finally{

try {

//关闭打开的字节数组流

if(baos != null)

{

baos.close();

}

} catch (IOException e) {

e.printStackTrace();

}finally{

td.drain();

td.close();

}

}

}

}

//播放类,同样也做成内部类

class Play implements Runnable

{

//播放baos中的数据即可

public void run() {

byte bts[] = new byte[10000];

try {

int cnt;

//读取数据到缓存数据

while ((cnt = ais.read(bts, 0, bts.length)) != -1)

{

if (cnt 0)

{

//写入缓存数据

//将音频数据写入到混频器

sd.write(bts, 0, cnt);

}

}

} catch (Exception e) {

e.printStackTrace();

}finally{

sd.drain();

sd.close();

}

}

}

}/span

java如何播放声音

对声音媒体的直接支持可以说是Java的一大特色,尤其是在动画中配上声音效果,就可以使人在视觉上和听觉上均得到美的享受,那才叫过瘾。Java中播放声音文件与显示图像文件一样方便,同样只需要先将声音文件装载进来,然后播放就行了。

Java目前支持的声音文件只有一种格式,那就是SUN公司的AU格式(.AU文件),也称为u-law格式。由于AU格式的声音仅有8KHz的采样频率且不支持立体声效果,所以音质不算太好。唯一的好处就是AU声音文件的尺寸比其它格式小,有利于网上传输。一般,我们较熟悉的大都是WAV格式的声音文件,因此必须先将它们转换为AU格式(可以选用Goldwave软件来进行这种格式转换)。

声音文件准备好以后,就可以考虑将它装载进来并播放。在Applet类中提供的play( )方法可以将声音文件的装载与播放一并完成,其调用格式如下:

void play(URL url)

void play(URL url, String name)

可见,play( )方法的调用格式与getImage( )方法是完全一样的,也采用URL来定位声音文件。例如,某声音文件audio.au与applet文件存放在同一目录下,可以这样写:

play(getCodeBase( ),"audio.au");

一旦play( )方法装载了该声音文件,就立即播放。如果找不到指定URL下的声音文件,play( )方法不返回出错信息,只是听不到想听的声音而已。

由于play( )方法只能将声音播放一遍,若想循环播放某声音作为背景音乐,就需要用到功能更强大的AudioClip类,它能更有效地管理声音的播放操作。因为它被定义在java.applet程序包中,所以使用该类的话,不要忘了在程序头部加上:

import java.applet.AudioClip;

为了得到AudioClip对象,我们可以调用Applet类中的getAudioClip( )方法。它能装载指定URL的声音文件,并返回一个AudioClip对象,其调用格式如下:

AudioClip getAudioClip(URL url)

AudioClip getAudioClip(URL url, String name)

得到AudioClip对象以后,就可以调用AudioClip类中所提供的各种方法来操作其中的声音数据,这些方法如表4-4所示。

如果getAudioClip( )方法没有找到所指定的声音文件,就会返回null值。所以,在调用表4-4中所列的方法前,应该先检查一下得到的AudioClip对象不是null,因为在null对象上调用上述方法将导致出错。

如果需要的话,我们还可以在applet中同时装载几个声音文件来一起播放,到时候,这些声音将混合在一起,就象二重奏一样。另外还有一点要说明的是,如果我们使用AudioClip对象的loop( )方法来重复播放背景音乐时,千万不要忘记在适当的时候调用AudioClip对象的stop( )方法来结束放音,否则的话,即使用户离开这一Web页面,该声音也不会停止,这无疑将会惹恼用户。因此,一般我们都在applet的stop( )方法中添上停止播放的代码。

例如,下面这段程序将播放两段声音,一段是连续播放的背景音乐,另一段是讲话录音。

import java.applet.AudioClip;

public class Audios extends java.applet.Applet{

AudioClip bgmusic,speak;

public void init(){

bgmusic=getAudioClip(getDocumentBase(),"space.au");

speak=getAudioClip(getDocumentBase(),"intro.au");

}

public void start(){

if(bgmusic!=null)

bgmusic.loop();

if(speak!=null)

speak.play();

}

public void stop(){

if(bgmusic!=null)

bgmusic.stop(); //关闭背景音乐,切记。

}

}

package com.hongyuan.test;

import java.io.File;

import java.io.IOException;

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.UnsupportedAudioFileException;

public class MusicTest {

public static final String MUSIC_FILE = "相逢一笑.wav";

public static void main(String[] args) throws

LineUnavailableException,

UnsupportedAudioFileException, IOException {

// 获取音频输入流

AudioInputStream audioInputStream =

AudioSystem

.getAudioInputStream(new File(MUSIC_FILE));

//

获取音频编码对象

AudioFormat audioFormat = audioInputStream.getFormat();

// 设置数据输入

DataLine.Info dataLineInfo = new

DataLine.Info(SourceDataLine.class,

audioFormat,

AudioSystem.NOT_SPECIFIED);

SourceDataLine sourceDataLine =

(SourceDataLine)

AudioSystem

.getLine(dataLineInfo);

sourceDataLine.open(audioFormat);

sourceDataLine.start();

/*

* 从输入流中读取数据发送到混音器

*/

int count;

byte tempBuffer[]

= new byte[1024];

while ((count = audioInputStream.read(tempBuffer, 0,

tempBuffer.length)) != -1) {

if (count 0)

{

sourceDataLine.write(tempBuffer, 0, count);

}

}

//

清空数据缓冲,并关闭输入

sourceDataLine.drain();

sourceDataLine.close();

}

}

JAVA 实现音频播放

这个程序只要写对了音乐文件的URL地址,例如:new URL("file:/C:/tmp/1/Windows Ding.wav");

就可以播放音乐,除了可以播放.wav格式的音乐,还可以播放.au格式的音乐。

另外,如果你不希望音乐循环播放,你可以去掉audio1.loop();这一语句。

import java.applet.AudioClip;

import java.net.MalformedURLException;

import java.net.URL;

import javax.swing.JFrame;

public class D extends JFrame{

D(){

setSize(200,200);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setVisible(true);

URL codebase=null;

try {

codebase = new URL("file:/C:/tmp/1/Windows Ding.wav");

} catch (MalformedURLException e) {

e.printStackTrace();

}

AudioClip audio1=Applet.newAudioClip(codebase);

audio1.loop();

}

public static void main(String[] args) {

new D();

}

}

java播放录音的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java 录音、java播放录音的信息别忘了在本站进行查找喔。

The End

发布于:2022-12-24,除非注明,否则均为首码项目网原创文章,转载请注明出处。