Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_for_Beginners.doc
Скачиваний:
28
Добавлен:
23.11.2019
Размер:
2.4 Mб
Скачать

Добавление файлов мультимедиа в приложение

Чтобы усовершенствовать приложения, в них можно добавить компоненты мультимедиа, например аудио-, видео- и графические файлы. В этом разделе содержатся ссылки на разделы, описывающие типовые задачи программирования по добавлению файлов мультимедиа в приложение.

Внедрение проигрывателя Windows Media в форму

Для добавления мультимедийных возможностей в приложение в форму Windows можно внедрить проигрыватель Windows Media. Сначала элемент управления "Windows Media Player COM" необходимо добавить на панель элементов, а затем — в приложение.

Добавление элемента управления "Windows Media Player" в панель элементов.

  1. В меню Файл выберите команду Создать проект.

  2. В диалоговом окне Создание проекта выберите Приложение Windows Forms, а затем нажмите кнопку ОК.

Откроется новый проект Windows Forms.

  1. Щелкните правой кнопкой мыши панель элементов и выберите пункт Выбрать элементы.

    Примечание.

    Если панель элементов не отображается, в меню Вид выберите пункт Панель элементов.

  2. Откроется диалоговое окно Настройка элементов панели элементов.

  3. На вкладке Компоненты COM установите флажок Проигрыватель Windows Media и нажмите кнопку ОК.

  4. На текущей вкладке Панель элементов появится элемент управления "Windows Media Player".

При добавлении элемента управления "Windows Media Player" на панель элементов Visual Studio автоматически добавляет ссылки на две библиотеки: AxWMPLib и WMPLib. Следующим этапом является добавление элемента управления в форму Windows Forms.

To add the Windows Media Player control to a Windows Form

  1. Drag the Windows Media Player control from the Toolbox to the Windows Form.

  2. In the Properties window, set the Dock property to Fill. You can do this by clicking the center square.

  3. Double-click the title bar of the form to add the default Load event in the Code Editor.

  4. Add the following code to the Form_Load event handler to load a video when the application opens.

    Note:

    The path used is a forward link that points to an on-line video. You can change the path and file name to display a different video.

    axWindowsMediaPlayer1.URL =

    @"http://go.microsoft.com/fwlink/?LinkId=95772";

  5. This code sets the URL of the Windows Media Player to the media file that you have specified. Windows Media Player will automatically start to play when you set the URL property because the autoStart property is true by default.

  6. Press F5 to run the code.

  7. When the application opens, change the size of the form to full-screen by double-clicking the title bar of the form.

Добавление элемента управления "Windows Media Player" в форму Windows Forms

  1. Перетащите элемент управления "Windows Media Player" из панели элементов в форму Windows Forms.

  2. В окне Свойства установите свойству Закрепить значение Заполнить. Для этого щелкните центральный квадрат.

  3. Дважды щелкните строку заголовка формы, чтобы добавить событие Load по умолчанию в редакторе кода.

  4. Добавьте в обработчик событий Form_Load следующий код, обеспечивающий загрузку видео при открытии приложения.

    Примечание.

    В качестве пути используется прямая ссылка, указывающая на видеоматериалы в Интернете. Для отображения других видеоматериалов путь и имя файла можно изменить.

    axWindowsMediaPlayer1.URL =

    "http://go.microsoft.com/fwlink/?LinkId=95772";

  5. В этом коде в проигрывателе Windows Media задается URL-адрес указанного медиафайла. При установке свойства URL проигрыватель Windows Media автоматически начнет воспроизведение, поскольку свойство autoStart имеет значение "true" по умолчанию.

  6. Нажмите клавишу F5 для выполнения кода.

  7. В открывшемся приложении измените размер формы на полноэкранный, дважды щелкнув строку заголовка формы.

How to: Play Sounds in an Application

You can add sound to your application by using the System.Media namespace. System sounds, such as a beep, can be played by using System.Media.SystemSounds.Beep.Play(); in an application.

You can also play specific audio files. The following example shows you how to play a waveform audio file that the user has selected.

To play an audio file

  1. On the File menu, click New Project.

  2. In the New Project dialog box, click Windows Forms Application, and then click OK.

A new Windows Forms project opens.

  1. Drag a Button control from the Toolbox to the Windows Form.

  2. Double-click the button to create the default Click event handler, and add the following code. This code displays the File Open dialog box and passes the results to a method named playSound that you will create in the next step.

    OpenFileDialog dialog = new OpenFileDialog();

    dialog.Filter = "Audio Files (.wav)|*.wav";

    if(dialog.ShowDialog() == DialogResult.OK)

    {

    string path = dialog.FileName;

    playSound(path);

    }

  3. Add the following method code under the button1_Click event hander.

    private void playSound(string path)

    {

    System.Media.SoundPlayer player =

    new System.Media.SoundPlayer();

    player.SoundLocation = path;

    player.Load();

    player.Play();

    }

  4. Press F5 to run the code.

  5. Click the button and select an audio file. After the file loads, the sound will play.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]