美文网首页
c语言调用PulseAudio播放音乐

c语言调用PulseAudio播放音乐

作者: 一路向后 | 来源:发表于2025-04-18 22:23 被阅读0次

1.源码实现

#include <pulse/simple.h>
#include <pulse/error.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int main()
{
    //配置音频参数
    const pa_sample_spec ss = {
        .format = PA_SAMPLE_S16LE,
        .rate = 44100,
        .channels = 2
    };

    //创建PulseAudio简单连接
    pa_simple *s = NULL;
    int error;

    if (!(s=pa_simple_new(
        NULL,
        "Example",
        PA_STREAM_PLAYBACK,
        NULL,
        "Test Tone",
        &ss,
        NULL,
        NULL,
        &error
    )))
    {
        fprintf(stderr, "pa_simple_new failed: %s\n", pa_strerror(error));

        return 1;
    }

    //生成1秒440Hz正弦波
    const int duration_sec = 1;
    const int buf_size = ss.rate * duration_sec * pa_sample_size(&ss);
    int16_t *buffer = malloc(buf_size*sizeof(int16_t));
    const double freq = 440.0;
    int i;

    for (i=0; i<ss.rate * duration_sec; i++)
    {
        double t = (double)i / ss.rate;
        double val = sin(t * freq * 2 * M_PI) * 0.5;

        buffer[2*i] = buffer[2*i+1] = val * INT16_MAX;
    }

    //写入音频数据
    if (pa_simple_write(s, buffer, buf_size, &error) < 0)
    {
        fprintf(stderr, "pa_simple_write() failed: %s\n", pa_strerror(error));

        pa_simple_free(s);
        free(buffer);

        return 1;
    }

    //等待播放完成
    if (pa_simple_drain(s, &error) < 0)
    {
        fprintf(stderr, "pa_simple_drain failed: %s\n", pa_strerror(error));

        pa_simple_free(s);
        free(buffer);

        return 1;
    }

    //清理资源
    pa_simple_free(s);
    free(buffer);

    return 0;
}

2.编译源码

$ g++ -g -o pa_simple pa_simple.c -lpulse-simple -lpulse

相关文章

  • C语言:播放音乐

    代码实例 1: 只限 mp3、wav、avi 代码实例 2: 只限 wav 编译:

  • 今日用C语言做个小东西,新手福利呦,模拟登陆验证,加音乐播放

    今日用C语言做个小东西,新手福利呦,模拟登陆验证,加音乐播放 主要内容 小编推荐一个学C语言/C++的学习裙【 六...

  • unity 调用objective-c 播放音乐

  • cgo

    cgo cgo是用来在Go语言中调用C语言的工具 Go语言调用C语言 简单C语言函数 在Go语言中需要通过impo...

  • Go调用C/C++

    cgo golang是类C的语言 支持调用C接口(不支持调用C++)Go调用C/C++的方式 : C : 直接调用...

  • ARM汇编语言与C语言混合编程(part1)

    汇编语言调用C语言 题目:用汇编语言调用C语言实现21!(21的阶乘) 实验软件:ARM Developer Su...

  • C++ 调用Python3

    作为一种胶水语言,Python 能够很容易地调用 C 、 C++ 等语言,也能够通过其他语言调用 Python 的...

  • C++基础教程

    C++是一种通用编程语言。 C++可以创建计算机程序。从应用程序,音乐播放器,甚至视频游戏它都可以胜任。 C ++...

  • Runtime之消息发送

    调用对象的方法,在Objective-C中叫做传递消息,先来看一下C语言中的函数调用方式 C语言中的函数调用方式 ...

  • AudioToolbox

    AudioToolbox这个库是C的接口,偏向于底层,用于在线流媒体音乐的播放,可以调用该库的相关接口自己封装一个...

网友评论

      本文标题:c语言调用PulseAudio播放音乐

      本文链接:https://www.haomeiwen.com/subject/ytypbjtx.html