public unsafe WavePlayer(int deviceIndex, double sampleRate, int framesPerBuffer, AudioBufferNeededDelegate bufferNeededDelegate) { Console.WriteLine("WavePlayer started, samplerate=" + sampleRate.ToString() + ", frameCount=" + framesPerBuffer.ToString()); this._bufferNeeded = bufferNeededDelegate; PaStreamParameters paStreamParameters = new PaStreamParameters { device = deviceIndex, channelCount = 2, suggestedLatency = 0.0, sampleFormat = PaSampleFormat.PaFloat32 }; PaError paError = PortAudioAPI.Pa_IsFormatSupported(IntPtr.Zero, ref paStreamParameters, sampleRate); if (paError != 0) { throw new ApplicationException("Init audio output device: " + paError.ToString()); } this._gcHandle = GCHandle.Alloc(this); paError = PortAudioAPI.Pa_OpenStream(out this._streamHandle, IntPtr.Zero, ref paStreamParameters, sampleRate, (uint)framesPerBuffer, PaStreamFlags.PaNoFlag, this._paCallback, (IntPtr)this._gcHandle); if (paError != 0) { this._gcHandle.Free(); throw new ApplicationException("Open audio output device: " + paError.ToString()); } paError = PortAudioAPI.Pa_StartStream(this._streamHandle); if (paError == PaError.paNoError) { return; } PortAudioAPI.Pa_CloseStream(this._streamHandle); this._gcHandle.Free(); throw new ApplicationException("Start audio output device: " + paError.ToString()); }
/// <summary> /// Determine if the device will support a given PCM format /// </summary> /// <param name="sampleFormat">The data format for PCM samples</param> /// <param name="channels">The number of channels</param> /// <param name="sampleRate">The number of frames/second the device will render/capture</param> /// <param name="suggestedLatency">The latency the device will attempt to match</param> /// <param name="asOutput">Marks if the device should be opened as an input or an output</param> /// <returns>True if the device supports this format, false otherwise</returns> public unsafe bool SupportsFormat(PortAudioSampleFormat sampleFormat, int channels, double sampleRate, TimeSpan suggestedLatency, bool asOutput) { PaStreamParameters *inputParams = default; PaStreamParameters *outputParams = default; var param = new PaStreamParameters { DeviceIndex = DeviceIndex, ChannelCount = channels, HostApiSpecificStreamInfo = IntPtr.Zero, SampleFormats = sampleFormat.SampleFormat, SuggestedLatency = new PaTime(suggestedLatency) }; if (asOutput) { outputParams = ¶m; } else { inputParams = ¶m; } return(Native.PortAudio.Pa_IsFormatSupported(inputParams, outputParams, sampleRate) >= PaErrorCode.NoError); }
public unsafe WaveDuplex(int deviceIndex, double sampleRate, int framesPerBuffer, AudioBufferAvailableDelegate bufferNeededDelegate) { this._bufferAvailable = bufferNeededDelegate; PaStreamParameters paStreamParameters = new PaStreamParameters { device = deviceIndex, channelCount = 2, suggestedLatency = 0.0, sampleFormat = PaSampleFormat.PaFloat32 }; PaError paError = PortAudioAPI.Pa_IsFormatSupported(ref paStreamParameters, ref paStreamParameters, sampleRate); if (paError != 0) { throw new ApplicationException(paError.ToString()); } this._gcHandle = GCHandle.Alloc(this); paError = PortAudioAPI.Pa_OpenStream(out this._streamHandle, ref paStreamParameters, ref paStreamParameters, sampleRate, (uint)framesPerBuffer, PaStreamFlags.PaNoFlag, this._paCallback, (IntPtr)this._gcHandle); if (paError != 0) { this._gcHandle.Free(); throw new ApplicationException(paError.ToString()); } paError = PortAudioAPI.Pa_StartStream(this._streamHandle); if (paError == PaError.paNoError) { return; } PortAudioAPI.Pa_CloseStream(this._streamHandle); this._gcHandle.Free(); throw new ApplicationException(paError.ToString()); }
public static extern PaError Pa_OpenStream( out IntPtr stream, ref PaStreamParameters inputParameters, IntPtr inPtr, double sampleRate, uint framesPerBuffer, PaStreamFlags streamFlags, PaStreamCallbackDelegate streamCallback, IntPtr userData);
static void Main(string[] args) { PortAudio.Initialize(); //(new SpectrumMeasurement()).Run(); //AppSettings.Current.Save(); //return; AppSettings.Current.Save(); Console.ReadKey(); return; var istreamParameters = new PaStreamParameters() { ChannelCount = 2, Device = PortAudio.Instance.GetDefaultInputDeviceIndex(), SampleFormat = PaSampleFormat.PaFloat32, SuggestedLatency = 0.1 }; var ostreamParameters = new PaStreamParameters() { ChannelCount = 2, Device = PortAudio.Instance.GetDefaultOutputDeviceIndex(), SampleFormat = PaSampleFormat.PaFloat32, SuggestedLatency = 0.1 }; var r = new Random(); var table = new float[96000]; var rec = new List <float>(); var x = 0; for (x = 0; x < 96000; x++) { table[x] = (float)(Math.Sin(x * (2 * Math.PI / 96))); } x = 0; Process.GetCurrentProcess().PriorityBoostEnabled = true; Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.RealTime; int runs = 0; Console.ReadKey(); }
public PortAudioInputStream(PaStreamParameters inputParameters, double sampleRate, uint framesPerBuffer, PaStreamFlags streamFlags, StreamCallback streamCallback, IntPtr userData) : base(inputParameters.sampleFormat, inputParameters.channelCount) { using (var input = Factory.ToNative<PaStreamParameters> (inputParameters)) HandleError (PortAudioInterop.Pa_OpenStream ( out handle, input.Native, IntPtr.Zero, sampleRate, framesPerBuffer, streamFlags, ToPaStreamCallback (streamCallback, false), userData )); }
/// <summary> /// Create a PortAudioDevicePump for an input device /// Note: This MUST be disposed, or you risk breaking audio on the host until the next reboot /// </summary> /// <param name="device">The input device to create a pump for</param> /// <param name="channelCount">The number of channels to capture from the input device</param> /// <param name="sampleFormat">The sample format of the output PCM data</param> /// <param name="suggestedLatency">The latency the device will attempt to achieve</param> /// <param name="sampleRate">The sample rate of the output PCM data</param> /// <param name="callback">The callback that will be invoked when data is produced</param> /// <exception cref="ArgumentNullException">Thrown in the case that the device or callback are null</exception> public unsafe PortAudioDevicePump(PortAudioDevice device, int channelCount, PortAudioSampleFormat sampleFormat, TimeSpan suggestedLatency, double sampleRate, WriteDataCallback callback) { if (device == null) { throw new ArgumentNullException(nameof(device)); } if (callback == null) { throw new ArgumentNullException(nameof(callback)); } PortAudioLifetimeRegistry.Register(this); SampleFormat = sampleFormat; Channels = channelCount; SampleRate = sampleRate; SuggestedLatency = suggestedLatency; _handle = GCHandle.Alloc(this); _isOutput = false; _writeDataCallback = callback; var inputParams = new PaStreamParameters { ChannelCount = channelCount, DeviceIndex = device.DeviceIndex, HostApiSpecificStreamInfo = IntPtr.Zero, SampleFormats = sampleFormat.SampleFormat, SuggestedLatency = new PaTime(suggestedLatency) }; var err = Native.PortAudio.Pa_OpenStream(out _stream, &inputParams, null, sampleRate, FRAMES_TO_BUFFER, PaStreamFlags.NoFlag, StreamCallback, GCHandle.ToIntPtr(_handle)); if (err < PaErrorCode.NoError) { throw PortAudioException.GetException(err); } err = Native.PortAudio.Pa_SetStreamFinishedCallback(_stream, StreamFinishedCallback); if (err < PaErrorCode.NoError) { throw PortAudioException.GetException(err); } }
public WavePlayer(int deviceIndex, double sampleRate, int framesPerBuffer, AudioBufferNeededDelegate bufferNeededDelegate) { _bufferNeeded = bufferNeededDelegate; var ouputParams = new PaStreamParameters(); ouputParams.device = deviceIndex; ouputParams.channelCount = 2; ouputParams.suggestedLatency = 0; ouputParams.sampleFormat = PaSampleFormat.PaFloat32; var pe = PortAudioAPI.Pa_IsFormatSupported(IntPtr.Zero, ref ouputParams, sampleRate); if (pe != PaError.paNoError) { throw new ApplicationException(pe.ToString()); } _gcHandle = GCHandle.Alloc(this); pe = PortAudioAPI.Pa_OpenStream( out _streamHandle, IntPtr.Zero, ref ouputParams, sampleRate, (uint)framesPerBuffer, PaStreamFlags.PaNoFlag, _paCallback, (IntPtr)_gcHandle); if (pe != PaError.paNoError) { _gcHandle.Free(); throw new ApplicationException(pe.ToString()); } pe = PortAudioAPI.Pa_StartStream(_streamHandle); if (pe != PaError.paNoError) { PortAudioAPI.Pa_CloseStream(_streamHandle); _gcHandle.Free(); throw new ApplicationException(pe.ToString()); } }
static void Main(string[] args) { Console.WriteLine(); Console.WriteLine($"Using PortAudio version:\n {PaLibrary.VersionInfo.versionText}"); Console.WriteLine(); using (var paLibrary = PaLibrary.Initialize()) { PrintDevices(paLibrary); double sampleRate = 44100; var outIndex = ChooseDevice(paLibrary); var outputParameters = new PaStreamParameters() { device = outIndex, channelCount = 1, sampleFormat = PaSampleFormat.paFloat32, suggestedLatency = paLibrary.GetDeviceInfo(outIndex).Value.defaultHighOutputLatency, hostApiSpecificStreamInfo = IntPtr.Zero }; var callbackData = new SineCallbackData() { osc = new Complex(1, 0), delta = Complex.Exp(new Complex(0, 440 * 2 * Math.PI / sampleRate)) }; using (var stream = paLibrary.OpenStream( null, outputParameters, sampleRate, 512, PaStreamFlags.paNoFlag, SineCallback, callbackData)) { stream.SetStreamFinishedCallback(PrintDoneCallback, "stream finished"); stream.StartStream(); Console.WriteLine("Press any key to stop..."); Console.ReadKey(); stream.StopStream(); } } }
public void start() { var device = paLibrary.DefaultOutputDevice; var outputParameters = new PaStreamParameters() { device = device, channelCount = 1, sampleFormat = PaSampleFormat.paFloat32, suggestedLatency = paLibrary.GetDeviceInfo(device).Value.defaultLowOutputLatency, hostApiSpecificStreamInfo = IntPtr.Zero }; osc = 0; stream = paLibrary.OpenStream( null, outputParameters, SampleRate, 512, PaStreamFlags.paNoFlag, SineCallback, IntPtr.Zero); stream.StartStream(); }
public PortAudioOutputStream(PaStreamParameters outputParameters, double sampleRate, uint framesPerBuffer, PaStreamFlags streamFlags, StreamCallback streamCallback, object userData) : base(outputParameters.sampleFormat, outputParameters.channelCount) { var gch = userData == null ? default (GCHandle) : GCHandle.Alloc (userData, GCHandleType.Pinned); try { using (var output = Factory.ToNative<PaStreamParameters> (outputParameters)) HandleError (PortAudioInterop.Pa_OpenStream ( out handle, IntPtr.Zero, output.Native, sampleRate, framesPerBuffer, streamFlags, ToPaStreamCallback (streamCallback, true), userData != null ? gch.AddrOfPinnedObject () : IntPtr.Zero)); } finally { if (userData != null) gch.Free (); } }
public AudioPlayer(int deviceIndex, double sampleRate, uint framesPerBuffer, SamplesAvailableEvent samplesAvailableCallback) { _bufferNeeded = samplesAvailableCallback; PaStreamParameters ouputParams = new PaStreamParameters(); ouputParams.device = deviceIndex; ouputParams.channelCount = 2; ouputParams.suggestedLatency = 0; ouputParams.sampleFormat = PaSampleFormat.paFloat32; PaError paErr = Pa_IsFormatSupported(IntPtr.Zero, ref ouputParams, sampleRate); if (paErr != PaError.paNoError) { throw new ApplicationException(paErr.ToString()); } _gcHandle = GCHandle.Alloc(this); paErr = Pa_OpenStream(out _streamHandle, IntPtr.Zero, ref ouputParams, sampleRate, framesPerBuffer, PaStreamFlags.paNoFlag, _paCallback, (IntPtr)_gcHandle); if (paErr != PaError.paNoError) { _gcHandle.Free(); throw new ApplicationException(paErr.ToString()); } paErr = Pa_StartStream(_streamHandle); if (paErr != PaError.paNoError) { Pa_CloseStream(_streamHandle); _gcHandle.Free(); throw new ApplicationException(paErr.ToString()); } }
protected override void StartDevices() { if (stream != null) { if (stream.IsActive()) { stream.Abort(); } stream.Dispose(); } /* TODO: Restore device settings */ var inputStreamParameters = new PaStreamParameters() { ChannelCount = AppSettings.Current.Device.InputDevice.ChannelsCount, Device = AppSettings.Current.Device.InputDevice.Index, SampleFormat = ToPortAudioSampleFormat(AppSettings.Current.Device.InputDevice.SampleFormat), SuggestedLatency = AppSettings.Current.Device.InputDevice.LatencyMilliseconds / 1000.0 }; var outputStreamParameters = new PaStreamParameters() { ChannelCount = AppSettings.Current.Device.OutputDevice.ChannelsCount, Device = AppSettings.Current.Device.OutputDevice.Index, SampleFormat = ToPortAudioSampleFormat(AppSettings.Current.Device.OutputDevice.SampleFormat), SuggestedLatency = AppSettings.Current.Device.OutputDevice.LatencyMilliseconds / 1000.0 }; stream = new PortAudioStream(inputStreamParameters, outputStreamParameters, AppSettings.Current.Device.SampleRate, 0, 0x00000002); stream.OnRead += OnRead; stream.OnWrite += OnWrite; stream.OnError += OnError; stream.Start(); }
public static extern PaError Pa_IsFormatSupported( ref PaStreamParameters inputParameters, ref PaStreamParameters outputParameters, double sampleRate);
unsafe public static extern PaError PA_OpenStream ( out void *stream, PaStreamParameters *inputParameters, PaStreamParameters *outputParameters, double sampleRate, uint framesPerBuffer, PaStreamFlags streamFlags, PaStreamCallback streamCallback, int callback_id); // 0 for callback1, else callback2
unsafe public static extern PaError PA_IsFormatSupported( PaStreamParameters *inputParameters, PaStreamParameters *outputParameters, double sampleRate);
private static IEnumerable <DeviceInfo> EnumerateDevices(bool enumerateInputDevices) { var result = new List <DeviceInfo>(); var streamParameters = new PaStreamParameters(); var devices = enumerateInputDevices ? deviceCache.Value.Where(device => device.Info.MaxInputChannels > 0) : deviceCache.Value.Where(device => device.Info.MaxOutputChannels > 0); var sampleFormats = ((SampleFormat[])Enum.GetValues(typeof(SampleFormat))) .Select(value => new { SampleFormat = value, PaSampleFormat = ToPortAudioSampleFormat(value) }) .ToList(); foreach (var device in devices) { streamParameters.Device = device.Index; foreach (var sampleFormat in sampleFormats) { streamParameters.SampleFormat = sampleFormat.PaSampleFormat; foreach (var sampleRate in AppSettings.Current.Device.DefaultSampleRates) { var maxChannels = enumerateInputDevices ? device.Info.MaxInputChannels : device.Info.MaxOutputChannels; int channelCount; for (channelCount = 1; channelCount < maxChannels + 1; channelCount++) { streamParameters.ChannelCount = channelCount; var isFormatSupported = enumerateInputDevices ? PortAudio.Instance.IsFormatSupported(streamParameters, null, sampleRate) : PortAudio.Instance.IsFormatSupported(null, streamParameters, sampleRate); if (!isFormatSupported) { break; } } if (channelCount - 1 > 0) { result.Add(new DeviceInfo() { Index = device.Index, ApiName = GetApiName(device.Info.HostApi), Name = device.Info.Name, ChannelsCount = channelCount - 1, SampleFormat = sampleFormat.SampleFormat, SampleRate = (int)sampleRate, LatencyMilliseconds = (int)(1000.0 * (enumerateInputDevices ? device.Info.DefaultHighInputLatency : device.Info.DefaultHighOutputLatency)) }); } } } } return(result); }
public static extern PaError Pa_IsFormatSupported( IntPtr inputParameters, // Not Used ref PaStreamParameters outputParameters, double sampleRate);
public static unsafe extern PaError PA_OpenStream( out void* stream, PaStreamParameters* inputParameters, PaStreamParameters* outputParameters, double sampleRate, uint framesPerBuffer, PaStreamFlags streamFlags, PaStreamCallback streamCallback, int user_data, int callback_id);
/// <summary> /// Create a PortAudioDevicePump for an output device /// Note: This MUST be disposed, or you risk breaking audio on the host until the next reboot /// </summary> /// <param name="device">The output device to create a pump for</param> /// <param name="channelCount">The number of channels in the input PCM data</param> /// <param name="sampleFormat">The sample format of the input PCM data</param> /// <param name="suggestedLatency">The latency the device will attempt to achieve</param> /// <param name="sampleRate">The sample rate of playback</param> /// <param name="callback">The callback that will supply data to the output device</param> /// <exception cref="ArgumentNullException">Thrown in the case that the device or callback are null</exception> public unsafe PortAudioDevicePump(PortAudioDevice device, int channelCount, PortAudioSampleFormat sampleFormat, TimeSpan suggestedLatency, double sampleRate, ReadDataCallback callback) { if (device == null) { throw new ArgumentNullException(nameof(device)); } if (callback == null) { throw new ArgumentNullException(nameof(callback)); } PortAudioLifetimeRegistry.Register(this); SampleFormat = sampleFormat; Channels = channelCount; SampleRate = sampleRate; SuggestedLatency = suggestedLatency; _handle = GCHandle.Alloc(this); _isOutput = true; _readDataCallback = callback; var outputParams = new PaStreamParameters { ChannelCount = channelCount, DeviceIndex = device.DeviceIndex, HostApiSpecificStreamInfo = IntPtr.Zero, SampleFormats = sampleFormat.SampleFormat, SuggestedLatency = new PaTime(suggestedLatency) }; var err = Native.PortAudio.Pa_OpenStream(out _stream, null, &outputParams, sampleRate, FRAMES_TO_BUFFER, PaStreamFlags.NoFlag, StreamCallback, GCHandle.ToIntPtr(_handle)); if (err < PaErrorCode.NoError) { throw PortAudioException.GetException(err); } err = Native.PortAudio.Pa_SetStreamFinishedCallback(_stream, StreamFinishedCallback); if (err < PaErrorCode.NoError) { throw PortAudioException.GetException(err); } _dataQueue = new ConcurrentQueue <BufferContainer>(); _bufferPool = new ConcurrentBag <BufferContainer>(); for (var i = 0; i < BUFFER_CHAIN_LENGTH; i++) { var buffer = new byte[FRAMES_TO_BUFFER * (ulong)channelCount * (ulong)sampleFormat.FormatSize]; var readLength = WriteAudioFrame(buffer, buffer.Length); _dataQueue.Enqueue(new BufferContainer(buffer) { ReadLength = readLength }); } _queueCount = new SemaphoreSlim(BUFFER_CHAIN_LENGTH); _poolCount = new SemaphoreSlim(0); _threadEndEvent = new ManualResetEventSlim(false); _processingThreadCancel = new CancellationTokenSource(); Task.Run(() => DataTask(_processingThreadCancel.Token)); }
public static PaErrorCode CheckIfFormatSupported(PaStreamParameters inputParameters, PaStreamParameters outputParameters, double sampleRate) { using (var input = Factory.ToNative<PaStreamParameters> (inputParameters)) using (var output = Factory.ToNative<PaStreamParameters> (outputParameters)) return PortAudioInterop.Pa_IsFormatSupported (input.Native, output.Native, sampleRate); }