/// <summary> /// Sends a pseudo-random sample to replicate white noise. /// </summary> private void SendNoiseSample(object state) { lock (_audioStreamTimer) { int bufferSize = SAMPLE_RATE / 1000 * AUDIO_SAMPLE_PERIOD_MILLISECONDS; float[] linear = new float[bufferSize]; _signalGenerator.Read(linear, 0, bufferSize); byte[] encodedSample = new byte[bufferSize]; short[] pcm = linear.Select(x => (short)(x * 32767f)).ToArray(); if (_sendingFormat.FormatCodec == SDPMediaFormatsEnum.G722) { _g722Codec.Encode(_g722CodecState, encodedSample, pcm, bufferSize); } else { for (int index = 0; index < bufferSize; index++) { if (_sendingFormat.FormatCodec == SDPMediaFormatsEnum.PCMA) { encodedSample[index] = ALawEncoder.LinearToALawSample(pcm[index]); } else { encodedSample[index] = MuLawEncoder.LinearToMuLawSample(pcm[index]); } } } SendAudioFrame((uint)bufferSize, (int)_sendingFormat.FormatCodec, encodedSample); } }
public byte[] EncodeAudio(short[] pcm, AudioFormat format) { if (format.Codec == AudioCodecsEnum.G722) { if (_g722Codec == null) { _g722Codec = new G722Codec(); _g722CodecState = new G722CodecState(G722_BIT_RATE, G722Flags.None); } int outputBufferSize = pcm.Length / 2; byte[] encodedSample = new byte[outputBufferSize]; int res = _g722Codec.Encode(_g722CodecState, encodedSample, pcm, pcm.Length); return(encodedSample); } else if (format.Codec == AudioCodecsEnum.PCMA) { return(pcm.Select(x => ALawEncoder.LinearToALawSample(x)).ToArray()); } else if (format.Codec == AudioCodecsEnum.PCMU) { return(pcm.Select(x => MuLawEncoder.LinearToMuLawSample(x)).ToArray()); } else if (format.Codec == AudioCodecsEnum.L16) { // When netstandard2.1 can be used. //return MemoryMarshal.Cast<short, byte>(pcm) // Put on the wire in network byte order (big endian). return(pcm.SelectMany(x => new byte[] { (byte)(x >> 8), (byte)(x) }).ToArray()); } else if (format.Codec == AudioCodecsEnum.PCM_S16LE) { // Put on the wire as little endian. return(pcm.SelectMany(x => new byte[] { (byte)(x), (byte)(x >> 8) }).ToArray()); } else { throw new ApplicationException($"Audio format {format.Codec} cannot be encoded."); } }