Читаем Программирование КПК и смартфонов на .NET Compact Framework полностью

private extern static int PlaySoundBytes(byte[] szSound, IntPtr hMod,

 int flags);

Данная функция использует для параметра flags несколько предопределенных констант. Более подробную информацию о назначении флагов этой функции можно найти в документации.

После этого создаются два конструктора с разными параметрами, которые будут использоваться для разных методов воспроизведения звука, и метод Play. Теперь нужно перейти к основной форме и разместить на ней две кнопки. Первая кнопка, butResource, будет проигрывать звуковой фрагмент, который хранится в ресурсах приложения. Кнопка butFilе запустит метод, который проигрывает аудиофайл.

Для того чтобы пример работал, понадобятся два звуковых файлов. В состав Windows XP входит несколько звуковых файлов. Для данного примера использовался файл chimes.wav. Его нужно добавить в проект. Чтобы включить файл chimes.wav в проект как ресурс, надо в свойствах файла выбрать пункт Build Action и установить значение Embedded Resource.

В качестве внешнего аудиофайла будет использоваться файл alarm3.wav, входящий в состав Windows Mobile. Этот файл находится в папке Windows. При желании можно использовать свой файл, но при этом надо в коде указать путь к нему. Теперь достаточно прописать код для обработки события Click созданных кнопок, как показано в листинге 13.11, — и приложение готово.

Листинг 13.11

using System;

using System.Collections.Generic;

using System.Text;

using System.IO;

using System.Runtime.InteropServices;


namespace PlaySound_CS {

 public class Sound {

  private byte[] m_soundBytes;

  private string m_fileName;

  private enum Flags {

   SND_SYNC = 0x0000,

   SND_ASYNC = 0x0001,

   SND_NODEFAULT = 0x0002,

   SND_MEMORY = 0x0004,

   SND_LOOP = 0x0008,

   SND_NOSTOP = 0x0010,

   SND_NOWAIT = 0x00002000,

   SND_ALIAS = 0x00010000,

   SND_ALIAS_ID = 0x00110000,

   SND_FILENAME = 0x00020000,

   SND_RESOURCE = 0x00040004

  }


  [DllImport("CoreDll.DLL", EntryPoint = "PlaySound", SetLastError = true)]

  private extern static int PlaySound(string szSound, IntPtr hMod, int flags);


  [DllImport("CoreDll.DLL", EntryPoint = "PlaySound", SetLastError = true)]

  private extern static int PlaySoundBytes(byte[] szSound, IntPtr hMod,

   int flags);


  ///

  /// Конструктор объекта Sound, который проигрывает звук из

  /// указанного файла

  ///

  public Sound(string fileName) {

   m_fileName = fileName;

  }


  ///

  /// Конструктор объекта Sound, который проигрывает звук из

  /// ресурсов

  ///

  public Sound(Stream stream) {

   // читаем данные из потока

   m_soundBytes = new byte[stream.Length];

   stream.Read(m_soundBytes, 0, (int)stream.Length);

  }


  ///

  /// Воспроизводим звук

  ///

  public void Play() {

   // Если из файла, то вызываем PlaySound.

   // если из ресурсов, то PlaySoundBytes.

   if (m_fileName != null)

    PlaySound(m_fileName, IntPtr.Zero,

     (int)(Flags.SND_ASYNC | Flags.SND_FILENAME));

   else

    PlaySoundBytes(m_soundBytes, IntPtr.Zero,

     (int)(Flags.SND_ASYNC | Flags.SND_MEMORY));

  }

 }

}

Теперь нужно перейти к самой форме. Код для нее приведен в листинге 13.12.

Листинг 13.12

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Reflection;


namespace PlaySound_CS {

 public partial class Form1 : Form {

Перейти на страницу:

Похожие книги

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных