简体   繁体   中英

java microphone TargetDataLine sensitivity / max INPUT amplitude

I am writing a core Java application (JDK 11) which should record audio and video. After extensive trial & error with various libs I managed to get both running using the deprecated Xuggler library.

However, recording audio in decent quality still remains a problem. I manage to get recordings as short[] samples and encode these, but for some reason they are cut off by the TargetDataLine at amplitude 127. I can increase them for encoding by simply multiplying them with a factor, but any recording detail above 127 is lost to noise. Ie. I can wispre into the microphone and amplify it after the fact (loud or normal speech is lost). Unfortunately I cannot control the FloatControl.Type.MASTER_GAIN in java as no control type seems to be supported by AudioSystem (if that could potentially fixed the issue);


Question:

How can I capture the full sound / sample amplitude from TargetDataLine and not get cut off at 127?


Research pointed me to the following useful threads:

How to get Audio for encoding using Xuggler

How to set volume of a SourceDataLine in Java

Java algorithm for normalizing audio

Xuggler encoding and muxing


Here is my code:

  private static void startRecordingVideo() {
      
    // total duration of the media
    long duration = DEFAULT_TIME_UNIT.convert(1, SECONDS);
    
    // video parameters
    //Dimension size = WebcamResolution.QVGA.getSize();
    //webcam.setViewSize(size);

    BufferedImage img = webCamImageStream.get(); 
    
    final int videoStreamIndex = 0;
    final int videoStreamId = 0;
    final long frameRate = DEFAULT_TIME_UNIT.convert(2, MILLISECONDS);
    
    // audio parameters
    TargetDataLine mic = null;
    final int audioStreamIndex = 1;
    final int audioStreamId = 0;
    final int channelCount = 2; //1 mono  2Stereo
    final int sampleRate = 44100; // Hz
    final int sampleSizeInBits = 16; // bit in sample
    final int frameSizeInByte = 4;  
    final int sampleCount = 588; //CD standard (588 lines per frame) 

    // the clock time of the next frame
    long nextFrameTime = 0;

    // the total number of audio samples
    long totalSampleCount = 0;

    // create a media writer and specify the output file

    final IMediaWriter writer = ToolFactory.makeWriter("capture.mp4");

    // add the video stream
    writer.addVideoStream(videoStreamIndex, videoStreamId,
            img.getWidth(), img.getHeight());
    
    // add the audio stream
    writer.addAudioStream(audioStreamIndex, audioStreamId,
        channelCount, sampleRate);


    //define audio format
    AudioFormat audioFormat = new AudioFormat(
            AudioFormat.Encoding.PCM_SIGNED, 
            sampleRate, 
            sampleSizeInBits, 
            channelCount,
            frameSizeInByte, 
            sampleRate, 
            true);
    DataLine.Info info = new DataLine.Info(TargetDataLine.class, audioFormat);
    AudioInputStream audioInputStream = null; 
   
        try {       
            mic = (TargetDataLine) AudioSystem.getLine(info);
            //mic.open();
            mic.open(audioFormat, mic.getBufferSize());
             // Adjust the volume on the output line.
             if (mic.isControlSupported(FloatControl.Type.MASTER_GAIN)) {
                FloatControl gain = (FloatControl) mic.getControl(FloatControl.Type.MASTER_GAIN);
                gain.setValue(-10.0f); // attempt to Reduce volume by 10 dB.
             }else {
                 System.out.println("Not supported in my case :'( ");
             }
            
            mic.start();
            audioInputStream = new AudioInputStream(mic);
    
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    // loop through clock time, which starts at zero and increases based
    // on the total number of samples created thus far
    long start = System.currentTimeMillis(); 
    //duration = frameRate; 
    recordingVideo = true; 
    updateUI("Recording");
    System.out.println("Audio Buffer size : " + mic.getBufferSize());
    coverImage = webCamImageStream.get();
    int frameCount = 0;

//IGNOR Complexity of for Loop*******************************************************************
    for (long clock = 0; clock < duration;  clock = IAudioSamples.samplesToDefaultPts(totalSampleCount, sampleRate)){
      // while the clock time exceeds the time of the next video frame,
      // get and encode the next video frame
      while (frameCount * clock >= nextFrameTime) {
                BufferedImage image = webCamImageStream.get();
                IConverter converter = ConverterFactory.createConverter(image, IPixelFormat.Type.YUV420P);
                IVideoPicture frame = converter.toPicture(image, (System.currentTimeMillis() - start) * 1000);
                writer.encodeVideo(videoStreamIndex, frame);
        nextFrameTime += frameRate;
      }
      
      
//##################################### Audio Recording section #######################################
      

      int factor = 2; 
      byte[] audioBytes = new byte[mic.getBufferSize() ]; // best size?
      int numBytesRead = 0;
        try {
            numBytesRead =  audioInputStream.read(audioBytes, 0, audioBytes.length);
            //error is probably here as it is only reading up to 127
        } catch (IOException e) {
            numBytesRead =  mic.read(audioBytes, 0, audioBytes.length);
            e.printStackTrace();
        }
     
        mic.flush();
          // max for normalizing
          short rawMax = Short.MIN_VALUE;
          for (int i = 0; i < numBytesRead; ++i) {
              short value = audioBytes[i];
              rawMax = (short) Math.max(rawMax, value);
          }

//127 is max input amplitude (microphone could go higher but its cut off) ###############################

        //values at and over 127 are static noises
        System.out.println("MAX = " +rawMax );
      
      // convert to signed shorts representing samples
        int volumeGainfactor = 2;
      int numSamplesRead = numBytesRead / factor;
      short[] audioSamples = new short[ numSamplesRead ];
      if (audioFormat.isBigEndian()) {
          for (int i = 0; i < numSamplesRead; i++) {
              audioSamples[i] = (short)((audioBytes[factor*i] << 8) | audioBytes[factor*i + 1]);
          }
      }
      else {
          for (int i = 0; i < numSamplesRead; i++) {
              audioSamples[i] = (short)(((audioBytes[factor*i + 1] ) << 8) |(audioBytes[factor*i])) ;
              
                    //normalization -> does not help (issue lies in Max read value) 
                    //short targetMax = 127; //maximum volume 
                    //Normalization method
                    /*
                        double maxReduce = 1 - targetMax/(double)rawMax;
                        int abs = Math.abs(audioSamples[i]);
                        double factor1 = (maxReduce * abs/(double)rawMax);
                        audioSamples[i] = (short) Math.round((1 - factor1) * audioSamples[i]); 
                    */
              //https://stackoverflow.com/questions/12469361/java-algorithm-for-normalizing-audio
          }
      }

//##################################### END Audio Recording Section #####################################  
    

      writer.encodeAudio(audioStreamIndex, audioSamples, clock, 
        DEFAULT_TIME_UNIT);
      //extend duration if video is not terminated 
      if(!recordingVideo) {break;}
      else {duration += 22675;} //should never catch up to duration 
      // 22675 = IAudioSamples.samplesToDefaultPts(588, sampleRate)
      //totalSampleCount += sampleCount;
      totalSampleCount = sampleCount; 
      frameCount++; 
    }
    
    
    // manually close the writer
    writer.close();
    mic.close();
    }

Debug Print Example:

 MAX = 48 (is recorded)

 MAX = 127 (is static noise)

Ok so it seems like I managed to fix it through trial and error & This post:

reading wav/wave file into short[] array

The issue was with the conversion of byte[] (origin) to short[].

  1. the audioFormat had to be set to BigEndian = false
AudioFormat audioFormat = new AudioFormat(
            AudioFormat.Encoding.PCM_SIGNED, 
            sampleRate, 
            sampleSizeInBits, 
            channelCount,
            frameSizeInByte, 
            sampleRate, 
            false);`
  1. the conversion from Bytes to Short needs to be as follows
      int factor = 2; 
      byte[] audioBytes = new byte[mic.getBufferSize() ];
      int numBytesRead = 0;
      numBytesRead =  audioInputStream.read(audioBytes, 0, audioBytes.length);

      mic.flush();
      
      // convert to signed shorts representing samples
      int volumeGainfactor = 2;
      int numSamplesRead = numBytesRead / factor;
      short[] audioSamples = new short[ numSamplesRead ];
      if (audioFormat.isBigEndian()) {
          for (int i = 0; i < numSamplesRead; i++) {
              //BigEndian Conversion not working
              audioSamples[i] = (short)((audioBytes[factor*i] << 8) | audioBytes[factor*i + 1]);
          }
      }
      else {
          for (int i = 0; i < numSamplesRead; i++) {
____________________________________________________ ISSUE WAS HERE __________________________________________
              audioSamples[i] = ( (short)( ( audioBytes[i*2] & 0xff )|( audioBytes[i*2 + 1] << 8 )) );
____________________________________________________________________________________________________      
          }
      }

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