private IntPtr streamOpen(int inputDevice, int inputChannels, int outputDevice, int outputChannels, int sampleRate, uint framesPerBuffer) { IntPtr stream = new IntPtr(); IntPtr data = new IntPtr(0); PortAudio.PaStreamParameters inputParams = new PortAudio.PaStreamParameters(); inputParams.channelCount = inputChannels; inputParams.device = inputDevice; inputParams.sampleFormat = PortAudio.PaSampleFormat.paInt16; inputParams.suggestedLatency = 0.0; PortAudio.PaStreamParameters outputParams = new PortAudio.PaStreamParameters(); outputParams.channelCount = outputChannels; outputParams.device = outputDevice; outputParams.sampleFormat = PortAudio.PaSampleFormat.paInt16; outputParams.suggestedLatency = 0.0; errorCheck("OpenDefaultStream", PortAudio.Pa_OpenStream( out stream, ref inputParams, ref outputParams, sampleRate, framesPerBuffer, PortAudio.PaStreamFlags.paNoFlag, this.paStreamCallback, data)); return(stream); }
public void Record() { IntPtr userdata = IntPtr.Zero; //intptr.zero is essentially just a null pointer callbackDelegate = new PortAudio.PaStreamCallbackDelegate(myPaStreamCallback); PortAudio.Pa_Initialize(); PortAudio.PaStreamParameters outputparams = new PortAudio.PaStreamParameters(); outputparams.channelCount = 1; outputparams.sampleFormat = PortAudio.PaSampleFormat.paInt16; outputparams.device = PortAudio.Pa_GetDefaultInputDevice(); outputparams.suggestedLatency = PortAudio.Pa_GetDeviceInfo(outputparams.device).defaultLowInputLatency; outputparams.hostApiSpecificStreamInfo = IntPtr.Zero; PortAudio.PaStreamParameters a = new PortAudio.PaStreamParameters(); //uninteresting output params cause i cant give it null a.channelCount = 1; a.sampleFormat = PortAudio.PaSampleFormat.paInt16; a.device = PortAudio.Pa_GetDefaultOutputDevice(); a.suggestedLatency = PortAudio.Pa_GetDeviceInfo(a.device).defaultLowOutputLatency; a.hostApiSpecificStreamInfo = IntPtr.Zero; PortAudio.PaError error = PortAudio.Pa_OpenStream(out stream, ref outputparams, ref a, this.sampleRate, (uint)NUM_SAMPLES, PortAudio.PaStreamFlags.paClipOff, callbackDelegate, IntPtr.Zero); this.isRecording = true; PortAudio.Pa_StartStream(stream); Thread myThread = new Thread(new ThreadStart(record_loop)); myThread.Start(); }
private void GetChannelNames(RealtimeHostConfig config) { if (config == null) { InputNames = new string[0]; OutputNames = new string[0]; return; } var inputDeviceInfo = PortAudio.Pa_GetDeviceInfo(config.InputDeviceID); var outputDeviceInfo = PortAudio.Pa_GetDeviceInfo(config.OutputDeviceID); InputNames = Enumerable.Range(0, inputDeviceInfo.maxInputChannels) .Select(ch => { string chName = null; PortAudio.PaAsio_GetInputChannelName((PortAudio.PaDeviceIndex)config.InputDeviceID, ch, ref chName); return((ch + 1) + ": " + chName); }) .ToArray(); OutputNames = Enumerable.Range(0, outputDeviceInfo.maxOutputChannels) .Select(ch => { string chName = null; PortAudio.PaAsio_GetOutputChannelName((PortAudio.PaDeviceIndex)config.OutputDeviceID, ch, ref chName); return((ch + 1) + ": " + chName); }) .ToArray(); }
private static void Main(string[] args) { Console.WriteLine("PortAudioSharp Test"); Console.WriteLine("*******************"); Console.WriteLine(); Console.WriteLine("PortAudioSharpTest version: " + Assembly.GetExecutingAssembly().GetName().Version.ToString()); Console.WriteLine("PortAudioSharp version: " + Assembly.GetAssembly(typeof(PortAudio)).GetName().Version.ToString()); Console.WriteLine("PortAudio version: " + PortAudio.Pa_GetVersionText() + " (" + PortAudio.Pa_GetVersion() + ")"); Console.WriteLine(); try { PortAudio.Pa_Initialize(); Application.EnableVisualStyles(); XmlDocument doc = new XmlDocument(); XmlElement elem = doc.CreateElement("Config"); elem.AppendChild(doc.CreateTextNode("ciao")); doc.AppendChild(elem); ApiHostSelectionForm apiHostSelectionForm = new ApiHostSelectionForm(); // apiHostSelectionForm.ApiHostConfigElement = elem; apiHostSelectionForm.ShowDialog(); } catch (Exception e) { Console.Error.WriteLine(e); Console.Read(); } finally { PortAudio.Pa_Terminate(); } }
private void _Dispose(bool disposing) { if (_Disposed) { return; } if (!disposing) { CLog.LogDebug("Did not close CPortAudioHandle"); } //Make sure we do not leek any streams as we may keep PA open if (_Streams.Count > 0) { CLog.LogDebug("Did not close " + _Streams.Count + "PortAudio-Stream(s)"); while (_Streams.Count > 0) { CloseStream(_Streams[0]); } } lock (_Mutex) { Debug.Assert(_RefCount > 0); _RefCount--; if (_RefCount == 0) { PortAudio.Pa_Terminate(); } } _Disposed = true; }
void ASIODeviceControlLoad(object sender, EventArgs e) { int deviceCount = PortAudio.Pa_GetDeviceCount(); Console.WriteLine("Device count: " + paHostApiInfo.deviceCount + " default input device: " + paHostApiInfo.defaultInputDevice); deviceComboBox.Items.Clear(); for (int i = 0; i < deviceCount; i++) { PortAudio.PaDeviceInfo paDeviceInfo = PortAudio.Pa_GetDeviceInfo(i); PortAudio.PaHostApiInfo paHostApi = PortAudio.Pa_GetHostApiInfo(paDeviceInfo.hostApi); if (paHostApi.type == PortAudio.PaHostApiTypeId.paASIO) { Console.WriteLine("\n#" + i + "\n" + paDeviceInfo); if (paDeviceInfo.maxOutputChannels > 0) { deviceComboBox.Items.Add(new DeviceItem(i, paDeviceInfo)); if (i == paHostApiInfo.defaultOutputDevice) { deviceComboBox.SelectedIndex = deviceComboBox.Items.Count - 1; } } } } bufferSizeComboBox.Items.Clear(); int bufferSize = 256; while (bufferSize < 44100 / 2) { bufferSizeComboBox.Items.Add(bufferSize); bufferSize *= 2; } bufferSizeComboBox.SelectedIndex = 2; }
public PortAudioPlayer(int channels, int frequency, uint framesPerBuffer, PortAudio.PaStreamCallbackDelegate paStreamCallback) { log("Initializing..."); this.channels = channels; this.frequency = frequency; this.framesPerBuffer = framesPerBuffer; this.paStreamCallback = paStreamCallback; if (errorCheck("Initialize", PortAudio.Pa_Initialize())) { this.disposed = true; // if Pa_Initialize() returns an error code, // Pa_Terminate() should NOT be called. throw new Exception("Can't initialize audio"); } int apiCount = PortAudio.Pa_GetHostApiCount(); for (int i = 0; i < apiCount; i++) { PortAudio.PaHostApiInfo availableApiInfo = PortAudio.Pa_GetHostApiInfo(i); log("available API index: " + i + "\n" + availableApiInfo.ToString()); } this.hostApi = apiSelect(); log("selected Host API: " + this.hostApi); this.apiInfo = PortAudio.Pa_GetHostApiInfo(this.hostApi); this.inputDeviceInfo = PortAudio.Pa_GetDeviceInfo(apiInfo.defaultInputDevice); this.outputDeviceInfo = PortAudio.Pa_GetDeviceInfo(apiInfo.defaultOutputDevice); log("input device:\n" + inputDeviceInfo.ToString()); log("output device:\n" + outputDeviceInfo.ToString()); }
private void record_loop() { while (cSamplePos < mSamplePos) { if (stop_flag) { break; } if (sampleQueue.Count > 0) { check_diskspace(); byte[] packet = (byte[])sampleQueue.Dequeue(); SoundPacket p = new SoundPacket(packet); form.Invoke(form.myDelegate, new object[] { p.averageDB }); writer.Write(packet, 0, packet.Length); } } this.isRecording = false; writer.Close(); PortAudio.Pa_StopStream(stream); }
/// <summary> /// Init PortAudio and list record devices /// </summary> /// <returns>true if success</returns> public bool Init() { _Devices = new List <SRecordDevice>(); try { if (_initialized) { CloseAll(); } if (errorCheck("Initialize", PortAudio.Pa_Initialize())) { return(false); } _initialized = true; int hostAPI = apiSelect(); int numDevices = PortAudio.Pa_GetDeviceCount(); for (int i = 0; i < numDevices; i++) { PortAudio.PaDeviceInfo info = PortAudio.Pa_GetDeviceInfo(i); if (info.hostApi == hostAPI && info.maxInputChannels > 0) { SRecordDevice dev = new SRecordDevice(); dev.ID = i; dev.Name = info.name; dev.Driver = info.name + i.ToString(); dev.Inputs = new List <SInput>(); SInput inp = new SInput(); inp.Name = "Default"; inp.Channels = info.maxInputChannels; if (inp.Channels > 2) { inp.Channels = 2; //more are not supported in vocaluxe } dev.Inputs.Add(inp); _Devices.Add(dev); } } _recHandle = new IntPtr[_Devices.Count]; _myRecProc = new PortAudio.PaStreamCallbackDelegate(myPaStreamCallback); _DeviceConfig = _Devices.ToArray(); } catch (Exception e) { _initialized = false; CLog.LogError("Error initializing PortAudio: " + e.Message); return(false); } return(true); }
// Shutdown audio engine public static void Shutdown() { PortAudio.Pa_StopStream(stream); PortAudio.Pa_CloseStream(stream); PortAudio.Pa_Terminate(); }
private void DoFree() { if (_Initialized) { Stop(); PortAudio.Pa_Terminate(); } _Closeproc(_StreamID); }
/// <summary> /// Stop all voice capturing streams and terminate PortAudio /// </summary> public void CloseAll() { Stop(); if (_initialized) { PortAudio.Pa_Terminate(); _initialized = false; } //System.IO.File.WriteAllBytes("test0.raw", _Buffer[0].Buffer); }
public MMEDeviceControl(PortAudio.PaHostApiInfo paHostApiInfo) { // // The InitializeComponent() call is required for Windows Forms designer support. // InitializeComponent(); // // TODO: Add constructor code after the InitializeComponent() call. // this.paHostApiInfo = paHostApiInfo; }
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 void CloseStream(IntPtr stream) { if (_Disposed) { throw new ObjectDisposedException("PortAudioHandle already disposed"); } lock (_Mutex) { PortAudio.Pa_CloseStream(stream); _Streams.Remove(stream); } }
/// <summary> /// Stop Voice Capturing /// </summary> /// <returns></returns> public bool Stop() { if (!_initialized) { return(false); } for (int i = 0; i < _recHandle.Length; i++) { PortAudio.Pa_StopStream(_recHandle[i]); } return(true); }
/// <summary> /// Initializes PortAudio library (if required) /// </summary> public CPortAudioHandle() { lock (_Mutex) { if (_RefCount == 0) { if (CheckError("Initialize", PortAudio.Pa_Initialize())) { throw new Exception(); } } _RefCount++; } }
/* * private void streamWrite(IntPtr stream, float[] buffer) { * errorCheck("WriteStream",PortAudio.Pa_WriteStream( * stream,buffer,(uint)(buffer.Length/2))); * } */ private void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { // Dispose here any managed resources } // Dispose here any unmanaged resources log("Terminating..."); errorCheck("Terminate", PortAudio.Pa_Terminate()); } this.disposed = true; }
public HostApiItem(PortAudio.PaHostApiInfo hostApiInfo) { this.hostApiInfo = hostApiInfo; switch(hostApiInfo.type) { case PortAudio.PaHostApiTypeId.paMME: hostApiDeviceControl = new MMEDeviceControl(hostApiInfo); break; case PortAudio.PaHostApiTypeId.paDirectSound: hostApiDeviceControl = new DirectSoundDeviceControl(hostApiInfo); break; case PortAudio.PaHostApiTypeId.paASIO: hostApiDeviceControl = new ASIODeviceControl(hostApiInfo); break; } }
private void AudioSetup() { StopAudioEngine(); lock (globalLock) { try { // this is done because the devices and Ids go a bit t**s when you re-initialize... string serialized = null; if (realtimeConfig != null) { serialized = realtimeConfig.Serialize(); } PortAudio.Pa_Terminate(); PortAudio.Pa_Initialize(); RealtimeHostConfig deserialized = null; if (serialized != null) { deserialized = RealtimeHostConfig.Deserialize(serialized); } // Use the graphical editor to create a new config var config = RealtimeHostConfig.CreateConfig(deserialized); if (config != null) { realtimeConfig = config; } } catch (InvalidFormatException ex) { Logging.ShowMessage(ex.Message, LogType.Warning); } catch (Exception) { realtimeConfig = RealtimeHostConfig.CreateConfig(); } GetChannelNames(realtimeConfig); NotifyPropertyChanged(nameof(SamplerateWarning)); SaveSettings(); } UpdateMemoryMap(); StartAudioEngine(); }
public static void Main(string[] args) { Console.WriteLine("PortAudioSharp Test"); Console.WriteLine("*******************"); Console.WriteLine(); Console.WriteLine("PortAudioSharpTest version: " + Assembly.GetExecutingAssembly().GetName().Version.ToString()); Console.WriteLine("PortAudioSharp version: " + Assembly.GetAssembly(typeof(PortAudio)).GetName().Version.ToString()); Console.WriteLine("PortAudio version: " + PortAudio.Pa_GetVersionText() + " (" + PortAudio.Pa_GetVersion() + ")"); Console.WriteLine(); new PortAudioTest().Run(); }
private int apiSelect() { int selectedHostApi = PortAudio.Pa_GetDefaultHostApi(); int apiCount = PortAudio.Pa_GetHostApiCount(); for (int i = 0; i < apiCount; i++) { PortAudio.PaHostApiInfo apiInfo = PortAudio.Pa_GetHostApiInfo(i); if ((apiInfo.type == PortAudio.PaHostApiTypeId.paDirectSound) || (apiInfo.type == PortAudio.PaHostApiTypeId.paOSS)) { selectedHostApi = i; } } return(selectedHostApi); }
private bool errorCheck(String action, PortAudio.PaError errorCode) { if (errorCode != PortAudio.PaError.paNoError) { CLog.LogError(action + " error: " + PortAudio.Pa_GetErrorText(errorCode)); if (errorCode == PortAudio.PaError.paUnanticipatedHostError) { PortAudio.PaHostErrorInfo errorInfo = PortAudio.Pa_GetLastHostErrorInfo(); CLog.LogError("- Host error API type: " + errorInfo.hostApiType); CLog.LogError("- Host error code: " + errorInfo.errorCode); CLog.LogError("- Host error text: " + errorInfo.errorText); } return(true); } return(false); }
private void play_loop() { while (reader.Position < reader.Length) { if (stop_flag) { break; } if (pause_flag) { continue; //just wait for it to be unpaused } //This is essentially working as a circular/FIFO buffer, where new sample packets are only added to the queue //if there's room in the queue. Once the packet is read out of the queue in the callback function it's //removed from the queue and there is room to add more info to the queue if (sampleQueue.Count < QUEUE_LENGTH) { //Console.WriteLine("Writing"); byte[] buffer = new byte[NUM_SAMPLES]; //buffer to read the wav raw bytes into int bytesRead = reader.Read(buffer, 0, NUM_SAMPLES); //read a block of bytes out from the wav cSamplePos += bytesRead; SoundPacket packet = new SoundPacket(buffer); sampleQueue.Enqueue(packet); //send the buffer to the queue } } this.stop_flag = true; while (PortAudio.Pa_IsStreamActive(stream) != 0) { } PortAudio.Pa_StopStream(stream); this.isPlaying = false; cSamplePos = 0; this.stop_flag = false; }
public PortAudio.PaError OpenStream(out IntPtr stream, ref PortAudio.PaStreamParameters?inputParameters, ref PortAudio.PaStreamParameters?outputParameters, double sampleRate, uint framesPerBuffer, PortAudio.PaStreamFlags streamFlags, PortAudio.PaStreamCallbackDelegate streamCallback, IntPtr userData) { lock (_Mutex) { if (_Disposed) { throw new ObjectDisposedException("PortAudioHandle already disposed"); } PortAudio.PaError res = PortAudio.Pa_OpenStream(out stream, ref inputParameters, ref outputParameters, sampleRate, framesPerBuffer, streamFlags, streamCallback, userData); if (res == PortAudio.PaError.paNoError) { _Streams.Add(stream); } return(res); } }
public void CloseStream(IntPtr stream) { lock (_Mutex) { if (_Disposed) { throw new ObjectDisposedException("PortAudioHandle already disposed"); } try { PortAudio.Pa_CloseStream(stream); } catch (Exception ex) { CLog.LogError(errorText: $"Error closing stream: {ex.Message}", e: ex); } _Streams.Remove(stream); } }
public static void Main() { Application.EnableVisualStyles(); Application.Run(new Form2()); Application.Run(new Form1()); Console.WriteLine("PortAudioSharp Test"); Console.WriteLine("*******************"); Console.WriteLine(); Console.WriteLine("PortAudioSharpTest version: " + Assembly.GetExecutingAssembly().GetName().Version.ToString()); Console.WriteLine("PortAudioSharp version: " + Assembly.GetAssembly(typeof(PortAudio)).GetName().Version.ToString()); Console.WriteLine("PortAudio version: " + PortAudio.Pa_GetVersionText() + " (" + PortAudio.Pa_GetVersion() + ")"); Console.WriteLine(); new PortAudioTest().Run(); }
public void Play() { IntPtr userdata = IntPtr.Zero; //intptr.zero is essentially just a null pointer callbackDelegate = new PortAudio.PaStreamCallbackDelegate(myPaStreamCallback); PortAudio.Pa_Initialize(); uint sampleFormat = 0; switch (bitDepth) { case 8: sampleFormat = 16; break; case 16: sampleFormat = 8; break; case 24: sampleFormat = 4; break; case 32: sampleFormat = 2; break; default: Console.WriteLine("broken WAV"); break; } //not sure why framesPerBuffer is so strange. PortAudio.PaError error = PortAudio.Pa_OpenDefaultStream(out stream, inputChannels, outputChannels, sampleFormat, sampleRate / outputChannels, (uint)(NUM_SAMPLES / (frameSize * 2)), callbackDelegate, userdata); PortAudio.Pa_StartStream(stream); Thread myThread = new Thread(new ThreadStart(play_loop)); myThread.Start(); }
private void _Dispose(bool disposing) { if (_Disposed) { return; } if (!disposing) { CLog.LogDebug("Did not close CPortAudioHandle"); } //Make sure we do not leek any streams as we may keep PA open if (_Streams.Count > 0) { CLog.LogDebug("Did not close " + _Streams.Count + "PortAudio-Stream(s)"); while (_Streams.Count > 0) { CloseStream(_Streams[0]); } } lock (_Mutex) { if (_Disposed) { return; } Debug.Assert(_RefCount > 0); _RefCount--; if (_RefCount == 0) { try { PortAudio.Pa_Terminate(); } catch (Exception ex) { CLog.LogError(errorText: $"Error disposing PortAudio: {ex.Message}", e: ex); } } _Disposed = true; } }
/// <summary> /// Selects the most appropriate host api /// </summary> /// <returns>The most appropriate host api</returns> public int GetHostApi() { if (_Disposed) { throw new ObjectDisposedException("PortAudioHandle already disposed"); } int selectedHostApi = PortAudio.Pa_GetDefaultHostApi(); int apiCount = PortAudio.Pa_GetHostApiCount(); for (int i = 0; i < apiCount; i++) { PortAudio.PaHostApiInfo apiInfo = PortAudio.Pa_GetHostApiInfo(i); if ((apiInfo.type == PortAudio.PaHostApiTypeId.paDirectSound) || (apiInfo.type == PortAudio.PaHostApiTypeId.paALSA)) { selectedHostApi = i; } } return(selectedHostApi); }
// Startup audio engine public static void Startup() { LibPD.ReInit(); LibPD.Print += printCallback; LibPD.Float += floatCallback; LibPD.Bang += bangCallback; LibPD.OpenAudio(1, 2, 44100); LibPD.ComputeAudio(true); handle = LibPD.OpenPatch("patch/soundsystem.pd"); PortAudio.Pa_Initialize(); PortAudio.Pa_OpenDefaultStream(out stream, 1, 2, (uint)PortAudio.PaSampleFormat.paFloat32, 44100, 256, renderCallback, (IntPtr)null); PortAudio.Pa_StartStream(stream); }
/// <summary> /// Checks if PA returned an error and logs it /// Returns true on error /// </summary> /// <param name="action">Action identifier (E.g. openStream)</param> /// <param name="errorCode">Result returned by Pa_* call</param> /// <returns>True on error</returns> public bool CheckError(String action, PortAudio.PaError errorCode) { if (_Disposed) { throw new ObjectDisposedException("PortAudioHandle already disposed"); } if (errorCode != PortAudio.PaError.paNoError) { CLog.LogError(action + " error: " + PortAudio.Pa_GetErrorText(errorCode)); if (errorCode == PortAudio.PaError.paUnanticipatedHostError) { PortAudio.PaHostErrorInfo errorInfo = PortAudio.Pa_GetLastHostErrorInfo(); CLog.LogError("- Host error API type: " + errorInfo.hostApiType); CLog.LogError("- Host error code: " + errorInfo.errorCode); CLog.LogError("- Host error text: " + errorInfo.errorText); } return(true); } return(false); }
public DeviceItem(int deviceIndex, PortAudio.PaDeviceInfo deviceInfo) { this.deviceIndex = deviceIndex; this.deviceInfo = deviceInfo; }