如何用C语言让计算机发声
时间: 2024-04-01 18:33:23 浏览: 16
要使用C语言让计算机发声,需要调用相应的库函数,下面是两种方法:
1. 使用Windows.h库中的Beep函数
Windows.h库中的Beep函数可以用来发出简单的蜂鸣声,其原型如下:
```c
BOOL Beep(
DWORD dwFreq, // 指定声音的频率,单位为赫兹(Hz)
DWORD dwDuration // 指定声音的持续时间,单位为毫秒(ms)
);
```
调用该函数可以让计算机发出指定频率和持续时间的声音,例如:
```c
#include <windows.h>
int main()
{
Beep(1000, 1000); // 发出频率为1000Hz,持续1秒的声音
return 0;
}
```
2. 使用alsa/asoundlib.h库中的snd_pcm_writei函数
如果需要更为复杂的声音效果,可以使用alsa/asoundlib.h库中的snd_pcm_writei函数,该函数可以控制声卡输出音频流。需要注意的是,该函数的使用需要安装alsa驱动和库,而且需要在Linux系统下运行。
下面是一个使用snd_pcm_writei函数输出正弦波的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <alsa/asoundlib.h>
#define PI 3.14159265358979323846
int main()
{
int err;
snd_pcm_t *handle; // 声卡句柄
snd_pcm_hw_params_t *params; // 声卡参数结构体
unsigned int val;
int dir;
snd_pcm_uframes_t frames;
char *buffer;
int freq = 440; // 发声频率
int duration = 1000; // 发声持续时间,单位为毫秒
int sample_rate = 44100; // 采样率
int amplitude = 16384; // 振幅
// 打开默认声卡设备
err = snd_pcm_open(&handle, "default", SND_PCM_STREAM_PLAYBACK, 0);
if (err < 0) {
printf("Error opening PCM device: %s\n", snd_strerror(err));
exit(1);
}
// 分配并初始化声卡参数结构体
snd_pcm_hw_params_alloca(¶ms);
snd_pcm_hw_params_any(handle, params);
snd_pcm_hw_params_set_access(handle, params, SND_PCM_ACCESS_RW_INTERLEAVED);
snd_pcm_hw_params_set_format(handle, params, SND_PCM_FORMAT_S16_LE);
snd_pcm_hw_params_set_channels(handle, params, 1);
val = sample_rate;
snd_pcm_hw_params_set_rate_near(handle, params, &val, &dir);
frames = 32;
snd_pcm_hw_params_set_period_size_near(handle, params, &frames, &dir);
err = snd_pcm_hw_params(handle, params);
if (err < 0) {
printf("Error setting HW params: %s\n", snd_strerror(err));
exit(1);
}
// 生成正弦波数据并输出
int num_samples = sample_rate * duration / 1000;
buffer = (char*) malloc(num_samples * 2); // 16-bit signed PCM数据
int i;
for (i = 0; i < num_samples; i++) {
double angle = 2.0 * PI * freq * i / sample_rate;
short sample = (short) (amplitude * sin(angle));
buffer[i*2] = (char)sample;
buffer[i*2+1] = (char)(sample >> 8);
}
snd_pcm_writei(handle, buffer, num_samples);
// 关闭声卡设备
snd_pcm_drain(handle);
snd_pcm_close(handle);
free(buffer);
return 0;
}
```
该程序的作用是输出一个持续1秒钟、频率为440Hz的正弦波声音。