public void InitVoiceHost(Peer host, Voice.Server dpvs, Voice.Client dpvc, Form wnd) { try { server = dpvs; client = dpvc; TestAudioSetup(wnd); //Audio Setup was successful, open the configuration form mConfigForm.ShowDialog(mClientConfig, dpvs.CompressionTypes, false); if (mConfigForm.DialogResult == DialogResult.Cancel) { throw new Exception("Voice configuration cancelled"); } mClientConfig = mConfigForm.ClientConfig; //create the voice session CreateVoiceSession(host, Voice.SessionType.Peer, mConfigForm.CompressionGuid); //Connect to the voice session ConnectToVoiceSession(host, wnd); } catch (Exception e) { MessageBox.Show("Error attempting to start Voice Server Session. This sample will now exit.", "Exiting", MessageBoxButtons.OK, MessageBoxIcon.Information); throw e; } }
private void VoiceHostMigrated(object sender, Voice.HostMigratedEventArgs dpMessage) { if (localPlayerId == dpMessage.Message.NewHostID) { // I'm the new host, update my UI this.Text += " (HOST)"; //add reference to new voice server server = dpMessage.Message.ServerObject; //notify the voice wizard of the change voiceSettings.HostMigrate(server); } }
/// <summary> /// Initializes the DirectPlayVoice Client and Server objects /// </summary> private void InitDirectPlayVoice() { // Release any existing resources if (m_VoiceClient != null) { m_VoiceClient.Dispose(); m_VoiceClient = null; } if (m_VoiceServer != null) { m_VoiceServer.Dispose(); m_VoiceServer = null; } // Initialize UI variables this.m_NumPlayersTalking = 0; // Based on the current connection, create DirectPlay voice objects. #region About DirectPlay Voice // Since the DirectPlay Voice API defines server and client interfaces, // but not a peer interface, one of the peers must act as the server // for voice communication; the logical choice is the session host, so // for this sample, the session host creates a server object in addition // to a client object. Note that in order to send and receive voice // messages you must have a connected voice client object, even if you // are acting as the voice server. #endregion switch (Connection) { case ConnectionType.Hosting: { // Create a new Voice Server m_VoiceServer = new Voice.Server(m_Peer); // Create a Session Description for the voice session Voice.SessionDescription desc = new Voice.SessionDescription(); desc.SessionType = Voice.SessionType.Peer; desc.BufferQuality = Voice.BufferQuality.Default; desc.GuidCompressionType = Voice.CompressionGuid.Default; desc.BufferAggressiveness = Voice.BufferAggressiveness.Default; // Launch a new voice session m_VoiceServer.StartSession(desc); // Fall-through to create client object goto case ConnectionType.Connected; } case ConnectionType.Connected: { // Test Direct Voice if (TestDirectVoice() == false) { return; } // Create a new Voice Client m_VoiceClient = new Voice.Client(m_Peer); // Add event handlers m_VoiceClient.PlayerStarted += new Voice.PlayerStartedEventHandler(PlayerStartedHandler); m_VoiceClient.PlayerStopped += new Voice.PlayerStoppedEventHandler(PlayerStoppedHandler); m_VoiceClient.RecordStarted += new Voice.RecordStartedEventHandler(RecordStartedHandler); m_VoiceClient.RecordStopped += new Voice.RecordStoppedEventHandler(RecordStoppedHandler); // Fill in description object for device configuration Voice.SoundDeviceConfig soundConfig = new Voice.SoundDeviceConfig(); soundConfig.Flags = Voice.SoundConfigFlags.AutoSelect; soundConfig.GuidPlaybackDevice = DSoundHelper.DefaultPlaybackDevice; soundConfig.GuidCaptureDevice = DSoundHelper.DefaultCaptureDevice; soundConfig.Window = m_Form; soundConfig.MainBufferPriority = 0; // Fill in description object for client configuration Voice.ClientConfig clientConfig = new Voice.ClientConfig(); clientConfig.Flags = Voice.ClientConfigFlags.AutoVoiceActivated | Voice.ClientConfigFlags.AutoRecordVolume; clientConfig.RecordVolume = (int)Voice.RecordVolume.Last; clientConfig.PlaybackVolume = (int)Voice.PlaybackVolume.Default; clientConfig.Threshold = Voice.Threshold.Unused; clientConfig.BufferQuality = Voice.BufferQuality.Default; clientConfig.BufferAggressiveness = Voice.BufferAggressiveness.Default; clientConfig.NotifyPeriod = 0; try { // Connect to the voice session m_VoiceClient.Connect(soundConfig, clientConfig, Voice.VoiceFlags.Sync); } catch (Exception ex) { m_Form.ShowException(ex, "Connect", true); m_Form.Dispose(); return; } // Set DirectPlay to send voice messages to all players int[] targets = { (int)Voice.PlayerId.AllPlayers }; m_VoiceClient.TransmitTargets = targets; break; } case ConnectionType.Disconnected: { return; } } }
public void HostMigrate(Voice.Server dpvs) { server = dpvs; mIsHost = true; }
/// <summary> /// Constructor /// </summary> public VoiceConnect() { InitializeComponent(); try { //set up state members playerList = new ArrayList(); //create the peer peerObject = new Peer(); //create the voice client and attach message handlers client = new Voice.Client(peerObject); client.HostMigrated += new Voice.VoiceHostMigratedEventHandler(VoiceHostMigrated); client.PlayerCreated += new Voice.VoicePlayerCreatedEventHandler(VoicePlayerCreated); client.PlayerDeleted += new Voice.VoicePlayerDeletedEventHandler(VoicePlayerDeleted); client.SessionLost += new Voice.SessionLostEventHandler(VoiceSessionLost); client.PlayerStarted += new Voice.PlayerStartedEventHandler(PlayerStarted); client.PlayerStopped += new Voice.PlayerStoppedEventHandler(PlayerStopped); client.RecordStarted += new Voice.RecordStartedEventHandler(RecordStarted); client.RecordStopped += new Voice.RecordStoppedEventHandler(RecordStopped); //session was not lobby launched -- using connection wizard playWizard = new ConnectWizard(peerObject, g_guidApp, "VoiceConnect"); playWizard.DefaultPort = DefaultPort; //create the voice wizard voiceSettings = new VoiceWizard(); if (playWizard.StartWizard()) { if (playWizard.IsHost) { this.Text += " (HOST)"; //create the voice server server = new Voice.Server(peerObject); //init the voice server voiceSettings.InitVoiceHost(peerObject, server, client, this); } else { //connection to another host was successful voiceSettings.InitVoiceClient(peerObject, client, this); } } else { this.Dispose(); } } catch (Exception e) { Console.WriteLine(e.ToString()); //allow exception to fall though and exit. this.Close(); } }
/// <summary>Begin a new game as a host.</summary> /// <param name="mode">Server codec and mixing policy.</param> /// <param name="port">IP port that will listen.</param> public void Start(VoiceServerMode mode, int port) { uncompressJobsPending = new ManualResetEvent(false); try { ApplicationDescription description = new ApplicationDescription(); description.GuidApplication = new Guid("{920BAF09-A06C-47d8-BCE0-21B30D0C3586}"); description.MaxPlayers = 0; // unlimited description.SessionName = "ZunTzu"; description.Flags = Microsoft.DirectX.DirectPlay.SessionFlags.ClientServer | Microsoft.DirectX.DirectPlay.SessionFlags.FastSigned | Microsoft.DirectX.DirectPlay.SessionFlags.NoDpnServer | Microsoft.DirectX.DirectPlay.SessionFlags.NoEnumerations; using (Address address = new Address()) { address.ServiceProvider = Address.ServiceProviderTcpIp; address.AddComponent(Address.KeyPort, port); server.Host(description, address); } if (System.Environment.OSVersion.Version.Major < 6) // not Vista? // launch a voice session { voiceServer = new Microsoft.DirectX.DirectPlay.Voice.Server(server); SessionDescription desc = new SessionDescription(); desc.SessionType = SessionType.Fowarding; // (mode == VoiceServerMode.ForwardingAdpcm || mode == VoiceServerMode.ForwardingGsm ? SessionType.Fowarding : SessionType.Mixing); desc.BufferQuality = BufferQuality.Default; desc.GuidCompressionType = (mode == VoiceServerMode.ForwardingAdpcm || mode == VoiceServerMode.MixingAdpcm ? CompressionGuid.AdPcm : CompressionGuid.Gsm); desc.BufferAggressiveness = BufferAggressiveness.Default; desc.Flags = Microsoft.DirectX.DirectPlay.Voice.SessionFlags.NoHostMigration; //desc.Flags = Microsoft.DirectX.DirectPlay.Voice.SessionFlags.ServerControlTarget; voiceServer.StartSession(desc); } // allow NAT traversal (3 trials) InternetConnectivity connectivity = InternetConnectivity.Unknown; for (int trial = 0; (natTraversalSession == null || !natTraversalSession.Enabled) && trial < 3; ++trial) { natTraversalSession = NatResolver.EnableNatTraversal(port); } string fallbackPublicIpAddress = null; if (natTraversalSession.Enabled) { // notify the parent process via the standard output connectivity = InternetConnectivity.Full; } else { // fallback: discover public IP through HTTP try { // Start a synchronous request. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"http://www.zuntzu.com/hostfallback.php"); request.UserAgent = "ZunTzu"; request.Timeout = 10000; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; byte[] bytes = System.Text.ASCIIEncoding.ASCII.GetBytes("id=" + natTraversalSession.SessionId.ToString("N")); request.ContentLength = bytes.Length; using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(bytes, 0, bytes.Length); } using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode == HttpStatusCode.OK) { using (Stream stream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream)) { string responseContent = reader.ReadToEnd(); Regex ipAddressRegex = new Regex(@"^(?<1>[012])(?<2>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})", RegexOptions.Singleline); Match ipAddressMatch = ipAddressRegex.Match(responseContent); if (ipAddressMatch.Success) { switch (ipAddressMatch.Groups[1].Value) { case "0": connectivity = InternetConnectivity.Unknown; break; case "1": connectivity = InternetConnectivity.NoEgress; break; case "2": connectivity = InternetConnectivity.NoIngress; break; } fallbackPublicIpAddress = ipAddressMatch.Groups[2].Value; } } } } else { throw new WebException(); } } } catch (Exception) { // fallback: query a public web site to check Internet connectivity try { // Start a synchronous request. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"http://www.google.com/"); request.Timeout = 10000; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode != HttpStatusCode.OK) { throw new WebException(); } } } catch (Exception) { connectivity = InternetConnectivity.None; } } } // notify the parent process via the standard output switch (connectivity) { case InternetConnectivity.Unknown: case InternetConnectivity.None: Console.Out.WriteLine("Server started {0}/?/?", (int)connectivity); break; case InternetConnectivity.NoEgress: case InternetConnectivity.NoIngress: Console.Out.WriteLine("Server started {0}/{1}/?", (int)connectivity, fallbackPublicIpAddress); break; case InternetConnectivity.Full: Console.Out.WriteLine("Server started {0}/{1}/{2}", (int)connectivity, natTraversalSession.PublicIpAddress, natTraversalSession.PublicPort); break; } } catch (InvalidDeviceAddressException) { // notify the parent process via the standard output Console.Out.WriteLine("Invalid Device Address"); } catch (Exception e) { // notify the parent process via the standard output Console.Out.WriteLine(e.Message); } Console.Out.Flush(); processVideoFrames(); }