代码改变世界

简单的音频函数 PlaySound[原创]

2006-10-22 14:35  老博客哈  阅读(3570)  评论(1编辑  收藏  举报

要学音频, 得从基础抓起。。。

--------------------------------------------------------------------------------

首先得说起大家可能都在Console下面听到的一个声音, 嘟。。。

对,就是它, 转义字符'\a', 也就是Ctrl+G/g。

好了, 弄一小段程序测试下吧。

 

 Console.WriteLine("Enter Ctrl + g");//按下键盘的Ctrl键和G字母就可以了
 int s = Console.Read();//这个读取字符'\a'
 Console.ReadLine();//这个读取末尾的'\n'
 Console.WriteLine((char)s);

 

好了, 听到嘟的一声没阿, 呵呵。

下面再看几个API了

第一个见面的是Beep, 嘿嘿, 金山词霸对它的解释就是

beep
[bi:p]
n.
哔哔声
v.
嘟嘟响

知道大概什么意思了吧。

好了, 为了更清楚地表述这个API的用途,我就把MSDN里面的解释给搬过来了哈。

Beep

The Beep function generates simple tones on the speaker. The function is synchronous; it performs an alertable wait and does not return control to its caller until the sound finishes.

BOOL Beep(
  DWORD dwFreq,
  DWORD dwDuration
);

Parameters

dwFreq
[in] Frequency of the sound, in hertz. This parameter must be in the range 37 through 32,767 (0x25 through 0x7FFF).
Windows Me/98/95:  The Beep function ignores this parameter.
dwDuration
[in] Duration of the sound, in milliseconds.
Windows Me/98/95:  The Beep function ignores this parameter.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

Muting and volume control have no effect on Beep; you will still hear the tone. To silence the tone, use the following commands:

net stop beep
sc config beep start=disabled

Terminal Services:  The beep is redirected to the client.
Windows Me/98/95:  On computers with a sound card, the function plays the default sound event. On computers without a sound card, the function plays the standard system beep.

Example Code [C++]

The following example demonstrates the use of this function.

Beep( 750, 300 );

Requirements

Client Requires Windows XP, Windows 2000 Professional, Windows NT Workstation, Windows Me, Windows 98, or Windows 95.
Server Requires Windows Server 2003, Windows 2000 Server, or Windows NT Server.
Header

Declared in Winbase.h; include Windows.h.

Library

Link to Kernel32.lib.

DLL Requires Kernel32.dll.

说的已经非常清楚了, 我也没有必要多说什么了阿。

不知道大家是否知道在C#中如何使用API, 我就稍微的啰嗦一下了哈。

首先引入名字空间

 

using System.Runtime.InteropServices;//这个是为了使用DllImport

 

好了下面用上

 

[DllImport("Kernel32.dll")]
        
public static extern bool Beep(int dwFreq, int dwDuration);

 

DllImport 这个东东偶也说一下, 貌似是个叫什么特性的东东。去摘下MSDN

The extern modifier is used to declare a method that is implemented externally. A common use of the extern modifier is with the DllImport attribute when using Interop services to call into unmanaged code; in this case, the method must also be declared as static, as shown in the following example:

 
[DllImport("avifil32.dll")]
private static extern void AVIFileInit();
Note

The extern keyword also can define an external assembly alias, making it possible to reference different versions of the same component from within a single assembly. For more information, see extern alias (C# Reference).

It is an error to use the abstract (C# Reference) and extern modifiers together to modify the same member. Using the extern modifier means that the method is implemented outside the C# code, while using the abstract modifier means that the method implementation is not provided in the class.

The extern keyword is more limited in use than in C++. To compare with the C++ keyword, see Using extern to Specify Linkage in the C++ Language Reference.

In this example, the program receives a string from the user and displays it inside a message box. The program uses the MessageBox method imported from the User32.dll library.

 
using System;
using System.Runtime.InteropServices;
class MainClass 
{
    [DllImport("User32.dll")]
    public static extern int MessageBox(int h, string m, string c, int type);

    static int Main() 
    {
        string myString; 
        Console.Write("Enter your message: ");
        myString = Console.ReadLine();
        return MessageBox(0, myString, "My Message Box", 0);
    }
}

Example 2

This example creates an external DLL that is invoked from within the C# program in Example 3.

 
// cmdll.c
// compile with: /LD /MD
int __declspec(dllexport) SampleMethod(int i)
{
    return i*10;
}

Example 3

This example uses two files, CM.cs and Cmdll.c, to demonstrate extern. The C file is the external DLL created in Example 2 that is invoked from within the C# program.

 
// cm.cs
using System;
using System.Runtime.InteropServices;
public class MainClass 
{
    [DllImport("Cmdll.dll")]
    public static extern int SampleMethod(int x);
    static void Main() 
    {
        Console.WriteLine("SampleMethod() returns {0}.", 
                SampleMethod(5));
    }
}

Output

 
SampleMethod() returns 50.

Remarks

To build the project:

  • Compile Cmdll.c to a DLL using the Visual C++ command line:

    cl /LD /MD Cmdll.c

  • Compile CM.cs using the command line:

    csc CM.cs

This will create the executable file CM.exe. When you run this program, SampleMethod will pass the value 5 to the DLL file, which returns the value multiplied by 10.

C# Language Specification

For more information, see the following sections in the C# Language Specification:

  • 10.5.7 External methods

 

说的真是太好了,这个我就不说了。

 

            while (true)
            
{
                Console.WriteLine(
"Please enter Frequency of the sounds:");
                
int freq = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine(
"Please duration of the sound, in milliseconds:");
                
int dur = Convert.ToInt32(Console.ReadLine());
                Beep(freq, dur);
            }

 

去感受一下声音吧。

其实 .net里面Console下面已经有了Beep函数了哈,嘿嘿 , 没有早告诉点, 不然

不会有这么多麻烦事。

 

using System;
using System.Collections.Generic;
using System.Text;

namespace SoundPlaying
{
    
class Program
    
{
        
static void Main(string[] args)
        
{
            Console.Beep();
            
while (true)
            
{
                Console.WriteLine(
"Please enter Frequency of the sounds:");
                
int freq = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine(
"Please duration of the sound, in milliseconds:");
                
int dur = Convert.ToInt32(Console.ReadLine());
                Console.Beep(freq, dur);
            }

        }

    }

}


和上面的效果一样了哈。

最后使用的API 就是 PlaySound

同样的,我去摘MSDN了(不要砸我啊)

PlaySound

The PlaySound function plays a sound specified by the given filename, resource, or system event. (A system event may be associated with a sound in the registry or in the WIN.INI file.)

BOOL PlaySound(
  LPCSTR pszSound,  
  HMODULE hmod,     
  DWORD fdwSound    
);

Parameters

pszSound

A string that specifies the sound to play. The maximum length, including the null terminator, is 256 characters. If this parameter is NULL, any currently playing waveform sound is stopped. To stop a non-waveform sound, specify SND_PURGE in the fdwSound parameter.

Three flags in fdwSound (SND_ALIAS, SND_FILENAME, and SND_RESOURCE) determine whether the name is interpreted as an alias for a system event, a filename, or a resource identifier. If none of these flags are specified, PlaySound searches the registry or the WIN.INI file for an association with the specified sound name. If an association is found, the sound event is played. If no association is found in the registry, the name is interpreted as a filename.

hmod

Handle to the executable file that contains the resource to be loaded. This parameter must be NULL unless SND_RESOURCE is specified in fdwSound.

fdwSound

Flags for playing the sound. The following values are defined.

Value Meaning
SND_APPLICATION The sound is played using an application-specific association.
SND_ALIAS The pszSound parameter is a system-event alias in the registry or the WIN.INI file. Do not use with either SND_FILENAME or SND_RESOURCE.
SND_ALIAS_ID The pszSound parameter is a predefined sound identifier.
SND_ASYNC The sound is played asynchronously and PlaySound returns immediately after beginning the sound. To terminate an asynchronously played waveform sound, call PlaySound with pszSound set to NULL.
SND_FILENAME The pszSound parameter is a filename.
SND_LOOP The sound plays repeatedly until PlaySound is called again with the pszSound parameter set to NULL. You must also specify the SND_ASYNC flag to indicate an asynchronous sound event.
SND_MEMORY A sound event's file is loaded in RAM. The parameter specified by pszSound must point to an image of a sound in memory.
SND_NODEFAULT No default sound event is used. If the sound cannot be found, PlaySound returns silently without playing the default sound.
SND_NOSTOP The specified sound event will yield to another sound event that is already playing. If a sound cannot be played because the resource needed to generate that sound is busy playing another sound, the function immediately returns FALSE without playing the requested sound.

If this flag is not specified, PlaySound attempts to stop the currently playing sound so that the device can be used to play the new sound.

SND_NOWAIT If the driver is busy, return immediately without playing the sound.
SND_PURGE Sounds are to be stopped for the calling task. If pszSound is not NULL, all instances of the specified sound are stopped. If pszSound is NULL, all sounds that are playing on behalf of the calling task are stopped.

You must also specify the instance handle to stop SND_RESOURCE events.

SND_RESOURCE The pszSound parameter is a resource identifier; hmod must identify the instance that contains the resource.
SND_SYNC Synchronous playback of a sound event. PlaySound returns after the sound event completes.

Return Values

Returns TRUE if successful or FALSE otherwise.

Remarks

The sound specified by pszSound must fit into available physical memory and be playable by an installed waveform-audio device driver. PlaySound searches the following directories for sound files: the current directory; the Windows directory; the Windows system directory; directories listed in the PATH environment variable; and the list of directories mapped in a network. For more information about the directory search order, see the documentation for the OpenFile function.

If it cannot find the specified sound, PlaySound uses the default system event sound entry instead. If the function can find neither the system default entry nor the default sound, it makes no sound and returns FALSE.

Windows 95/98/Me: PlaySoundW is supported by the Microsoft Layer for Unicode. To use this, you must add certain files to your application, as outlined in Microsoft Layer for Unicode on Windows 95/98/Me Systems.

Requirements

  Windows NT/2000/XP: Included in Windows NT 3.1 and later.
  Windows 95/98/Me: Included in Windows 95 and later.
  Header: Declared in Mmsystem.h; include Windows.h.
  Library: Use Winmm.lib.
  Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000/XP. Also supported by Microsoft Layer for Unicode.

有件很麻烦的事就是这些宏, 其实他们是一些数字了, 但是要在C#

里面用, 可不能再这样了, 用一个const表示下吧,可是到底这些

宏代表什么呢?我当时是建了一个VC的Win32 Application 项目

然后写出宏, 把鼠标移上去看它代表的数字。

唉, 真够烦的阿, 不知道有什么好的方法, 还望过路大下侠指导一下。

 

 

        public const int SND_FILENAME = 0x00020000;
        
public const int SND_ASYNC = 0x0001;

[DllImport(
"winmm.dll")]
        
public static extern bool PlaySound(string pszSound, int hmod, int fdwSound);

PlaySound(
"clock.wav"0, SND_FILENAME | SND_ASYNC);

 

Ok, 就可以听到了音乐了阿。

注: .Net FrameWork 2.0 当中System.Media下 有个SoundPlayer也可以哦!