在C 语言中使用SoX播放文件

编程语言 2026-07-08

我正在尝试编写一个应用程序,用sox找到一个文件、打开并播放,但我在让任何输出出现方面遇到了困难。我按照并修改了我在这里找到的几个示例 这里这里,但没有任何东西在播放。我需要在主函数中创建实例并传递几个指针,并在一个函数中添加实际的数据文件,但这与主示例相比,我真正改动的也就这么多。我在下面的代码中放入了一个示例文件来测试该函数,而不是进行搜索。除非需要一个效果才能让它工作,否则我不想以任何方式改变输入文件。

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#include "sox.h"

typedef struct State {
    sox_format_t *sox_in;
    sox_format_t *sox_out;
    sox_effects_chain_t *sox_chain;

} State;


State *sm;

void init_player(sox_format_t* sxin, sox_format_t* sxout, sox_effects_chain_t* sxchain)
{
    sm  = (struct State*)malloc(sizeof(struct State));
    sm->sox_in = sxin;
    sm->sox_out = sxout;
    sm->sox_chain = sxchain;
}

void play(State* s)
{
    sm->sox_in = sox_open_read("/home/me/Music/sox_out1.flac", NULL, NULL, NULL);
    printf("successful read\n");
    sm->sox_in = sox_open_write("default", &(sm->sox_in)->signal, NULL, "alsa", NULL, NULL);
    printf("successful write\n");
    sm->sox_chain = sox_create_effects_chain(&(sm->sox_in)->encoding, &(sm->sox_out)->encoding);
    printf("chain created\n");
    printf("starting to flow effects\n");           
    sox_flow_effects(sm->sox_chain, NULL, NULL);
    printf("successful flow\n"); 
    sox_delete_effects_chain(sm->sox_chain);
    sox_close(sm->sox_out);
    sox_close(sm->sox_in);
}


int main() {
    static sox_format_t *in, *out; /* input and output files */
    static sox_effects_chain_t *chain;

    assert(sox_init() == SOX_SUCCESS);

    init_player(in, out, chain);

    play(sm);
}

解决方案

好吧,如果你的目标只是播放你在C 代码中使用的那个文件,即 /home/me/Music/sox_out1.flac,那么要达到你想要的结果,你在 play() 函数中的代码缺少对 sox_write() 的使用。

下面是一个修改过的 void play(State *s) 函数,用来播放所需的文件:

void play(State* s)
{
    sm->sox_in = sox_open_read("/home/me/Music/sox_out1.flac", NULL, NULL, NULL);
    printf("successful read\n");
    sm->sox_out = sox_open_write("default", &(sm->sox_in)->signal, NULL, "alsa", NULL, NULL);
    printf("successful write\n");
    sm->sox_chain = sox_create_effects_chain(&(sm->sox_in)->encoding, &(sm->sox_out)->encoding);
    printf("chain created\n");
    printf("starting to flow effects\n");           
    sox_flow_effects(sm->sox_chain, NULL, NULL);
    printf("successful flow\n"); 

    sox_sample_t buffer[16];
    size_t samples_read;

    while ((samples_read = sox_read(sm->sox_in, buffer, 16)) > 0) {
        sox_write(sm->sox_out, buffer, samples_read);
    }

    sox_delete_effects_chain(sm->sox_chain);
    sox_close(sm->sox_out);
    sox_close(sm->sox_in);
}

请注意,我仅聚焦在你问题中的第一句话上

我正在尝试编写一个应用程序,找到一个文件,打开并使用sox播放,但我在让任何输出产生方面遇到了困难。

据此,我提出了解决方案。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章