简体   繁体   中英

Java TargetDataLine not picking up any audio?

I'm writing a function to capture an audio clip for ~ 7.5 seconds using a TargetDataLine. The code executes and renders an 'input.wav' file, but when I play it there is no sound.

My approach, as shown in the code at the bottom of this post, is to do the following things:

  1. Create an AudioFormat and get the Info for a Target Data Line.
  2. Create the Target Data Line by getting the line from AudioSystem.
  3. Open and Start the TargetDataLine, which allocates system resources for recording.
  4. Create an auxiliary Thread that will record audio by writing to a file.
  5. Start the auxiliary Thread, pause the main Thread in the meantime, and then close out the Target Data Line in order to stop recording.

What I have tried so far:

  1. Changing the AudioFormat. Initially, I was using the other AudioFormat constructor which takes the file type as well (where the first argument is AudioFormat.Encoding.PCM_SIGNED etc). I had a sample rate of 44100, 16 bits, 2 channels and small-Endian settings on the other format, which yielded the same result.

  2. Changing the order of commands on my auxiliary and main Thread (ie performing TLine.open() or start() in alternate locations).

  3. Checking that my auxiliary thread does actually start.

For reference I am using IntelliJ on a Mac OS Big Sur.

public static void captureAudio() {
        try {
            AudioFormat f = new AudioFormat(22050, 8, 1, false, false);
            DataLine.Info secure = new DataLine.Info(TargetDataLine.class, f);
            if (!AudioSystem.isLineSupported(secure)) {
                System.err.println("Unsupported Line");
            }
            TargetDataLine tLine = (TargetDataLine)AudioSystem.getLine(secure);
            System.out.println("Starting recording...");
            tLine.open(f);
            tLine.start();
            File writeTo = new File("input.wav");
            Thread t = new Thread(){
                    public void run() {
                        try {
                            AudioInputStream is = new AudioInputStream(tLine);
                            AudioSystem.write(is, AudioFileFormat.Type.WAVE, writeTo);
                        } catch(IOException e) {
                            System.err.println("Encountered system I/O error in recording:");
                            e.printStackTrace();
                        }
                    }
            };
            t.start();
            Thread.sleep(7500);
            tLine.stop();
            tLine.close();
            System.out.println("Recording has ended.");
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

Update 1: Some new testing and results

  1. My microphone and speakers are both working with other applications - recorded working audio with QuickTimePlayer.

  2. I did a lot of testing around what my TargetDataLines are and what the deal is with them. I ran the following code:

public static void main(String[] args) {
AudioFormat f = new AudioFormat(48000, 16, 2, true, false);
        //DataLine.Info inf = new DataLine.Info(SourceDataLine.class, f);
        try {
            TargetDataLine line = AudioSystem.getTargetDataLine(f);
            DataLine.Info test = new DataLine.Info(TargetDataLine.class, f);
            TargetDataLine other = (TargetDataLine)AudioSystem.getLine(test);
            String output = line.equals(other) ? "Yes" : "No";
            if (output.equals("No")) {
                System.out.println(other.toString());
            }
            System.out.println(line.toString());
            System.out.println("_______________________________");
            for (Mixer.Info i : AudioSystem.getMixerInfo()) {
                Line.Info[] tli = AudioSystem.getMixer(i).getTargetLineInfo();
                if (tli.length != 0) {
                   Line comp = AudioSystem.getLine(tli[0]);
                   System.out.println(comp.toString() + ":" +i.getName());
                   if (comp.equals(line) || comp.equals(other)) {
                       System.out.println("The TargetDataLine is from " + i.getName());
                   }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
}

Long story short, the TargetDataLine I receive from doing TargetDataLine line = AudioSystem.getTargetDataLine(f); and TargetDataLine other = (TargetDataLine)AudioSystem.getLine(new DataLine.Info(TargetDataLine.class, f)); are different, and furthermore, don't match any of the TargetDataLines that are associated with my system's mixers.

The output of the above code was this (where there first lines are other and line respectively):

com.sun.media.sound.DirectAudioDevice$DirectTDL@cc34f4d
com.sun.media.sound.DirectAudioDevice$DirectTDL@17a7cec2
_______________________________
com.sun.media.sound.PortMixer$PortMixerPort@79fc0f2f:Port MacBook Pro Speakers
com.sun.media.sound.PortMixer$PortMixerPort@4d405ef7:Port ZoomAudioDevice
com.sun.media.sound.DirectAudioDevice$DirectTDL@3f91beef:Default Audio Device
com.sun.media.sound.DirectAudioDevice$DirectTDL@1a6c5a9e:MacBook Pro Microphone
com.sun.media.sound.DirectAudioDevice$DirectTDL@37bba400:ZoomAudioDevice
  1. Upon this realization I manually loaded up all the TargetDataLines from my mixers and tried recording audio with each of them to see if I got any sound.

I used the following method to collect all the TargetDataLines:

public static ArrayList<Line.Info> allTDL() {
        ArrayList<Line.Info> all = new ArrayList<>();
        for (Mixer.Info i : AudioSystem.getMixerInfo()) {
            Line.Info[] tli = AudioSystem.getMixer(i).getTargetLineInfo();
            if (tli.length != 0) {
                for (int f = 0; f < tli.length; f += 1) {
                    all.add(tli[f]);
                }
            }
        }
        return all;
    }

My capture/record audio method remained the same, except for switching the format to AudioFormat f = new AudioFormat(48000, 16, 2, true, false); , changing the recording time to 5000 milliseconds, and writing the method header as public static void recordAudio(Line.Info inf) so I could load each TargetDataLine individually with it's info.

I then executed the following code to rotate TargetDataLines:

public static void main(String[] args) {
   for (Line.Info inf : allTDL()) {
            recordAudio(inf);
            try {
                Thread.sleep(5000);
            } catch(Exception e) {
                e.printStackTrace();
            }
            if (!soundless(loadAsBytes("input.wav"))) {
                System.out.println("The recording with " + inf.toString() + " has sound!");
            }
            System.out.println("The last recording with " + inf.toString() + " was soundless.");
        }

    }
}

The output was as such:

Recording...
Was unable to cast com.sun.media.sound.PortMixer$PortMixerPort@506e1b77 to a TargetDataLine.
End recording.
The last recording with SPEAKER target port was soundless.
Recording...
Was unable to cast com.sun.media.sound.PortMixer$PortMixerPort@5e9f23b4 to a TargetDataLine.
End recording.
The last recording with ZoomAudioDevice target port was soundless.
Recording...
End recording.
The last recording with interface TargetDataLine supporting 8 audio formats, and buffers of at least 32 bytes was soundless.
Recording...
End recording.
The last recording with interface TargetDataLine supporting 8 audio formats, and buffers of at least 32 bytes was soundless.
Recording...
End recording.
The last recording with interface TargetDataLine supporting 14 audio formats, and buffers of at least 32 bytes was soundless.

TL;DR the audio came out soundless for every TargetDataLine. For completeness, here are the soundless and loadAsBytes functions:

 public static byte[] loadAsBytes(String name) {
        assert name.contains(".wav");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        File retrieve = new File("src/"+ name);
        try {
            InputStream input = AudioSystem.getAudioInputStream(retrieve);

            int read;
            byte[] b = new byte[1024];
            while ((read = input.read(b)) > 0) {
                out.write(b, 0, read);
            }
            out.flush();
            byte[] full = out.toByteArray();
            return full;

        } catch(UnsupportedAudioFileException e) {
            System.err.println("The File " + name + " is unsupported on this system.");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("Input-Output Exception on retrieval of file " + name);
            e.printStackTrace();
        }
        return null;

    }

  static boolean soundless(byte[] s) {
        if (s == null) {
            return true;
        }
        for (int i = 0; i < s.length; i += 1) {
            if (s[i] != 0) {
                return false;
            }
        }
        return true;
    }

I'm not really sure what the issue could be at this point save for an operating system quirk that doesn't allow Java to access audio lines, but I do not know how to fix that - looking at System Preferences there isn't any obvious way to allow access. I think it might have to be done with terminal commands but also not sure of precisely what commands I'd have to execute there.

I'm not seeing anything wrong in the code you are showing. I haven't tried testing it on my system though. (Linux, Eclipse)

It seems to me your code closely matches this tutorial . The author Nam Ha Minh is exceptionally conscienscious about answering questions. You might try his exact code example and consult with him if his version also fails for you.

But first, what is the size of the resulting.wav file? Does the file size match the amount of data expected for the duration you are recording? If so, are you sure you have data incoming from your microphone? Nam has another code example where recorded sound is progressively read and placed into memory. Basically, instead of using the AudioInputStream as a parameter to the AudioSystem.write method, you execute multiple read method calls on the AudioInputStream and inspect the incoming data directly. That might be helpful for trouble-shooting whether the problem is occurring on the incoming vs outgoing part of the process.

I'm not knowledgeable enough about formats to know if the Mac does things differently. I'm surprised you are setting the format to unsigned . For my limited purposes, I stick with "CD quality stereo" and signed PCM at all junctures.

EDIT: based on feedback, it seems that the problem is that the incoming line is not returning data. From looking at other, similar tutorials, it seems that several people have had the same problem on their Mac systems.

First thing to verify: does your microphone work with other applications?

As far as next steps, I would try verifying the chosen line. The lines that are exposed to java can be enumerated/inspected. The tutorial Accessing Audio System Resources has some basic information on how to do this. It looks like AudioSystem.getMixerInfo() will return a list of available mixers that can be inspected. Maybe AudioSystem.getTargetLineInfo() would be more to the point.

I suppose it is possible that the default Line or Port being used when you obtain a TargetDataLine isn't the one that is running the microphone. If a particular line or port turns out to be the one you need, then it can be specified explicitly via an overridden getTargetDataLine method .

I'm reading that there might be a security policy that needs to be handled. I don't fully understand the code, but if that were the issue, an Exception presumably would have been thrown. Perhaps there are new security measures coming from the MacOs, to prevent an external program from opening a mic line surreptitiously?

If you do get this solved, be sure and post the answer and mark it solved. This seems to be a live question for many people.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM