c语言怎么对音频进行采样并存到数组中,能 举个例子嘛
时间: 2023-06-06 17:05:39 浏览: 98
对音频进行采样,可以使用C语言中的音频库,例如PortAudio,将音频输入设定为麦克风或者其他音源,然后通过代码实现采样并存储到数组中。以下是一个简单的例子:
```c
#include <stdio.h>
#include <stdlib.h>
#include "portaudio.h"
#define NUM_SECONDS 5
#define SAMPLE_RATE 44100
#define FRAMES_PER_BUFFER 64
#define NUM_CHANNELS 1
#define DITHER_FLAG 0
typedef struct
{
float *samples;
int currentIndex;
}
paTestData;
static paTestData data;
static int recordCallback(const void *inputBuffer, void *outputBuffer,
unsigned long framesPerBuffer,
const PaStreamCallbackTimeInfo *timeInfo,
PaStreamCallbackFlags statusFlags,
void *userData )
{
float *input = (float*)inputBuffer;
paTestData *data = (paTestData*)userData;
int i;
for (i=0; i<framesPerBuffer; i++) {
data->samples[data->currentIndex++] = *input++;
}
return paContinue;
}
int main(int argc, char *argv[])
{
PaStream *stream;
PaError err;
data.samples = (float*)malloc(NUM_SECONDS * SAMPLE_RATE * sizeof(float));
data.currentIndex = 0;
err = Pa_Initialize();
if( err != paNoError ) goto error;
err = Pa_OpenDefaultStream( &stream,
NUM_CHANNELS,
0,
paFloat32,
SAMPLE_RATE,
FRAMES_PER_BUFFER,
recordCallback,
&data );
if( err != paNoError ) goto error;
err = Pa_StartStream( stream );
if( err != paNoError ) goto error;
printf("\n=== recording ===\n"); fflush(stdout);
Pa_Sleep(NUM_SECONDS*1000);
err = Pa_StopStream( stream );
if( err != paNoError ) goto error;
err = Pa_CloseStream( stream );
if( err != paNoError ) goto error;
Pa_Terminate();
printf("Finished.\n");
return 0;
error:
Pa_Terminate();
fprintf(stderr, "An error occured while using the portaudio stream\n");
fprintf(stderr, "Error number: %d\n", err);
fprintf(stderr, "Error message: %s\n", Pa_GetErrorText(err));
return -1;
}
```
这段代码会录制5秒钟的音频,将它存储到一个数组中data.samples,并作为回调函数recordCallback的参数传入。可以根据需要修改参数,例如改变录音时长、采样率等。
阅读全文