录音在java中不工作

2024-01-06

我正在尝试通过java录制声音,该声音正在我的Windows机器上通过扬声器/耳机播放。

我遇到的问题是我没有找到 AudioSystem 支持的单个 TargetDataLine。

我尝试了 getSupportedFormats() 方法来检查是否有任何可以获取的 TargetDataLine,但是我得到了 0 行。如果将 getSupportedFormats 中的参数更改为 SourceDataLine,我将获得 9 个可用行。

     Vector<AudioFormat> formats = getSupportedFormats(TargetDataLine.class);
    System.out.println(formats.size());

     public static Vector<AudioFormat> getSupportedFormats(Class<?> dataLineClass) {
    /*
     * These define our criteria when searching for formats supported
     * by Mixers on the system.
     */
    float sampleRates[] = { (float) 8000.0, (float) 16000.0, (float) 44100.0 };
    int channels[] = { 1, 2 };
    int bytesPerSample[] = { 2 };

    AudioFormat format;
    DataLine.Info lineInfo;

    //SystemAudioProfile profile = new SystemAudioProfile(); // Used for allocating MixerDetails below.
    Vector<AudioFormat> formats = new Vector<AudioFormat>();

    for (Mixer.Info mixerInfo : AudioSystem.getMixerInfo()) {
        for (int a = 0; a < sampleRates.length; a++) {
            for (int b = 0; b < channels.length; b++) {
                for (int c = 0; c < bytesPerSample.length; c++) {
                    format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
                            sampleRates[a], 8 * bytesPerSample[c], channels[b], bytesPerSample[c],
                            sampleRates[a], false);
                    lineInfo = new DataLine.Info(dataLineClass, format);
                    if (AudioSystem.isLineSupported(lineInfo)) {
                        /*
                         * TODO: To perform an exhaustive search on supported lines, we should open
                         * TODO: each Mixer and get the supported lines. Do this if this approach
                         * TODO: doesn't give decent results. For the moment, we just work with whatever
                         * TODO: the unopened mixers tell us.
                         */
                        if (AudioSystem.getMixer(mixerInfo).isLineSupported(lineInfo)) {
                            formats.add(format);
                        }
                    }
                }
            }
        }
    }
    return formats;
}

另外,我已经尝试了 audioFormats 方法返回的大多数格式,但仍然无法找到一行。

public List<AudioFormat> audioFormats() throws LineUnavailableException{
Mixer.Info[] mi = AudioSystem.getMixerInfo();
List<AudioFormat> audioFormats = new ArrayList<AudioFormat>();
for (Mixer.Info info : mi) {
    System.out.println("info: " + info);
    Mixer m = AudioSystem.getMixer(info);
    System.out.println("mixer " + m);
    Line.Info[] sl = m.getSourceLineInfo();
    for (Line.Info info2 : sl) {
        System.out.println("    info: " + info2);
        Line line = AudioSystem.getLine(info2);
        if (line instanceof SourceDataLine) {
            SourceDataLine source = (SourceDataLine) line;

            DataLine.Info i = (DataLine.Info) source.getLineInfo();
            for (AudioFormat format : i.getFormats()) {
                audioFormats.add(format);
                System.out.println("    format: " + format);
            }
        }
    }
}
return audioFormats;
}

这是我尝试过的示例类

    import javax.sound.sampled.*;
    import javax.sound.sampled.AudioFormat.Encoding; 
    import java.io.*;


    public class Recorder {
    // record duration, in milliseconds
    static final long RECORD_TIME = 30000;  // 1 minute

// path of the wav file
File wavFile = new File("spacemusic.wav");

// format of audio file
AudioFileFormat.Type fileType = AudioFileFormat.Type.WAV;

// the line from which audio data is captured
TargetDataLine line;

/**
 * Defines an audio format
 */
AudioFormat getAudioFormat() {
    float sampleRate = 44100;
    int sampleSizeInBits = 16;
    int channels = 2; 
    boolean bigEndian = false;
    Encoding encoding = Encoding.PCM_SIGNED;
    int frameSize = 4;
    float framRate = 44100;
   /* AudioFormat format = new AudioFormat(sampleRate, sampleSizeInBits,
                                     channels, signed, bigEndian);*/
    AudioFormat format = new AudioFormat(encoding, sampleRate, sampleSizeInBits, channels, frameSize, framRate, bigEndian);
    return format;
}

/**
 * Captures the sound and record into a WAV file
 * @throws UnsupportedAudioFileException 
 */
void start() throws UnsupportedAudioFileException {
    try {

        AudioFormat format = getAudioFormat();  
        DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);  
        if (!AudioSystem.isLineSupported(info)) {
            System.out.println("Line not supported");
            System.exit(0);
        }
        line = (TargetDataLine) AudioSystem.getLine(info);
        line.open(format);
        line.start();   // start capturing

        System.out.println("Start capturing...");

        AudioInputStream ais = new AudioInputStream(line);

        System.out.println("Start recording...");

        // start recording
        AudioSystem.write(ais, fileType, wavFile);

    } catch (LineUnavailableException ex) {
        ex.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

/**
 * Closes the target data line to finish capturing and recording
 */
void finish() {
    line.stop();
    line.close();
    System.out.println("Finished");
}

/**
 * Entry to run the program
 * @throws UnsupportedAudioFileException 
 */
public static void main(String[] args) throws UnsupportedAudioFileException {
    final Recorder recorder = new Recorder();

    // creates a new thread that waits for a specified
    // of time before stopping
    Thread stopper = new Thread(new Runnable() {
        public void run() {
            try {
                Thread.sleep(RECORD_TIME);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
            recorder.finish();
        }
    });

    stopper.start();

    // start recording
    recorder.start();
}

}

关于如何获得受支持的线路以便我可以继续录制的任何想法。谢谢


你可以尝试一下这门课。对我来说效果很好。我从麦克风捕获音频并将其保存到文件中(即 file.au)

首先,复制所有内容并在项目中创建一个新类

`

  import javax.swing.*;
  import java.awt.*;
  import java.awt.event.*;
  import java.io.*;

  import javax.sound.sampled.*;

 // Class for capturing and saving into file, audio from mic




public class AudioCaptureAndSaveIntoFile {

boolean stopCapture = false;
ByteArrayOutputStream byteArrayOutputStream;
AudioFormat audioFormat;
TargetDataLine targetDataLine;
AudioInputStream audioInputStream;
SourceDataLine sourceDataLine;

FileOutputStream fout;
AudioFileFormat.Type fileType;

public AudioRecorder() {
}

// Captures audio input
// from mic.
// Saves input in
// a ByteArrayOutputStream.
public void captureAudio() {
    try {

        audioFormat = getAudioFormat();
        DataLine.Info dataLineInfo = new DataLine.Info(
                TargetDataLine.class, audioFormat);
        targetDataLine = (TargetDataLine) AudioSystem.getLine(dataLineInfo);
        targetDataLine.open(audioFormat);
        targetDataLine.start();

        // Thread to capture from mic
        // This thread will run till stopCapture variable
        // becomes true. This will happen when saveAudio()
        // method is called.
        Thread captureThread = new Thread(new CaptureThread());
        captureThread.start();
    } catch (Exception e) {
        System.out.println(e);
        System.exit(0);
    }
}

// Saves the data from
// ByteArrayOutputStream
// into a file
public void saveAudio(File filename) {
    stopCapture = true;
    try {

        byte audioData[] = byteArrayOutputStream.toByteArray();

        InputStream byteArrayInputStream = new ByteArrayInputStream(
                audioData);
        AudioFormat audioFormat = getAudioFormat();
        audioInputStream = new AudioInputStream(byteArrayInputStream,
                audioFormat, audioData.length / audioFormat.getFrameSize());
        DataLine.Info dataLineInfo = new DataLine.Info(
                SourceDataLine.class, audioFormat);
        sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
        sourceDataLine.open(audioFormat);
        sourceDataLine.start();

        // This thread will actually do the job
        Thread saveThread = new Thread(new SaveThread(filename));
        saveThread.start();
    } catch (Exception e) {
        System.out.println(e);
        System.exit(0);
    }
}

public AudioFormat getAudioFormat() {
    float sampleRate = 8000.0F;
    // You can try also 8000,11025,16000,22050,44100
    int sampleSizeInBits = 16;
    int channels = 1;
    boolean signed = true;
    boolean bigEndian = false;
    return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed,
            bigEndian);
}

class CaptureThread extends Thread {
    // temporary buffer
    byte tempBuffer[] = new byte[10000];

    public void run() {
        byteArrayOutputStream = new ByteArrayOutputStream();
        stopCapture = false;
        try {
            while (!stopCapture) {

                int cnt = targetDataLine.read(tempBuffer, 0,
                        tempBuffer.length);
                if (cnt > 0) {

                    byteArrayOutputStream.write(tempBuffer, 0, cnt);

                }
            }
            byteArrayOutputStream.close();
        } catch (Exception e) {
            System.out.println(e);
            System.exit(0);
        }
    }
}

class SaveThread extends Thread {
    // Set a file from saving from ByteArrayOutputStream
    File fname;

    public SaveThread(File fname) {
        this.fname = fname;
    }

    //
    byte tempBuffer[] = new byte[10000];

    public void run() {
        try {
            int cnt;

            if (AudioSystem.isFileTypeSupported(AudioFileFormat.Type.AU,
                    audioInputStream)) {
                AudioSystem.write(audioInputStream,
                        AudioFileFormat.Type.AU, fname);
            }

        } catch (Exception e) {
            System.out.println(e);
            System.exit(0);
        }
    }
}

  }

  ` 

在您的项目中使用上面的类,如下所示:

要将麦克风中的音频捕获到临时 ByteArrayOutput 对象中,首先:

audiorec = new AudioCaptureAndSaveIntoFile(); audiorec.captureAudio();

并保存到文件中:

 audiorec.saveAudio(savefile); 

注意:您保存的文件应该以 ie 结尾。 “.au”或“.wav”

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

录音在java中不工作 的相关文章

随机推荐

  • 在 Spring4+STOMP+SockJS 应用程序中配置外部代理(RabbitMQ)

    我正在开发一个聊天应用程序 该应用程序使用 Spring4 Messaging 开发 并使用 SockJS 实现 STOMP 当我使用时该应用程序运行良好简单消息代理 config enableSimpleBroker queue topi
  • 如何在 GWT 表单面板中发布整个页面

    使用 GWT FormPanel 时 提交表单后 它会发布表单但不会重定向到操作 url 有谁能够帮助我 formPanelObject getElement
  • SSIS存储过程使用临时表2008和2014

    我目前正在编写一个 SSIS 包 它通过 OLE DB 源从存储过程中检索数据 存储过程包含一个相当讨厌的查询 我可以通过使用临时表来改进它 如果我将这些临时表切换为表变量 逻辑读取次数会从大约 130 万次跃升至大约 5600 万次 我对
  • 如何在android列表视图中使整行可点击

    我有一个ListView 其内容假设android在第一行 黑莓在第二行 iphone在第三行 所以现在我想让ListView的整行可点击 但是当我点击listview行的上面内容时 它只执行点击事件 但我如果我单击连续的任何位置 则应该执
  • 如何向已调试的Android应用程序授予权限?

    I have
  • Gitlab CI 作业在运行 mocha 测试之前成功

    我发现我的 Gitlab 作业正在成功并在实际测试运行之前结束 首先 我为我的应用程序安装所需的依赖项 然后调用mocha命令 但作业在它们产生任何输出之前就成功了 我的 gitlab ci yml image node lts alpin
  • ParticleSystem 中 BufferGeometry 的 Z 缓冲区问题

    在我的应用程序中 我遇到了 z 缓冲区的问题 我有一个粒子系统 其中的点具有看起来像球体的纹理 但有两个问题我无法同时解决 球体要么在 z 缓冲区中正确排序但不透明 要么它们是透明的但排序不正确 请看看我的JSfiddle http jsf
  • Java 泛型 - 类型信息消失?

    好的 我知道 Java 泛型对于粗心的人来说可能是一个雷区 但我刚刚遇到了一个不直观的 无论如何对我来说 行为 我想知道是否有人可以解释 首先 这是一个编译类 public class Dummy public List
  • Gradle 食谱“为其他插件创建源和资源目录”

    我可以在食谱中看到以下内容 task create dirs lt lt sourceSets all java srcDirs each it mkdirs sourceSets all resources srcDirs each it
  • 在 Google Cloud 中将 http 重定向到 https

    我已经设置了一个负载均衡器 它接受来自用户的 https 连接 然后 计算引擎使用 http 连接连接到负载均衡器 我在根文件夹中编写了以下 htaccess 文件 RewriteEngine On RewriteCond HTTPS of
  • 如何计算图表的趋势线?

    谷歌不是我的朋友 自从我在大学上统计课以来已经很长时间了 我需要计算图表上趋势线的起点和终点 有没有一种简单的方法可以做到这一点 使用 C 工作 但任何适合你的语言 感谢大家的帮助 我已经离开这个问题几天了 刚刚回来 能够将其拼凑在一起 不
  • 在Python中,一行中的多个“with”语句是否相当于嵌套的“with”语句?

    这两个陈述等价吗 with A as a B as b do something with A as a with B as b do something 我问是因为两者a and b改变全局变量 这里是张量流 和b取决于所做的更改a 所以
  • 使用 Git diff 检测代码移动 + 如何使用 diff 选项

    考虑文件 1 c 包含三个函数以及作者 M 和 J 所做的更改 如果有人运行git blame 1 c 他将得到以下输出 869c699 M 2012 09 25 14 05 31 0600 1 de24af82 J 2012 09 25
  • MVC @Html.DropDownList 在 ViewBag 中使用 SelectList 时出现错误

    我有一个在控制器中创建的列表 var PayList new new ListEntry Id 1 Name new ListEntry Id 2 Name Yes new ListEntry Id 3 Name No ViewBag Pa
  • 如何使用事件处理程序检测实时 DigiScan 图像何时完成获取完整帧?

    我正在寻找实时 DigiScan 图像的快照 但是 我只想在获取完整 或接近完整 的帧时才这样做 将事件处理程序附加到实时 DigiScan 图像不起作用 因为图像会随着连续采集的每一行而 变化 我希望仅监视实时图像的最后几个像素 并仅在这
  • Wordpress 有条件 if is_single

    我尝试在我的 single php 页面上使用条件语句 我想要做的是 如果它是自定义帖子类型 current products 则使用特定的 single product php 模板页面 如果不是 即标准博客文章 则使用默认的 singl
  • 使用 LINQ to MySQL (DbLinq) 和动态 LINQ 的可排序 JqGrid - Orderby 不起作用

    我在 JqGrid 中排序条目时遇到问题 Orderby 似乎不起作用 我在代码中设置了断点 我注意到 orderby 不会改变元素的顺序 知道可能出什么问题吗 我正在使用 LINQ to SQL 和 MySQL DbLinq 项目 我的操
  • 如何使用 BERT 进行机器翻译?

    我遇到了一个大问题 对于我的学士论文 我必须使用 BERT 制作一个机器翻译模型 但我现在一事无成 您知道可以在这里帮助我的文档或其他东西吗 我已经阅读了一些这方面的论文 但也许有文档或教程可以帮助我 对于我的学士论文 我必须将文本摘要翻译
  • 如何让 JavaScript 延迟,然后刷新页面

    我希望我的 JavaScript 在我创建的函数结束时等待七秒钟 然后刷新我的页面 如果它很重要 我在下面列出了 JavaScript 和 HTML 的重要部分 JavaScript var textfill function var no
  • 录音在java中不工作

    我正在尝试通过java录制声音 该声音正在我的Windows机器上通过扬声器 耳机播放 我遇到的问题是我没有找到 AudioSystem 支持的单个 TargetDataLine 我尝试了 getSupportedFormats 方法来检查