首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

基於 libmad 的 MP3 解碼播放器實現 (MyMinimad.c)

     編輯:關於C語言

專案簡介

本程式改編自經典的 minimad 範例,目標是實現一個精簡的 MP3 解碼播放器,直接輸出 PCM 數據到聲音裝置 (/dev/dsp)。適合嵌入式 Linux 環境或學習音訊解碼流程的開發者參考。

編譯與執行指令

# 編譯 (需連結 libmad)
gcc MyMinimad.c -o MyMinimad -lmad -g -Wall

# 執行
./MyMinimad filename.mp3

核心架構說明

1. 數據結構設計

  • struct buffer:管理輸入緩衝區,包含起始指標 start 與剩餘長度 length。
  • static int sfd:聲音裝置檔案描述符 (/dev/dsp)。

2. 主流程

  1. 打開 MP3 檔案與聲音裝置。
  2. 使用 mmap 將整個檔案映射到記憶體,避免反覆 read 系統調用,提升效率。
  3. 呼叫 decode() 進入 libmad 解碼主循環。
  4. 解碼結束後釋放資源 (munmap, close)。

3. libmad 回調函數

libmad 採用回調模式,需實作三個核心回調:

  • input:向解碼器餵送數據。本例中直接將 mmap 後的記憶體區塊一次性傳給 mad_stream_buffer,後續不再提供數據 (length=0) 以結束串流。
  • output:處理解碼後的 PCM 采樣。此處將 mad_fixed_t 定點數轉為 16-bit 有號整數 (Little Endian),依聲道數交錯寫入輸出緩衝區,最後 write 到聲音裝置。注意:範例中採樣率乘 2 (speed = samplerate * 2) 可能為特定硬體調整,實際使用請依裝置規格設定。
  • error:錯誤處理,本例簡單返回 MAD_FLOW_CONTINUE 嘗試繼續解碼。

4. 關鍵轉換函數 scale()

static inline signed int scale(mad_fixed_t sample)
{
    // 四捨五入並飽和處理,轉為 16-bit 範圍
    sample += (1L << (MAD_F_FRACBITS - 16));
    if (sample >= MAD_F_ONE) sample = MAD_F_ONE - 1;
    else if (sample < -MAD_F_ONE) sample = -MAD_F_ONE;
    return sample >> (MAD_F_FRACBITS + 1 - 16);
}

完整代碼

[c]
/* MyMinimad.c - 2008/09/17 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/soundcard.h>
#include <sys/ioctl.h>
#include <sys/fcntl.h>
#include <sys/types.h>
#include <mad.h>

struct buffer {
    unsigned char const *start;
    unsigned long length;
};

static int sfd;
static int decode(unsigned char const *, unsigned long);

int main(int argc, char *argv[])
{
    struct stat stat;
    void *fdm;
    char const *file;
    int fd;

    file = argv[1];
    fd = open(file, O_RDONLY);
    if ((sfd = open("/dev/dsp", O_WRONLY)) < 0) {
        printf("can not open device!!!/n");
        return 5;
    }
    ioctl(sfd, SNDCTL_DSP_SYNC, 0);
    if (fstat(fd, &stat) == -1 || stat.st_size == 0) return 2;
    fdm = mmap(0, stat.st_size, PROT_READ, MAP_SHARED, fd, 0);
    if (fdm == MAP_FAILED) return 3;
    decode(fdm, stat.st_size);
    if (munmap(fdm, stat.st_size) == -1) return 4;
    ioctl(sfd, SNDCTL_DSP_RESET, 0);
    close(sfd);
    return 0;
}

static enum mad_flow input(void *data, struct mad_stream *stream)
{
    struct buffer *buffer = data;
    if (!buffer->length) return MAD_FLOW_STOP;
    mad_stream_buffer(stream, buffer->start, buffer->length);
    buffer->length = 0;
    return MAD_FLOW_CONTINUE;
}

static inline signed int scale(mad_fixed_t sample)
{
    sample += (1L << (MAD_F_FRACBITS - 16));
    if (sample >= MAD_F_ONE) sample = MAD_F_ONE - 1;
    else if (sample < -MAD_F_ONE) sample = -MAD_F_ONE;
    return sample >> (MAD_F_FRACBITS + 1 - 16);
}

static enum mad_flow output(void *data, struct mad_header const *header, struct mad_pcm *pcm)
{
    unsigned int nchannels, nsamples, n;
    mad_fixed_t const *left_ch, *right_ch;
    unsigned char Output[6912], *OutputPtr;
    int fmt, wrote, speed;

    nchannels = pcm->channels;
    n = nsamples = pcm->length;
    left_ch = pcm->samples[0];
    right_ch = pcm->samples[1];

    fmt = AFMT_S16_LE;
    speed = pcm->samplerate * 2;
    ioctl(sfd, SNDCTL_DSP_SPEED, &(speed));
    ioctl(sfd, SNDCTL_DSP_SETFMT, &fmt);
    ioctl(sfd, SNDCTL_DSP_CHANNELS, &(pcm->channels));

    OutputPtr = Output;
    while (nsamples--) {
        signed int sample;
        sample = scale(*left_ch++);
        *(OutputPtr++) = sample >> 0;
        *(OutputPtr++) = sample >> 8;
        if (nchannels == 2) {
            sample = scale(*right_ch++);
            *(OutputPtr++) = sample >> 0;
            *(OutputPtr++) = sample >> 8;
        }
    }
    n *= 4;
    OutputPtr = Output;
    while (n) {
        wrote = write(sfd, OutputPtr, n);
        OutputPtr += wrote;
        n -= wrote;
    }
    OutputPtr = Output;
    return MAD_FLOW_CONTINUE;
}

static enum mad_flow error(void *data, struct mad_stream *stream, struct mad_frame *frame)
{
    return MAD_FLOW_CONTINUE;
}

static int decode(unsigned char const *start, unsigned long length)
{
    struct buffer buffer;
    struct mad_decoder decoder;
    int result;
    buffer.start = start;
    buffer.length = length;
    mad_decoder_init(&decoder, &buffer, input, 0, 0, output, error, 0);
    mad_decoder_options(&decoder, 0);
    result = mad_decoder_run(&decoder, MAD_DECODER_MODE_SYNC);
    mad_decoder_finish(&decoder);
    return result;
}

遷移與優化建議

  • 現代 Linux 系統建議改用 ALSA (snd_pcm_* API) 或 PulseAudio/PipeWire 替代 OSS (/dev/dsp)。
  • 大檔案建議改用分塊讀取而非全檔 mmap,避免記憶體壓力。
  • 錯誤回調中可根據 stream->error 做更細緻的錯誤恢復 (如幀同步重試)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved