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

本文介绍了基本的声音编程技巧,包括使用转义字符、Beep API及PlaySound API生成和播放声音的方法。此外,还提供了C#中调用这些API的具体示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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

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

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

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

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

 

None.gif Console.WriteLine("Enter Ctrl + g");//按下键盘的Ctrl键和G字母就可以了
None.gif
 int s = Console.Read();//这个读取字符'\a'
None.gif
 Console.ReadLine();//这个读取末尾的'\n'
None.gif
 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 ,
  DWORD 
);
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, 我就稍微的啰嗦一下了哈。

首先引入名字空间

 

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

 

好了下面用上

 

None.gif[DllImport("Kernel32.dll")]
None.gif        
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 <?XML:NAMESPACE PREFIX = MSHelp NS = "http://msdn.microsoft.com/mshelp" /> 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

 

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

 

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

 

去感受一下声音吧。

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

不会有这么多麻烦事。

 

None.gifusing System;
None.gif
using System.Collections.Generic;
None.gif
using System.Text;
None.gif
None.gif
namespace SoundPlaying
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
class Program
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
static void Main(string[] args)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Console.Beep();
InBlock.gif            
while (true)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                Console.WriteLine(
"Please enter Frequency of the sounds:");
InBlock.gif                
int freq = Convert.ToInt32(Console.ReadLine());
InBlock.gif                Console.WriteLine(
"Please duration of the sound, in milliseconds:");
InBlock.gif                
int dur = Convert.ToInt32(Console.ReadLine());
InBlock.gif                Console.Beep(freq, dur);
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
None.gif

和上面的效果一样了哈。

最后使用的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 MeaningSND_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 项目

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

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

 

 

None.gif        public const int SND_FILENAME = 0x00020000;
None.gif        
public const int SND_ASYNC = 0x0001;
None.gif
None.gif[DllImport(
"winmm.dll")]
None.gif        
public static extern bool PlaySound(string pszSound, int hmod, int fdwSound);
None.gif
None.gifPlaySound(
"clock.wav"0, SND_FILENAME | SND_ASYNC);
None.gif

 

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

注: .Net FrameWork 2.0 当中System.Media下 有个SoundPlayer也可以哦!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值