public static AudioTrack FindAudioTrack(ref int sampleRate, ref Android.Media.Encoding audioFormat, ref ChannelOut channelConfig, ref int bufferSize) { foreach (var sr in _sampleRates) { foreach (var af in new Android.Media.Encoding[] { Android.Media.Encoding.Pcm16bit, Android.Media.Encoding.Pcm8bit }) { foreach (var cc in new ChannelOut[] { ChannelOut.Stereo, ChannelOut.Mono }) { foreach (var atm in new AudioTrackMode[] { AudioTrackMode.Static, AudioTrackMode.Stream}) { int bs = AudioTrack.GetMinBufferSize(sr, cc, af); if (bs > 0) { var audioTrack = new AudioTrack(Stream.Music, sr, cc, af, bs, atm); if (audioTrack.State == AudioTrackState.Initialized) { sampleRate = sr; audioFormat = af; channelConfig = cc; bufferSize = bs; return audioTrack; } } } } } } return null; }
private Track(Stream streamType, int sampleRateInHz, ChannelOut channelConfig, Encoding audioFormat, int bufferSizeInBytes, AudioTrackMode mode, int sessionId, int dataLength, byte[] data) : base(streamType, sampleRateInHz, channelConfig, audioFormat, bufferSizeInBytes, mode, sessionId) { TrackDataLength = dataLength; TrackData = data; }
public bool Open(string waveOutDeviceName, int samplesPerSecond, int bitsPerSample, int channels, int bufferCount) { Encoding depthBits = Encoding.Pcm16bit; if (bitsPerSample == 16) { depthBits = Encoding.Pcm16bit; } else if (bitsPerSample == 8) { depthBits = Encoding.Pcm8bit; } ChannelOut ch = ChannelOut.Mono; if (channels == 1) { ch = ChannelOut.Mono; } else { ch = ChannelOut.Stereo; } #pragma warning disable CS0618 // Type or member is obsolete audioTrack = new AudioTrack( // Stream type Stream.Music, // Frequency samplesPerSecond, //samplesPerSecond, // Mono or stereo ch, // Audio encoding depthBits, //Encoding.PcmFloat, //Encoding.Pcm8bit, // Length of the audio clip. //1024 * 1024, bufferCount, // Mode. Stream or static. AudioTrackMode.Stream); #pragma warning restore CS0618 // Type or member is obsolete return(true); }
private AudioTrack GetAudioTrack() { ChannelOut channelOut = _channels == 2 ? ChannelOut.Stereo : ChannelOut.Mono; Encoding encoding = Encoding.Pcm16bit;; int bufferSize = AudioTrack.GetMinBufferSize(_sampleRate, channelOut, encoding) * 2; AudioTrack audioTrack; AudioAttributes.Builder attributesBuilder = new AudioAttributes.Builder() .SetUsage(AudioUsageKind.Game); AudioFormat format = new AudioFormat.Builder() .SetEncoding(encoding) .SetSampleRate(_sampleRate) .SetChannelMask(channelOut) .Build(); if (Build.VERSION.SdkInt < BuildVersionCodes.O) { attributesBuilder.SetFlags(AudioFlags.LowLatency); } if (Build.VERSION.SdkInt >= BuildVersionCodes.O) { AudioTrack.Builder trackBuilder = new AudioTrack.Builder() .SetAudioFormat(format) .SetAudioAttributes(attributesBuilder.Build()) .SetTransferMode(AudioTrackMode.Stream) .SetBufferSizeInBytes(bufferSize); trackBuilder.SetPerformanceMode(AudioTrackPerformanceMode.LowLatency); audioTrack = trackBuilder.Build(); } else { audioTrack = new AudioTrack(attributesBuilder.Build(), format, bufferSize, AudioTrackMode.Stream, AudioManager.AudioSessionIdGenerate); } return(audioTrack); }
public StreamingSound(StreamingSource streamingSource, float volume = 1f, float pitch = 1f, float pan = 0f, bool isLooped = false, bool disposeOnStop = false, float bufferDuration = 0.3f) { VerifyStreamingSource(streamingSource); m_bufferDuration = MathUtils.Clamp(bufferDuration, 0f, 10f); ChannelOut channelConfig = (streamingSource.ChannelsCount == 1) ? ChannelOut.FrontLeft : ChannelOut.Stereo; int minBufferSize = AudioTrack.GetMinBufferSize(streamingSource.SamplingFrequency, channelConfig, Encoding.Pcm16bit); int bufferSizeInBytes = MathUtils.Max(CalculateBufferSize(m_bufferDuration), minBufferSize); m_audioTrack = new AudioTrack(Stream.Music, streamingSource.SamplingFrequency, channelConfig, Encoding.Pcm16bit, bufferSizeInBytes, AudioTrackMode.Stream); //m_audioTrack = new AudioTrack(new AudioAttributes.Builder().SetUsage(AudioUsageKind.Media).SetContentType(AudioContentType.Music).Build(), new AudioFormat(), bufferSizeInBytes, AudioTrackMode.Static, 0); Mixer.m_audioTracksCreated++; if (m_audioTrack.State == AudioTrackState.Uninitialized) { m_audioTrack.Release(); m_audioTrack = null; Mixer.m_audioTracksDestroyed++; Log.Warning("Failed to create StreamingSound AudioTrack. Created={0}, Destroyed={1}", Mixer.m_audioTracksCreated, Mixer.m_audioTracksDestroyed); } StreamingSource = streamingSource; base.ChannelsCount = streamingSource.ChannelsCount; base.SamplingFrequency = streamingSource.SamplingFrequency; base.Volume = volume; base.Pitch = pitch; base.Pan = pan; base.IsLooped = isLooped; base.DisposeOnStop = disposeOnStop; if (m_audioTrack != null) { m_task = Task.Run(delegate { try { StreamingThreadFunction(); } catch (Exception message) { Log.Error(message); } }); } }
/// <summary> /// Replays recorded audio by microphone. /// </summary> /// <param name="UIDispatcher">UIDispatcher needed for UWP platform.</param> public async void ReplayRecording(CoreDispatcher UIDispatcher) { #region UWP #if NETFX_CORE // Do nothign without buffer if (buffer == null) { return; } MediaElement playback = new MediaElement(); IRandomAccessStream audioBuffer; lock (bufferLock) { audioBuffer = buffer.CloneStream(); } if (audioBuffer == null) { throw new ArgumentNullException("buffer"); } // Replay async await UIDispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { playback.SetSource(audioBuffer, ""); playback.Play(); }); #endif #endregion #region ANDROID #if __ANDROID__ // Setup AudioTrack ChannelOut channels = Parameters.Channels == 1 ? ChannelOut.Mono : ChannelOut.Stereo; AudioTrack audioTrack = new AudioTrack.Builder() .SetAudioAttributes(new AudioAttributes.Builder() .SetUsage(AudioUsageKind.Media) .SetContentType(AudioContentType.Music) .Build()) .SetAudioFormat(new AudioFormat.Builder() .SetEncoding(Encoding.Pcm16bit) .SetSampleRate((int)Parameters.SamplingRate) .SetChannelMask(channels) .Build()) .SetBufferSizeInBytes(buffer.Length) .Build(); int totalBytesReplayed = 0; // Replay audio in lock until whole buffer is replayed lock (bufferLock) { audioTrack.Play(); while (totalBytesReplayed < bufferLimit) { try { totalBytesReplayed = audioTrack.Write(buffer, 0, bufferLimit); System.Diagnostics.Debug.WriteLine($"Read: {totalBytesReplayed}"); if (totalBytesReplayed < 0) { throw new Exception(String.Format("Exception code: {0}", totalBytesReplayed)); } } catch (Exception e) { // Invalidate audio buffer buffer = null; break; } } } #endif #endregion }