How to: Use Platform Invoke to Play a Wave File 


Мы поможем в написании ваших работ!



ЗНАЕТЕ ЛИ ВЫ?

How to: Use Platform Invoke to Play a Wave File



The following C# code example illustrates how to use platform invoke services to play a wave sound file on the Windows operating system.

Example

This example code uses DllImport to import winmm.dll's PlaySound method entry point as Form1 PlaySound(). The example has a simple Windows Form with a button. Clicking the button opens a standard windows OpenFileDialog dialog box so that you can open a file to play. When a wave file is selected, it is played by using the PlaySound() method of the winmm.DLL assembly method. For more information about winmm.dll's PlaySound method, see Using PlaySound to Play Waveform-Audio Files. Browse and select a file that has a.wav extension, and then click Open to play the wave file by using platform invoke. A text box shows the full path of the file selected.

The Open Files dialog box is filtered to show only files that have a.wav extension through the filter settings:

dialog1.Filter = "Wav Files (*.wav)|*.wav";

 


Взаимодействие

Возможность взаимодействия позволяет использовать существующие вложения в неуправляемый код. Код, находящийся под управлением среды CLR, называется управляемым кодом, а код, выполняемый вне этой среды, называется неуправляемым. Примерами неуправляемого программного кода могут служить компоненты COM, COM+, C++, ActiveX и Win32 API.

Платформа.NET Framework обеспечивает взаимодействие с неуправляемым кодом посредством служб вызова платформ, пространства имен System.Runtime.InteropServices, а также CLR посредством модуля COM Interoperability (COM-взаимодействие).

Использование вызова неуправляемого кода для воспроизведения звукового файла

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

Пример

В данном примере кода DllImport используется для импорта точки входа метода PlaySound winmm.dll в качестве Form1 PlaySound(). В примере используется простая форма Windows с кнопкой. При нажатии кнопки открывается стандартное диалоговое окно Windows OpenFileDialog, в котором можно выбрать воспроизводимый файл. Когда звуковой файл выбран, он воспроизводится с помощью метода PlaySound() из метода сборки winmm.DLL. Дополнительные сведения о методе PlaySound winmm.dll см. в разделе Using PlaySound to Play Waveform-Audio Files. Найдите и выберите файл с расширением.wav, а затем нажмите кнопку Открыть для воспроизведения звукового файла с помощью вызова неуправляемого кода. В текстовом поле отображается полный путь к выбранному файлу.

В диалоговом окне Открытые файлы отображаются только файлы, имеющие расширение.wav, так как в нем действуют параметры фильтра:

dialog1.Filter = "Wav Files (*.wav)|*.wav";

 


 

using System.Windows.Forms;

 

namespace WinSound

{

public partial class Form1: Form

{

private TextBox textBox1;

private Button button1;

public Form1() //constructor

{

InitializeComponent();

}

[System.Runtime.InteropServices.DllImport("winmm.DLL", EntryPoint = "PlaySound", SetLastError = true)]

private static extern bool PlaySound(string szSound, System.IntPtr hMod, PlaySoundFlags flags);

 

[System.Flags]

public enum PlaySoundFlags: int

{

SND_SYNC = 0x0000,

SND_ASYNC = 0x0001,

SND_NODEFAULT = 0x0002,

SND_LOOP = 0x0008,

SND_NOSTOP = 0x0010,

SND_NOWAIT = 0x00002000,

SND_FILENAME = 0x00020000,

SND_RESOURCE = 0x00040004

}

 

private void button1_Click (object sender, System.EventArgs e)

{

OpenFileDialog dialog1 = new OpenFileDialog();

 

dialog1.Title = "Browse to find sound file to play";

dialog1.InitialDirectory = @"c:\";

dialog1.Filter = "Wav Files (*.wav)|*.wav";

dialog1.FilterIndex = 2;

dialog1.RestoreDirectory = true;

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

{

textBox1.Text = dialog1.FileName;

PlaySound (dialog1.FileName, new System.IntPtr(), PlaySoundFlags.SND_SYNC);

}

}

}

}


 

ß---


Compiling the Code

To compile the code

1. Create a new C# Windows Application project in Visual Studio and name it WinSound.

2. Copy the code above, and paste it over the contents of the Form1.cs file.

3. Copy the following code, and paste it in the Form1.Designer.cs file, in the InitializeComponent() method, after any existing code.

this.button1 = new System.Windows.Forms.Button(); this.textBox1 = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // button1 // this.button1.Location = new System.Drawing.Point(192, 40); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(88, 24); this.button1.TabIndex = 0; this.button1.Text = "Browse"; this.button1.Click += new System.EventHandler(this.button1_Click); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(8, 40); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(168, 20); this.textBox1.TabIndex = 1; this.textBox1.Text = "FIle path"; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(5, 13); this.ClientSize = new System.Drawing.Size(292, 266); this.Controls.Add(this.textBox1); this.Controls.Add(this.button1); this.Name = "Form1"; this.Text = "Platform Invoke WinSound C#"; this.ResumeLayout(false); this.PerformLayout();

4. Compile and run the code.

 


Компиляция кода



Поделиться:


Последнее изменение этой страницы: 2017-01-19; просмотров: 117; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 3.16.70.101 (0.007 с.)