无法识别的音乐格式,使用SDL播放mp3文件

时间:2012-12-18 06:24:50

标签: c linux sdl

#include <SDL/SDL.h>
#include <SDL/SDL_mixer.h>
#include <stdio.h>
#include <stdlib.h>
Mix_Music *play_sound = NULL;
void cleanUp();

int main(int argc, char* args[])
{

    int channel;
    int audio_rate;
    Uint16 audio_format;
    int audio_channels;
    int audio_buffers;

        if(SDL_Init(SDL_INIT_AUDIO)<0)
        printf("Error In Init");

    audio_rate = 44100;
    audio_format = AUDIO_S16;
    audio_channels = 2;
    audio_buffers = 4096;


    if(Mix_OpenAudio(audio_rate, audio_format, 2, 4096)<0) {
                 //Some error shows here

    } else {
        Mix_QuerySpec(&audio_rate, &audio_format, &audio_channels);
        printf("Opened audio at %d Hz %d bit %s (%s), %d bytes audio buffer\n", audio_rate,
                (audio_format&0xFF),
                (audio_channels > 2) ? "surround" :                         (audio_channels > 1) ? "stereo" : "mono", 
                (audio_format&0x1000) ? "BE" : "LE",
                audio_buffers );
    }

    play_sound = Mix_LoadMUS("1.mp3");

    if ( play_sound == NULL ) {
        fprintf(stderr, "Couldn't load 1.mp3: %s\n",
            SDL_GetError());
        cleanUp();
        return;
    }

        Mix_PlayMusic(play_sound, -1);


    while (Mix_PlayingMusic() || Mix_PausedMusic()) {
            SDL_Delay(100);
        }

        cleanUp();
        return 0;
}

void cleanUp()
{
     Mix_FreeMusic(play_sound);
     Mix_CloseAudio();
     SDL_Quit();
}

这是我的输出:

Opened audio at 44100 Hz 16 bit stereo (LE), 4096 bytes audio buffer
Couldn't load 1.mp3: Unrecognised music format

有谁能告诉我用SDL播放mp3文件有什么问题?

2 个答案:

答案 0 :(得分:1)

它默认支持WAV文件,但是你需要SMPEG库以及一些更复杂的代码行来使mp3工作。几年前我遇到了同样的问题,通过各种论坛发现mp3很棘手。我最终将我的文件转换为OGG,这非常直接。

答案 1 :(得分:1)

这是一个小小的足迹!!!

#include <stdio.h>
#include <stdlib.h>
#include <SDL/SDL.h>
#include <smpeg/smpeg.h>
#include <dirent.h>

int main(int argc, char * argv[])
{
  SDL_Surface * screen;
  SMPEG *mpeg;
  SMPEG_Info info;

  /* Init SDL: */

  SDL_Init(SDL_INIT_VIDEO |
           SDL_INIT_AUDIO);

  mpeg = SMPEG_new("1.mp3",&info, 1);

  SMPEG_play(mpeg);

  do
    {
      SDL_Delay(250);
    }while(!SDL_QuitRequested() && SMPEG_status(mpeg)==SMPEG_PLAYING);

  SMPEG_delete(mpeg);
  SDL_Quit();

  return(0);
}

使用

进行编译
gcc `sdl-config --cflags --libs` sample.c -o sample -lSDL_mixer -lsmpeg