home *** CD-ROM | disk | FTP | other *** search
/ io Programmo 39 / IOPROG_39.ISO / SOFT / sdkjava40.exe / data1.cab / fg_Samples / Samples / DirectX / dsound / DSound.java < prev    next >
Encoding:
Java Source  |  2000-05-04  |  16.3 KB  |  516 lines

  1. // 
  2. // 
  3. //  (C) Copyright 1995 - 1999 Microsoft Corporation.  All rights reserved.
  4. // 
  5. //  File: DirectSoundTest.java
  6. //          
  7. //  Description: shows use of DirectSound (via DirectSoundLIB.java).
  8. // 
  9. // 
  10.  
  11.  
  12. import java.applet.*;
  13. import java.awt.*;
  14. import com.ms.com.*;
  15. import com.ms.directX.*;
  16. import java.net.URL;
  17. import java.net.MalformedURLException;
  18.  
  19.                                                 
  20. //==============================================================================
  21. // Main Class for applet DirectSoundTest
  22. //
  23. //==============================================================================
  24. public class DSound extends Applet implements Runnable, DirectXConstants, IEnumSoundDriversCallback
  25. {
  26.     private DSoundLIB m_dsLib;
  27.     private TextArea  m_TextArea = null;
  28.     private DSoundFrame m_DebugFrame;
  29.     private boolean running;
  30.  
  31.     // THREAD SUPPORT:
  32.     //              m_DirectSoundTest       is the Thread object for the applet
  33.     //--------------------------------------------------------------------------
  34.     Thread   m_DirectSoundTest = null;
  35.  
  36.     //if top level exception, print a message in the window
  37.     //--------------------------------------------------------------------------
  38.     boolean m_topException = false;
  39.     String m_exceptionMessage;
  40.  
  41.     // STANDALONE APPLICATION SUPPORT:
  42.     //        m_fStandAlone will be set to true if applet is run standalone
  43.     //--------------------------------------------------------------------------
  44.     boolean m_fStandAlone = false;
  45.  
  46.     // STANDALONE APPLICATION SUPPORT
  47.     //     The main() method acts as the applet's entry point when it is run
  48.     // as a standalone application. It is ignored if the applet is run from
  49.     // within an HTML page.
  50.     //--------------------------------------------------------------------------
  51.     public static void main(String args[])
  52.     {
  53.         // Create Toplevel Window to contain applet DirectSoundTest
  54.         //----------------------------------------------------------------------
  55.         DSoundFrame frame = new DSoundFrame("DirectSound Sample");
  56.  
  57.         // Must show Frame before we size it so insets() will return valid values
  58.         //----------------------------------------------------------------------
  59.         frame.show();
  60.         frame.hide();
  61.         frame.resize(frame.insets().left + frame.insets().right  + 320,
  62.                      frame.insets().top  + frame.insets().bottom + 240);
  63.  
  64.  
  65.         // The following code starts the applet running within the frame window.
  66.         // It also calls GetParameters() to retrieve parameter values from the
  67.         // command line, and sets m_fStandAlone to true to prevent init() from
  68.         // trying to get them from the HTML page.
  69.         //----------------------------------------------------------------------
  70.         DSound applet_directSoundTest = new DSound();
  71.  
  72.         frame.add("Center", applet_directSoundTest);
  73.  
  74.         applet_directSoundTest.m_fStandAlone = true;
  75.         applet_directSoundTest.init();
  76.         applet_directSoundTest.start();
  77.         frame.show();
  78.     }
  79.  
  80.    //------------------------------------------------
  81.  
  82.    private void DebugMsg (String s)
  83.    {
  84.       String ss;
  85.  
  86.       ss = "DirectSoundTest " + s;
  87.       System.out.println (ss);
  88.       if (m_TextArea != null)
  89.          m_TextArea.appendText (ss + "\n");
  90.       
  91.       // this will make those pesky numbers update to show it's 
  92.       // still alive...
  93.       repaint();
  94.    }
  95.  
  96.     // DirectSoundTest Class Constructor
  97.     //--------------------------------------------------------------------------
  98.     public DSound()
  99.     {
  100.     }
  101.  
  102.     // APPLET INFO SUPPORT:
  103.     //        The getAppletInfo() method returns a string describing the applet's
  104.     // author, copyright date, or miscellaneous information.
  105.         //--------------------------------------------------------------------------
  106.     public String getAppletInfo()
  107.     {
  108.         return "Name: DirectSoundTest\r\n" +
  109.                "Author: Microsoft\r\n" +
  110.                "Created with Microsoft Visual J++ Version 1.0";
  111.     }
  112.  
  113.         //--------------------------
  114.  
  115.     public String GetFullFileName (String rawFileName)
  116.     {
  117.         String file;
  118.  
  119.         try
  120.         {
  121.             URL url = new URL( getDocumentBase(), rawFileName);
  122.  
  123.             file = url.getFile();
  124.             char c0 = file.charAt(0);
  125.             char c2 = file.charAt(2);
  126.             if( (c0 == '/') && (c2 == ':') )
  127.             {
  128.                 char ch[] = new char[file.length()-1];
  129.                 file.getChars(1,file.length(),ch,0);
  130.                 file = new String(ch);
  131.             }
  132.         }
  133.         catch(MalformedURLException me)
  134.         {
  135.          DebugMsg ("GetFullFileName caught exception \n   " + me);
  136.             file = new String (rawFileName);
  137.         }
  138.       catch (Exception e)
  139.       {
  140.          DebugMsg ("GetFullFileName caught exception \n   " + e);
  141.             file = new String (rawFileName);
  142.         }
  143.  
  144.         return file;
  145.     }
  146.  
  147.     //--------------------------------
  148.  
  149.         public void CreateDebugWindow (int nWidth, int nHeight)
  150.         {
  151.  
  152.       m_DebugFrame = new DSoundFrame ("DirectSoundTest Msgs");
  153.       m_DebugFrame.resize (nWidth, nHeight);
  154.  
  155.       m_TextArea = new TextArea (nWidth, nHeight);
  156.       m_DebugFrame.add ("Center", m_TextArea);
  157.       m_DebugFrame.show();
  158.    }
  159.  
  160.    // The init() method is called by the AWT when an applet is first loaded or
  161.     // reloaded.  Override this method to perform whatever initialization your
  162.     // applet needs, such as initializing data structures, loading images or
  163.     // fonts, creating frame windows, setting the layout manager, or adding UI
  164.     // components.
  165.    //--------------------------------------------------------------------------
  166.     public void init()
  167.     {
  168.       resize (320, 240);
  169.       
  170. //      if (m_fStandAlone)
  171. //         CreateDebugWindow (300, 400);
  172.  
  173.       try
  174.       {
  175.          m_dsLib = new DSoundLIB (this, DSSCL_NORMAL);
  176.       }
  177.       catch (Exception e)
  178.       {
  179.          m_topException = true;
  180.          m_exceptionMessage = e.getMessage();
  181.          ErrorExit ("m_dsLib exception \n" + e, 1);
  182.          return;
  183.       }
  184.  
  185.       String sFile = new String ("walk.wav");   
  186.       
  187.       // 
  188.       // URL throws an exception when we try to get document base if
  189.       // we're not running from a browser (ie. JVIEW DirectSoundTest).  
  190.       // Otherwise we need to find the path to the wave file.
  191.       if (! m_fStandAlone)
  192.          sFile = GetFullFileName (sFile);
  193.  
  194.       if (! m_dsLib.PlayWave (sFile, true))
  195.          ErrorExit ("Can't play wave file [" + sFile + "]", 3);
  196.     }
  197.    
  198.    //--------------------------------------------------------------------------
  199.  
  200.    public void ErrorExit (String s, int nExitValue)
  201.    {
  202.       DebugMsg ("FatalError: [" + s + "]");
  203.         if(m_fStandAlone)
  204.          System.exit (nExitValue);
  205.    }
  206.  
  207.    // Place additional applet clean up code here.  destroy() is called when
  208.     // when you applet is terminating and being unloaded.
  209.     //-------------------------------------------------------------------------
  210.     public void destroy()
  211.     {
  212.     }
  213.  
  214.     // DirectSoundTest Paint Handler
  215.     //--------------------------------------------------------------------------
  216.     public void paint(Graphics g)
  217.     {
  218.         if (! m_fStandAlone)
  219.         {
  220.             g.drawString("For debug output, see ", 10, 20);
  221.             g.drawString("<windows dir>\\java\\JavaLog.txt..." , 10, 40);
  222.         }
  223.  
  224.         if(m_topException)
  225.         {
  226.             g.drawString(m_exceptionMessage, 10, 100);
  227.         }
  228.         else
  229.         {
  230.             g.drawString("Note: this window needs focus in ", 10, 100);
  231.             g.drawString("     order to hear the sound.", 10, 120);
  232.             g.drawString("Running (sound should be playing): " + Math.random(), 10, 140);
  233.         }
  234.     }
  235.  
  236.     //        The start() method is called when the page containing the applet
  237.     // first appears on the screen. The AppletWizard's initial implementation
  238.     // of this method starts execution of the applet's thread.
  239.     //--------------------------------------------------------------------------
  240.     public void start()
  241.     {
  242.         running = true;
  243.         m_DirectSoundTest = new Thread(this);
  244.         m_DirectSoundTest.start();
  245.     }
  246.     
  247.     //        The stop() method is called when the page containing the applet is
  248.     // no longer on the screen. The AppletWizard's initial implementation of
  249.     // this method stops execution of the applet's thread.
  250.     //--------------------------------------------------------------------------
  251.     public void stop()
  252.     {
  253.         m_dsLib.StopWave();
  254.         running = false;
  255.         if (m_DirectSoundTest != null)
  256.             m_DirectSoundTest.stop();
  257.     }
  258.  
  259.     // THREAD SUPPORT
  260.     //        The run() method is called when the applet's thread is started. If
  261.     // your applet performs any ongoing activities without waiting for user
  262.     // input, the code for implementing that behavior typically goes here. For
  263.     // example, for an applet that performs animation, the run() method controls
  264.     // the display of images.
  265.     //--------------------------------------------------------------------------
  266.     public void run()
  267.     {
  268.       // Test some basic DirectSound api's...
  269.       // 
  270.       // Note, if you just wanted to play a wave file, all you'd need is the
  271.       //       code in the Init()...
  272.       TestDirectSoundMethods();
  273.       DebugMsg (" ");
  274.       TestDirectSoundBufferMethods();
  275.       
  276.       while (running)
  277.         {
  278.          try
  279.             {
  280.                 repaint();
  281.                 m_DirectSoundTest.sleep(50);
  282.             }
  283.             catch (InterruptedException e)
  284.             {
  285.                 stop();
  286.             }
  287.         }
  288.     }
  289.  
  290.    //---------------------------------------
  291.  
  292.    public void callbackEnumSoundDrivers(_Guid g, String Description, 
  293.                               String mod, IUnknown lpContext)
  294.    {
  295.       DebugMsg ("   EnumSoundDrivers: [" + Description + ", " + mod + "]");
  296.    }
  297.  
  298.    //---------------------------------------
  299.  
  300.    public void TestDirectSoundMethods()
  301.       // 
  302.       // call some DirectSound api's to make sure things are working...
  303.    {
  304.         DirectSound ds;
  305.  
  306.       DebugMsg ("TestDirectSoundMethods =================");
  307.       try
  308.       {
  309.          // Get the initialized DirectSound object from the library
  310.          ds = m_dsLib.GetDirectSoundObject();
  311.  
  312.          
  313.          // Enumerate devices on system
  314.          DebugMsg ("TEST: EnumSoundDrivers...");
  315.          try{
  316.          ds.enumSoundDrivers ((IEnumSoundDriversCallback)this, (IUnknown)null);
  317.          }
  318.          catch (Exception e)
  319.          {
  320.             String s = e.toString();
  321.             System.out.println(s);
  322.          }
  323.  
  324.          // TEST  compact the sound card memory 
  325.          DebugMsg ("TEST: Compact()");
  326.          ds.setCooperativeLevel (this, DSSCL_EXCLUSIVE);
  327.          ds.compact();
  328.          ds.setCooperativeLevel (this, DSSCL_NORMAL);
  329.  
  330.          // TEST  speaker config
  331.          DebugMsg ("TEST: Get/SetSpeakerConfig()");
  332.          int nSpeakerConfig[] = new int [1];
  333.          ds.setSpeakerConfig (DSSPEAKER_HEADPHONE);
  334.          ds.getSpeakerConfig (nSpeakerConfig);
  335.          if (nSpeakerConfig[0] != DSSPEAKER_HEADPHONE)
  336.             DebugMsg ("Get/Set speaker config failed");
  337.  
  338.          
  339.          // TEST GetCaps()
  340.          DebugMsg ("TEST: GetCaps()");
  341.          DSCaps dsCaps = new DSCaps();
  342.          ds.getCaps (dsCaps);
  343.          DebugMsg ("   dsCaps.freeHwMemBytes         = " + dsCaps.freeHwMemBytes);
  344.          DebugMsg ("   dsCaps.freeHwMixingAllBuffers = " + dsCaps.freeHwMixingAllBuffers);
  345.          DebugMsg ("   dsCaps.primaryBuffers         = " + dsCaps.primaryBuffers);
  346.       }
  347.       catch (Exception e)
  348.       {
  349.          DebugMsg ("TestDirectSoundMethods, caught exception \n " + e);
  350.          e.printStackTrace();
  351.          stop();
  352.       }
  353.    }
  354.  
  355.    //---------------------------------------
  356.  
  357.    public void TestDirectSoundBufferMethods()
  358.       // 
  359.       // * call some DirectSound api's to make sure things are working...
  360.       // * assumes there's a wave file playing on LOOP mode.
  361.       // 
  362.    {
  363.       DebugMsg ("TestDirectSoundBufferMethods =================");
  364.       try
  365.       {
  366.          // Get the initialized DirectSound objects from the library
  367.          DirectSoundBuffer dsBuffer = m_dsLib.GetDirectSoundBufferObject();
  368.          DirectSound       ds       = m_dsLib.GetDirectSoundObject();
  369.    
  370.          // TEST GetCaps()
  371.          DebugMsg ("TEST: GetCaps()");
  372.          DSBCaps dsbCaps = new DSBCaps();
  373.          dsBuffer.getCaps (dsbCaps);
  374.          DebugMsg ("   dsbCaps.bufferBytes        = " + dsbCaps.bufferBytes);
  375.          DebugMsg ("   dsbCaps.unlockTransferRate = " + dsbCaps.unlockTransferRate);
  376.          DebugMsg ("   dsbCaps.playCpuOverhead    = " + dsbCaps.playCpuOverhead );
  377.  
  378.          // TEST GetCurrentPosition()
  379.          DebugMsg ("TEST: GetCurrentPosition()");
  380.          DSCursors dsCursors = new DSCursors();
  381.  
  382.          dsBuffer.getCurrentPosition (dsCursors);
  383.          DebugMsg ("   dsCursors.play  = " + dsCursors.play);
  384.          DebugMsg ("   dsCursors.write = " + dsCursors.write);
  385.  
  386.  
  387.          // TEST GetFormatSize()
  388.          DebugMsg ("TEST: GetFormatSize()");
  389.          int nSize;
  390.          nSize = dsBuffer.getFormatSize ();
  391.          DebugMsg ("   GetFormatSize = " + nSize);
  392.  
  393.  
  394.          // TEST GetFormat()
  395.          // note: GetFormat() returns a new WaveFormatEx(); 
  396.          DebugMsg ("TEST: GetFormat()");
  397.          WaveFormatEx waveForm;  
  398.          
  399.          waveForm = dsBuffer.getFormat();
  400.          DebugMsg ("   waveForm.channels      = " + waveForm.channels);
  401.          DebugMsg ("   waveForm.bitsPerSample = " + waveForm.bitsPerSample);
  402.          DebugMsg ("   waveForm.samplesPerSec = " + waveForm.samplesPerSec);
  403.  
  404.  
  405.          // let users get used to current volume level              
  406.          Wait (5);      
  407.  
  408.          // TEST GetVolume()
  409.          DebugMsg ("TEST: GetVolume()");
  410.          int nTemp = 10;
  411.          nTemp = dsBuffer.getVolume();
  412.          DebugMsg ("TEST: GetVolume() = " + nTemp);
  413.          
  414.  
  415.          // Test SetVolume()
  416.          DebugMsg ("   Setting volume to 1/2");
  417.  
  418.          // NOTE: units are in hundreths of decibels 
  419.          dsBuffer.setVolume (nTemp - 1000);   
  420.          Wait (6);
  421.          DebugMsg ("   Restoring volume to original level");
  422.          dsBuffer.setVolume (nTemp);
  423.  
  424.          // Test GetPan()
  425.          DebugMsg ("TEST: GetPan()");
  426.          nTemp = dsBuffer.getPan();
  427.          DebugMsg ("TEST: GetPan() = " + nTemp);
  428.  
  429.          // Test SetPan()
  430.          DebugMsg ("   Setting pan from LEFT to RIGHT....");
  431.          for (int nPan = -10000; nPan < 10000; nPan += 1000)
  432.          {
  433.             dsBuffer.setPan (nPan);
  434.             Wait (1);
  435.          }
  436.          
  437.          DebugMsg ("   Restoring original pan setting.... " + nTemp);
  438.          dsBuffer.setPan (nTemp);
  439.  
  440.  
  441.          // Test GetFrequency()
  442.          DebugMsg ("TEST: GetFrequency()");
  443.          nTemp = dsBuffer.getFrequency();
  444.          DebugMsg ("TEST: GetFrequency() = " + nTemp);
  445.  
  446.          // Test SetFrequency(); note upper limit is 100000
  447.          DebugMsg ("   Setting Frequency from 100 to 50000....");
  448.          for (int nFreq = 100; nFreq < 50000; nFreq += 3000)
  449.          {
  450.             dsBuffer.setFrequency (nFreq);
  451.             Wait (2);
  452.          }
  453.          
  454.          DebugMsg ("   Restoring original frequency setting.... " + nTemp);
  455.          dsBuffer.setFrequency (nTemp);
  456.  
  457.  
  458.          // Test: GetStatus
  459.          nTemp = dsBuffer.getStatus();
  460.          DebugMsg ("TEST: GetStatus() = " + nTemp);
  461.  
  462.  
  463.          // Test: Stop
  464.          DebugMsg ("TEST: Stop()");
  465.          m_dsLib.StopWave();
  466.          DebugMsg ("   wave playback is stopped now...");
  467.  
  468.  
  469.          // Test: SetCurrentPosition.  Wave buffer positions are 0 to maxBufferSize
  470.          DebugMsg ("TEST: SetCurrentPosition()");
  471.          int nBufferSize = m_dsLib.GetBufferSize();
  472.          DebugMsg ("   BufferSize = " + nBufferSize);
  473.          
  474.          // 
  475.          // play the wave file starting from different positions within
  476.          // the wave file.
  477.          int nPos;
  478.          for (int n = 0; n < 4; n++)
  479.          {
  480.             nPos = (int)((double)nBufferSize * Math.random());
  481.             DebugMsg ("   Setting current position to: " + nPos);
  482.             dsBuffer.setCurrentPosition (nPos);
  483.             m_dsLib.PlayWave (0);
  484.             while (dsBuffer.getStatus() == DSBSTATUS_PLAYING)
  485.                ;
  486.  
  487.             Wait (3);
  488.          }
  489.  
  490.  
  491.          Wait (2);
  492.          m_dsLib.PlayWave (DSBPLAY_LOOPING);
  493.          DebugMsg ("Normal wave playback has resumed now, \n   end of test...");
  494.       }
  495.       catch (Exception e)
  496.       {
  497.          DebugMsg ("TestDirectSoundBufferMethods, caught exception \n " + e);
  498.          stop();
  499.       }
  500.    }
  501.  
  502.    //--------------------------------------------------
  503.  
  504.    public void Wait(int nLoopCounter)
  505.    {
  506.       try
  507.       {
  508.          Thread.sleep (nLoopCounter * 500);
  509.       }
  510.       catch (InterruptedException e)
  511.       {
  512.          DebugMsg ("Wait: caught exception \n   " + e);
  513.       }
  514.    }
  515. }
  516.