详细解决方案
javaCV开发详解之5:录制音频(录制麦克风)到本地文件/流媒体服务器(基于javax.sound、javaCV-FFMPEG)
热度:22 发布时间:2023-11-25 03:14:30.0
转自:http://blog.csdn.net/eguid_1/article/details/52875793
1、依赖的包
对于依赖的包,本章用到的jar包有javaCV基础支撑包(即javaCV,javaCPP)和FFMPEG及其相关平台的jar包
推荐把javaCV.bin的所有包放到项目目录中
javaCV.bin下载请到javaCV的github下载:https://github.com/bytedeco/javacv
2、代码实现
实现录制本机麦克风音频到本地文件或者流媒体服务器,
对于录制音视频混合的同学可以很方便的将本章代码移植到到录制视频的代码里
注意:由于音频、视频时两个不同线程同时进行,所以在进行混合录制的时候需要注意统一帧率,以防止音画不同步现象
-
-
-
-
-
-
-
-
- AudioFormat audioFormat = new AudioFormat(44100.0F, 16, 2, true, false);
- System.out.println("准备开启音频!");
-
- Mixer.Info[] minfoSet = AudioSystem.getMixerInfo();
-
- Mixer mixer = AudioSystem.getMixer(minfoSet[AUDIO_DEVICE_INDEX]);
-
- DataLine.Info dataLineInfo = new DataLine.Info(TargetDataLine.class, audioFormat);
-
-
-
-
-
- Line dataline = null;
- try {
- dataline = AudioSystem.getLine(dataLineInfo);
- } catch (LineUnavailableException e2) {
- System.err.println("开启失败...");
- return null;
- }
- TargetDataLine line = (TargetDataLine) dataline;
- try {
- line.open(audioFormat);
- } catch (LineUnavailableException e1) {
- line.stop();
- try {
- line.open(audioFormat);
- } catch (LineUnavailableException e) {
- System.err.println("按照指定音频编码器打开失败...");
- return null;
- }
- }
- line.start();
- System.out.println("已经开启音频!");
-
- int sampleRate = (int) audioFormat.getSampleRate();
-
- int numChannels = audioFormat.getChannels();
-
- int audioBufferSize = sampleRate * numChannels;
- byte[] audioBytes = new byte[audioBufferSize];
-
- Runnable crabAudio = new Runnable() {
- ShortBuffer sBuff = null;
- int nBytesRead;
- int nSamplesRead;
-
- @Override
- public void run() {
- System.out.println("读取音频数据...");
-
- nBytesRead = line.read(audioBytes, 0, line.available());
-
- nSamplesRead = nBytesRead / 2;
- short[] samples = new short[nSamplesRead];
-
-
-
-
-
-
- ByteBuffer.wrap(audioBytes).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(samples);
-
- sBuff = ShortBuffer.wrap(samples, 0, nSamplesRead);
-
- try {
- System.out.println("录制音频数据...");
- recorder.recordSamples(sampleRate, numChannels, sBuff);
- } catch (org.bytedeco.javacv.FrameRecorder.Exception e) {
-
- }
- }
-
- @Override
- protected void finalize() throws Throwable {
- sBuff.clear();
- sBuff = null;
- super.finalize();
- }
- };
- return crabAudio;
-
- }
3、测试录制麦克风音频
这里演示录制flv
注意:对于想要推送音频到fms,red5,nginx-rtmp等流媒体服务器的同学务必请使用flv进行封装,不管是音频还是视频
-
-
-
- public static void test2() throws InterruptedException, LineUnavailableException {
- int FRAME_RATE = 25;
- ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
- Runnable crabAudio = recordMicroPhone(4, "localAudio.flv",FRAME_RATE);
- ScheduledFuture tasker = exec.scheduleAtFixedRate(crabAudio, 0, (long) 1000 / FRAME_RATE,
- TimeUnit.MILLISECONDS);
- Thread.sleep(20 * 1000);
- tasker.cancel(true);
- if (!exec.isShutdown()) {
- exec.shutdownNow();
- }
- }