我正在尝试使用以下代码行录制音频:
// The sample type to use
static const pa_sample_spec ss = {
.format = PA_SAMPLE_S32LE , //PA_SAMPLE_S16BE, ??? Which one to us here ??? BE...Big Endian
.rate = 44100, // That are samples per second
.channels = 2
};
// Create the recording stream
// see: http://freedesktop.org/software/pulseaudio/doxygen/parec-simple_8c-example.html
if (!(s = pa_simple_new(NULL, "Record", PA_STREAM_RECORD, NULL, "record", &ss, NULL, NULL, &error))) {
fprintf(stderr, __FILE__": pa_simple_new() failed: %s\n", pa_strerror(error));
pa_simple_free(s);
exit(EXIT_FAILURE);
}
int i = -1;
while (!exit_program) {
i = (i+1) % BUFNUMBER;
pthread_mutex_lock(&(buffer[i].write));
// Record data and save it to the buffer
if (pa_simple_read(s, buffer[i].buf, sizeof(buffer[i].buf), &error) < 0) {
fprintf(stderr, __FILE__": pa_simple_read() failed: %s\n", pa_strerror(error));
pa_simple_free(s);
exit(EXIT_FAILURE);
}
// unlock the reading mutex
pthread_mutex_unlock(&(buffer[i].read)); // open up for reading
}
如您所见,我将读取的字节存储在一个名为 buffer 的结构中,如下所示:
#define BUFSIZE 44100 // Size of one element
#define BUFNUMBER 16 // Number of elements
#define AUDIO_BUFFER_FORMAT char
// one element of the ringbuffer
typedef struct ringbuf {
AUDIO_BUFFER_FORMAT buf[BUFSIZE]; /* The buffer array */
pthread_mutex_t read; /* indicates if block was read */
pthread_mutex_t write; /* for locking writing */
} ringbuffer_element;
另一个线程尝试读取和播放存储在缓冲区中的字节:
// The sample type to use
static const pa_sample_spec ss = {
.format = PA_SAMPLE_S32LE , //PA_SAMPLE_S16BE,
.rate = 44100,
.channels = 2
};
if (stream == NULL) {
if (!(stream = pa_simple_new(NULL, "Stream", PA_STREAM_PLAYBACK, NULL, "playback", &ss, NULL, NULL, &error))) {
fprintf(stderr, __FILE__": pa_simple_new() failed: %s\n", pa_strerror(error));
return false;
}
}
if (pa_simple_write(stream, buf, (size_t) size, &error) < 0) {
fprintf(stderr, __FILE__": pa_simple_write() failed: %s\n", pa_strerror(error));
pa_simple_free(stream);
return false;
}
/* Make sure that every single sample was played */
if (pa_simple_drain(stream, &error) < 0) {
fprintf(stderr, __FILE__": pa_simple_drain() failed: %s\n", pa_strerror(error));
pa_simple_free(stream);
return false;
}
但是,我测试了缓冲区的实现,效果很好。尽管如此,我唯一能听到的就是噪音。所以我想知道,如果我需要转换字节才能再次播放它们,以便听起来像录音。
此外,我找不到我的声卡等的任何数据表。我必须转换字节还是可以按录制的方式播放它们?我使用的格式是否破坏了某些东西?
我真的被困在这里了。希望你们能帮助我。
编辑:还有一个问题:如果我使用 ALSA API 为了我的目的更接近硬件会更好吗?是的,我对声音编程完全陌生。