简体   繁体   中英

How to record sound from the microphone?

I'm trying to figure out how to record sound from the microphone using my MacBookPro. I'm not sure if this is a problem with the code or if this is a problem with hidden permissions within MacOS.

I've been through most of the tutorials and tried various different solutions to the point that I've created the test case below.

public class AudioLinesTester {

    private static final Logger LOGGER = LoggerFactory.getLogger(AudioLinesTester.class);

    public static void main(String[] args) {

        LOGGER.debug("Starting Line tester");

        AudioFormat format = new AudioFormat(8000.0f, 8, 1, true, true);

        Mixer.Info[] infos = AudioSystem.getMixerInfo();

        Map<Line.Info, byte[]> sounds = new HashMap<Line.Info, byte[]>();

        Stream.of(infos).forEach(mixerInfo -> {
            Mixer mixer = AudioSystem.getMixer(mixerInfo);
            Line.Info[] lineInfos = mixer.getTargetLineInfo();
            if (lineInfos.length > 0 && lineInfos[0].getLineClass().equals(TargetDataLine.class)) {
                // The name of the AudioDevice
                LOGGER.debug("Line Name: {}", mixerInfo.getName());
                // The type of audio device
                LOGGER.debug("Line Description: {}", mixerInfo.getDescription());

                for (Line.Info lineInfo : lineInfos) {
                    LOGGER.debug("\t---{}", lineInfo);
                    Line line;
                    try {
                        line = mixer.getLine(lineInfo);
                        TargetDataLine microphone = AudioSystem.getTargetDataLine(format, mixerInfo);
                        microphone.open(format, 100352);

                        LOGGER.debug("Listening on {}", microphone);

                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        int numBytesRead;
                        int CHUNK_SIZE = 1024;
                        byte[] data = new byte[microphone.getBufferSize() / 5];
                        microphone.start();

                        int bytesRead = 0;

                        try {
                            // Just so I can test if recording my mic works...
                            while (bytesRead < 100000) { 
                                numBytesRead = microphone.read(data, 0, CHUNK_SIZE);
                                bytesRead = bytesRead + numBytesRead;
//                              LOGGER.debug("Bytes read from the microphone : {} ", bytesRead);
                                out.write(data, 0, numBytesRead);
                            }
                        } catch (Exception e) {
                            LOGGER.error("Error trying to read from the microphone", e);
                        }
                        byte[] read = out.toByteArray();
                        LOGGER.debug("Have read {} bytes: {}", read.length, read);
                        sounds.put(lineInfo, read);

//                      microphone.drain();
                        microphone.stop();
                        microphone.close();

                    } catch (LineUnavailableException e) {
                        LOGGER.error("Something went wrong {}", e);
                        return;
                    }
                    LOGGER.debug("\t-----{}", line);
                }
            }
        });

        sounds.forEach((k,v) -> {
            LOGGER.debug("Trying to play the data capture on {}", k);
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
            LOGGER.debug("Got a new output line: {}", info);
            SourceDataLine line;
            try {
                line = (SourceDataLine) AudioSystem.getLine(info);

                line.open(format, v.length);
                line.start();
                long now = System.currentTimeMillis();
                LOGGER.debug("buffer size: {}", line.available());
                int written = line.write(v, 0, v.length);
                line.drain();
                line.close();
                LOGGER.debug("{} bytes written.", written);
                long total = System.currentTimeMillis() - now;
                LOGGER.debug("{}ms.", total);
            } catch (LineUnavailableException e) {
                LOGGER.error("Unable to play the sound", e);
            }
        });

        LOGGER.debug("Ending Lines tester");
    }

}

I was hoping to get some output from something, but I'm just getting byte arrays populated with 0.

Is anyone able to help?

Ok, so after a lot of to-ing and fro-ing and fighting with the laptop... The solution was to install a new version of Eclipse, at which point the Mac asked if I wanted to allow Java permission to access to microphone.

Hopefully this will help someone out there.

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