Jump to content
  • Advertisement


  • Content Count

  • Joined

  • Last visited

Everything posted by cartographer

  1. Hi all, i m using DirectSound to capture the audio from a server and sending it to client which plays the incomming data. But alas when i play audio i just hear sounds like hiss with short delays. everthing is fine but i couldnt find the clue to handle it. Here is my server code: <code> namespace MSDNAudioServer2 { public partial class Form1 : Form { public BufferPositionNotify[] PositionNotify = new BufferPositionNotify[NumberRecordNotifications + 1]; public const int NumberRecordNotifications = 2; public AutoResetEvent NotificationEvent = null; public CaptureBuffer applicationBuffer = null; public Capture applicationDevice = null; public Notify applicationNotify = null; private Thread NotifyThread = null; public int CaptureBufferSize = 0; public int NextCaptureOffset = 0; public WaveFormat InputFormat; public int NotifySize = 0; private bool Capturing = false; Socket socketForClient = null; TcpListener tcpListener = null; public Form1() { InitializeComponent(); InitDirectSound(); if (null == applicationDevice) Close(); else { InputFormat.SamplesPerSecond = 16000; InputFormat.BitsPerSample = 8; InputFormat.Channels = 1; InputFormat.BlockAlign = (short)(InputFormat.Channels * (InputFormat.BitsPerSample / 8)); InputFormat.AverageBytesPerSecond = InputFormat.BlockAlign * InputFormat.SamplesPerSecond; InputFormat.FormatTag = WaveFormatTag.Pcm; } } private void InitDirectSound() { CaptureBufferSize = 0; NotifySize = 0; // Create DirectSound.Capture using the preferred capture device try { applicationDevice = new Capture(); rt.AppendText("\n Capture initialized"); } catch { rt.AppendText("\n Capture not initialized");} } void CreateCaptureBuffer() { //----------------------------------------------------------------------------- // Name: CreateCaptureBuffer() // Desc: Creates a capture buffer and sets the format //----------------------------------------------------------------------------- CaptureBufferDescription dscheckboxd = new CaptureBufferDescription(); if (null != applicationNotify) { applicationNotify.Dispose(); applicationNotify = null; } if (null != applicationBuffer) { applicationBuffer.Dispose(); applicationBuffer = null; } if (0 == InputFormat.Channels) return; // Set the notification size NotifySize = (1024 > InputFormat.AverageBytesPerSecond / 8) ? 1024 : (InputFormat.AverageBytesPerSecond / 8); NotifySize -= NotifySize % InputFormat.BlockAlign; rt.AppendText("\n Notify Size "+ NotifySize); // Set the buffer sizes CaptureBufferSize = NotifySize * NumberRecordNotifications; rt.AppendText("\n Capture Buffer size "+CaptureBufferSize); // Create the capture buffer dscheckboxd.BufferBytes = CaptureBufferSize; dscheckboxd.Format = InputFormat; // Set the format during creatation applicationBuffer = new CaptureBuffer(dscheckboxd, applicationDevice); rt.AppendText("\nCapture Buffere created"); NextCaptureOffset = 0; InitNotifications(); } void InitNotifications() { //----------------------------------------------------------------------------- // Name: InitNotifications() // Desc: Inits the notifications on the capture buffer which are handled // in the notify thread. //----------------------------------------------------------------------------- if (null == applicationBuffer) throw new NullReferenceException(); // Create a thread to monitor the notify events if (null == NotifyThread) { if (socketForClient.Connected) { socketForClient.Send(BitConverter.GetBytes(NotifySize), 0, 4, System.Net.Sockets.SocketFlags.None); } rt.AppendText("\nNotify Thread Created"); NotifyThread = new Thread(new ThreadStart(WaitThread)); Capturing = true; NotifyThread.Start(); // Create a notification event, for when the sound stops playing NotificationEvent = new AutoResetEvent(false); } // Setup the notification positions for (int i = 0; i < NumberRecordNotifications; i++) { PositionNotify.Offset = (NotifySize * i) + NotifySize - 1; PositionNotify.EventNotifyHandle = NotificationEvent.Handle; } applicationNotify = new Notify(applicationBuffer); // Tell DirectSound when to notify the app. The notification will come in the from // of signaled events that are handled in the notify thread. applicationNotify.SetNotificationPositions(PositionNotify, NumberRecordNotifications); } void StartOrStopRecord(bool StartRecording) { //----------------------------------------------------------------------------- // Name: StartOrStopRecord() // Desc: Starts or stops the capture buffer from recording //----------------------------------------------------------------------------- if (StartRecording) { // Create a capture buffer, and tell the capture // buffer to start recording CreateCaptureBuffer(); applicationBuffer.Start(true); } else { // Stop the buffer, and read any data that was not // caught by a notification applicationBuffer.Stop(); Capturing = false; RecordCapturedData(); } } void RecordCapturedData() { //----------------------------------------------------------------------------- // Name: RecordCapturedData() // Desc: Copies data from the capture buffer to the output buffer //----------------------------------------------------------------------------- byte[] CaptureData = null; int ReadPos; int CapturePos; int LockSize; applicationBuffer.GetCurrentPosition(out CapturePos, out ReadPos); LockSize = ReadPos - NextCaptureOffset; if (LockSize < 0) LockSize += CaptureBufferSize; // Block align lock size so that we are always write on a boundary LockSize -= (LockSize % NotifySize); if (0 == LockSize) return; // Read the capture buffer. CaptureData = (byte[])applicationBuffer.Read(NextCaptureOffset, typeof(byte), LockFlag.None,LockSize); if(socketForClient.Connected) SendToClient(CaptureData); // Move the capture offset along NextCaptureOffset += CaptureData.Length; NextCaptureOffset %= CaptureBufferSize; // Circular buffer } private void WaitThread() { while (Capturing) { //Sit here and wait for a message to arrive NotificationEvent.WaitOne(Timeout.Infinite, true); RecordCapturedData(); } } private void SendToClient(byte[] audioData) { int length; length = audioData.Length; try { if (socketForClient.Connected) { socketForClient.Send(BitConverter.GetBytes(length), 0, 4, System.Net.Sockets.SocketFlags.None); int PacketSize = 16000; if (length > PacketSize) { long totalBytes = length; long index = 0; while (totalBytes > 0) { if (totalBytes > PacketSize) { byte[] b = new byte[PacketSize]; Array.Copy(audioData, index, b, 0, PacketSize); socketForClient.Send(b, 0, PacketSize, System.Net.Sockets.SocketFlags.None); b = null; } else { socketForClient.Send(audioData, (int)index, (int)totalBytes, System.Net.Sockets.SocketFlags.None); } totalBytes -= PacketSize; index += PacketSize; } } else { socketForClient.Send(audioData, (int)length, System.Net.Sockets.SocketFlags.None); } } } catch (SocketException e) { MessageBox.Show(e.ToString()); } } private void button1_Click(object sender, EventArgs e) { button1.Enabled = false; tcpListener = new TcpListener(6555); tcpListener.Start(); socketForClient = tcpListener.AcceptSocket(); rt.AppendText("\n Client connected"); CreateCaptureBuffer(); StartOrStopRecord(true); } } } </code> and here is my client code <code> namespace MSDNAudioClient2 { public partial class Form1 : Form { private SecondaryBuffer ApplicationBuffer = null; BufferDescription pBuffDesc; WaveFormat wFormat; private Device ApplicationDevice = null; private string PathSoundFile = string.Empty; private byte[] m_RecBuffer = null ; public Socket cs; public TcpClient tcp; Stream stm; private Thread ReaderThread = null; public Form1() { InitializeComponent(); try { ApplicationDevice = new Device(); ApplicationDevice.SetCooperativeLevel(this, CooperativeLevel.Priority); } catch { MessageBox.Show("Unable to create sound device. Sample will now exit."); // this.Close(); } wFormat = new WaveFormat(); wFormat.SamplesPerSecond = 16000; //44MHz wFormat.Channels = 1; wFormat.BitsPerSample = 8; wFormat.BlockAlign = (short)(wFormat.Channels * (wFormat.BitsPerSample / 8)); wFormat.AverageBytesPerSecond = wFormat.BlockAlign * wFormat.SamplesPerSecond; wFormat.FormatTag = WaveFormatTag.Pcm; pBuffDesc = new BufferDescription(); pBuffDesc.ControlEffects = true; pBuffDesc.ControlFrequency = true; pBuffDesc.ControlPan = true; pBuffDesc.ControlVolume = true; pBuffDesc.Format = wFormat; pBuffDesc.GlobalFocus = true; } private void button1_Click(object sender, EventArgs e) { tcp = new TcpClient(); try { tcp.Connect(IPAddress.Parse(""), 6555); } catch (SocketException se) { MessageBox.Show("not connected"); tcp = null; } if (tcp.Connected) { this.stm = tcp.GetStream(); } byte[] ba = new byte[4]; stm.Read(ba, 0, 4); int notifysize = BitConverter.ToInt32(ba, 0); pBuffDesc.BufferBytes = notifysize * 2; try { ApplicationBuffer = new SecondaryBuffer(pBuffDesc, ApplicationDevice); } catch (Exception) { MessageBox.Show("Unable to create sound buffer. Application will now exit."); this.Close(); } ReaderThread = new Thread(new ThreadStart(ReaderThreadProc)); ReaderThread.Start(); button1.Enabled = false; } public void ReaderThreadProc() { while (tcp.Connected) { ReadData(); } } private void ReadData() { int packetSize = 16000; int length = 0; byte[] ba = new byte[4]; stm.Read(ba, 0, 4); length = BitConverter.ToInt32(ba, 0); rt.AppendText("\nData Recevied: " + length); byte[] m_RecBuffer = new byte[length]; try { if (tcp.Connected) { if (length > packetSize) { long bytesToRead = length; long idx = 0; while (bytesToRead > 0) { byte[] tb = new byte[packetSize]; long bytesRead = 0; if (bytesToRead < packetSize) { bytesRead = (long)stm.Read(tb, 0, (int)bytesToRead); } else { bytesRead = (long)stm.Read(tb, 0, (int)packetSize); } Array.Copy(tb, 0, m_RecBuffer, idx, bytesRead); tb = null; idx += bytesRead; bytesToRead -= bytesRead; } } else { stm.Read(m_RecBuffer, 0, (int)length); } // MemoryStream ms = new MemoryStream(m_RecBuffer); ApplicationBuffer.Write(0, m_RecBuffer , LockFlag.EntireBuffer); ApplicationBuffer.SetCurrentPosition(0); ApplicationBuffer.Play(0, BufferPlayFlags.Default); } //end of first if } catch (Exception e) { } } </code> Please give me idea to tackle it
  2. cartographer

    How can i manage a smooth audio?

    Where all directsound developers has gone? No Response
  3. Hi All, I m making an application like windows RDP. I have completed all of the graphics stuff. Now i want to transfer any sound generated on server like audio songs, video songs, mouse clicks etc. to client and client will play the sound with no delay. I here from my friend that DirectSound can help me regarding to my problem. Is it suitable to use DirectSound to transfer any sound generated by sound card. I need performance. Since i m new to DirectSound so please guide me how can i achieve my target. Thanx for ur responses.
  4. cartographer

    How to stream audio over network?

    Thanx for ur reply. I mentioned that i m new to DirectSound so can u guide me how i can create capture buffer. Here is the code snippet that i found to create capture buffer. <code> Capture capturedDevice = null; CaptureBuffer cBuff = null; CaptureBufferDescription cBuffDesc; WaveFormat wFormat; capturedDevice = new Capture(); cBuffDesc = new CaptureBufferDescription(); wFormat = new WaveFormat(); wFormat.SamplesPerSecond = 44100; //44MHz wFormat.Channels = 1; wFormat.BitsPerSample = 16; wFormat.BlockAlign = (short)(wFormat.Channels * (wFormat.BitsPerSample / 8)); wFormat.AverageBytesPerSecond = wFormat.BlockAlign * wFormat.SamplesPerSecond; wFormat.FormatTag = WaveFormatTag.Pcm; cBuffDesc.BufferBytes = "WHAT SHOULD I PASS HERE" cBuffDesc.Format = wFormat; cBuff = new CaptureBuffer(cBuffDesc,capturedDevice); </code> There are some confusions i have in the above code. First I my case where i have to capture all of the sounds generated by the sound card WHAT WAVEFORMAT SETTINGS WOULD BE BEST. 2nd in the BufferDescription.BufferBytes what value should i pass. Also is OGG allows me to directly compress the Capture Buffer or i have to write the capture buffer data first in a MemoryStream and then using OGG i can compress it. Thanx
  5. cartographer

    How to stream audio over network?

    Hi all, I think some of u may help me. Thanx.
  6. Hi all, I want to display smaller bitmaps of variable sizes on a picturebox. How can i do it efficiently without any runtime exception. Thanx
  7. Ya i m using the same lines of code. But i does'nt properly scale the image and soem of the areas get black.
  8. Hi all, I have made an application like VNC where my server continously tracks the display changes of its machine and then sends the changed regions as compressed images to client. Here i m using Traditional BitBlt() to capture the updated display region. Its a CPU hungry and not so much fast method of capturing a bitmap. Can anybody give me some idea how can i enhance server performance(low CPU usage) with immediate response to client. Thanx.
  9. cartographer

    Is there any other faster mathod then BitBlt?

    Thanx Harding, Ur reply is quite informative. I already have some idea of Hooking Driver to GDI calls. Is there any resource for the development of that driver from where i can get help. Bcz now a days i m planning to purchase DDK but some of my friends suggest me that before purchasing be sure u have enough helping resources from where u can get guidelines. What u suggest whether should i built the driver or buy it somewhere? Thanx
  10. Hi all, I want to make a client on linux that can communicate with my server that is based upon WinSock on windows. Anybody having idea how can i do it? Thanx for ur replies
  11. Thanx Dear. I m not an expert of network programming. Can u plz tell me what u mean by toaster?
  12. Hi all, I have made an application(server) that captures the image of its display screen using GDI APIs. All is fine but capturing of the image is using BitBlt Source copy that is slow. someone suggests me to test capturing of desktop image using DirectX frontbuffer bcz it provides direct access to video card memory. I m not used to with directX so i dont know how to do it and whether it will be more efficient then tradiational BitBlt or not. Plz help me regarding to capturing and performance gain that i can have using it. Thanx
  13. Its fine dear, but the code u have given me is saving the bitmap in a file. I need in memory(system memory) bitmap like HBITMAP. I dont want to save it into file then what should i do? Also If i want to capture a rectangular region not the whole desktop then how is it possible? Thanx for ur response
  14. Dear I know how to capture it using directX but i ask is it feasible to use directX than BitBlt. Can i get performance gain with less CPU usage. Bcz i have to capture images of each update in the display. Thanx for ur reply.
  15. I need help regarding to negotiating protocol. What messages server/client should send and receive. When server should send the regions(rectangle) to the client? I think its more important and difficult for me then making a hooking dll and capturing regions bcz i m not so strong in making a protocol( a reliable).
  16. Hi all, I have devloped a Remote Managment App. where server captures the updated regions of its screen and sends to client. Problem is that server captures the area which is updated and then sends. Updation is so frequent and so quick if i will try to send all the updates as they occur then i think evrything will stop. So i stores the updates info into a queue and then get them one by one and sends to client. It looks all will be fine but after some data tranfer my client stops receiving data. Why i dont know? What protocol i have to use to make my session a reiable one and to minimize memory usage by removing intermediate queue? Thanx
  17. Dear taking union of updated regions is efficient if the regions are closer but if the regions are far off then it i m going to create a region that maybe my whole desktop. Problem i m facing after some upadtes are visible on client side then it stops why i dont know?
  18. U r quite right but we need our own properietry standard. Actualluy i m using system wide hooking dll to hook into the address space of each running process. That dll captures all the messages sent to these processes by OS and post the messages related to screen updates to my server application. Each message contains area of the updated rectangle. My server application gets the messages posted my dll. If i dont use queue to store all messages posted to my server by my dll then i may loss ceratin messages but if i use it then my memory usage goes higher. So in that situation what should i do.
  19. Hi all, I have developed a client/server application using C# where server captures its own desktop image, break it into 16 equal segments, compares them with the previous segments stored image data. If updated then sends these updated segments one by one to the client. Client upon receiving these updated segments, updates its application picture box respective regions. Problem is on client side they appear sequentially and it doesnt give the effet of real time application. Can somebody give me idea how my client should update its areas that it looks like the whole image change at once. Thanx
  20. Hi all i have developed a dll in VC++7.0 and want to use it in C# code but i got exception: " Unable to load DLL 'HookLib.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E) " my Dll code is: ////////////////////////"HookLib.cpp" #include "stdafx.h" extern HINSTANCE g_appInstance; BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: // // Capture the application instance of this module to pass to // hook initialization. // if (g_appInstance == NULL) { g_appInstance = hinstDLL; } break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: break; default: //OutputDebugString("Not sure what just happened.\n"); break; } return TRUE; } ///////////////////// //////////////////////////"HookCore.h" #pragma once LRESULT CALLBACK GetMessageProc(int nCode, WPARAM wParam, LPARAM lParam); bool InitializeHook(); void UninitializeHook(); //////////////// //////////////////////////"HookCore.cpp" #include "stdafx.h" #include <windows.h> #include "HookCore.h" #include "MessageFilter.h" HHOOK hookMsg = NULL; HINSTANCE g_appInstance = NULL; LRESULT CALLBACK GetMessageProc(int nCode, WPARAM wParam, LPARAM lParam){ if (nCode == HC_ACTION) { MSG *msg = (MSG *) lParam; if(msg->message == WM_PAINT){ //Beep debug Beep(1000,1); //Write file debug } //Process message //... } return CallNextHookEx (hookMsg, nCode, wParam, lParam); } bool InitializeHook() { if (g_appInstance == NULL) { return false; } hookMsg = SetWindowsHookEx(WH_CALLWNDPROC, (HOOKPROC)GetMessageProc, g_appInstance, 0); return hookMsg != NULL; } void UninitializeHook() { if(hookMsg != NULL) { UnhookWindowsHookEx(hookMsg); } hookMsg = NULL; } ///////////////////////////////////////////////// ///////////////////////"HookCore.def" LIBRARY "HookLib" EXPORTS InitializeHook UninitializeHook ////////////////////////////////////////////////////////////////////////// and my C# code to import dll functions is DllImport("HookLib.dll", EntryPoint="InitializeHook", SetLastError=true, CharSet=CharSet.Unicode, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)] private static extern bool InitializeHook(); [DllImport("HookLib.dll", EntryPoint="UninitializeHook", SetLastError=true, CharSet=CharSet.Unicode, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)] private static extern void UninitializeHook(); then i use the InitializeHook() method i got the above exception can somebody tell me how i can get rid of this Thanx for ur response.
  21. I want to know which areas of my whole display screen are being updated.And i know all of the painting on dekstop is through GDI API calls. So if i can hook or intercept these GDI API calls i can get the updated regions before their updation. Thanx
  22. Hi all, I want to make an application where i can inform my application all of the changes in the current display(whole screen) using C#. Any way to do it?
  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!