原创 java audio例程分析记录

2014-3-28 18:28 971 13 13 分类: 软件与OS

JavaSound示例程序CapturePlayback.java理解。

 

import java.io.*;

import javax.sound.sampled.*;

 

Java播放音频:

SourceDataLine line;

AudioFormat format = formatControls.getFormat();

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

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

line.open(format, bufSize);

line.start();

line.write(pData, 0, numBytesRemaining);

 

line.drain();

line.stop();

line.close();

 

Java录音:

TargetDataLine line;

AudioFormat format = formatControls.getFormat();

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

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

line.open(format, line.getBufferSize());

line.start();

numBytesRead = line.read(data, 0, bufferLengthInBytes));

 

line.stop();

line.close();

 

音频格式转换:

AudioFormat format = formatControls.getFormat();

AudioInputStream playbackInputStream = AudioSystem.getAudioInputStream(format, audioInputStream);

 

字节数组生成OutputStream:

ByteArrayOutputStream out = new ByteArrayOutputStream();

byte[] data = new byte[bufferLengthInBytes];

out.write(data, 0, numBytesRead);

 

字节数组生成InputStream:

byte audioBytes[] = out.toByteArray();

ByteArrayInputStream bais = new ByteArrayInputStream(audioBytes);

audioInputStream = new AudioInputStream(bais, format, audioBytes.length / frameSizeInBytes);

 

文件生成AudioInputStream:

audioInputStream = AudioSystem.getAudioInputStream(file);

 

AudioInputStream保存到文件:

        File file = new File(fileName = name);

        try {

            if (AudioSystem.write(audioInputStream, fileType, file) == -1) {

                throw new IOException("Problems writing to file");

            }

        } catch (Exception ex) { reportStatus(ex.toString()); }

 

音频格式设置:

            AudioFormat.Encoding encoding = AudioFormat.Encoding.ULAW;

                encoding = AudioFormat.Encoding.PCM_SIGNED;

                encoding = AudioFormat.Encoding.PCM_UNSIGNED;

                encoding = AudioFormat.Encoding.ALAW;

 

            return new AudioFormat(encoding, rate, sampleSize,

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

 

PARTNER CONTENT

文章评论0条评论)

登录后参与讨论
EE直播间
更多
我要评论
0
13
关闭 站长推荐上一条 /3 下一条