note:使用多线程的方式MP3实现播放器,其中用到libmpg123,以及asound库,解码用到libmpg123,播放用到alsa,以下为c语言例程源码
#include <alsa/asoundlib.h>
#include <mpg123.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <signal.h>
#define PCM_DEVICE "default"
#define MAX_SONGS 3
// 歌曲列表
char *songs[MAX_SONGS] = {
"/mnt/hgfs/share/talk_anymore.mp3",
"/mnt/hgfs/share/poxiao.mp3",
"/mnt/hgfs/share/attention.mp3"
};
int current_song = 0;
int play_mode = 0; // 0: 单曲播放, 1: 单曲循环, 2: 列表循环
int is_paused = 0; // 播放暂停标志
int stop_playback = 0; // 停止播放标志
int is_playing = 0; // 是否正在播放标志
char *music_mode[3]={"单曲模式","单曲循环","列表循环"};
pthread_mutex_t mutex;
pthread_cond_t cond;
mpg123_handle *mh;
snd_pcm_t *pcm_handle;
pthread_t play_thread;
// 清理函数,释放资源
void cleanup() {
if (mh) {
mpg123_close(mh);
mpg123_delete(mh);
}
if (pcm_handle) {
snd_pcm_close(pcm_handle);
}
mpg123_exit();
}
// 设置ALSA设备
int setup_alsa(int rate, int channels) {
int err;
snd_pcm_hw_params_t *params;
if ((err = snd_pcm_open(&pcm_handle, PCM_DEVICE, SND_PCM_STREAM_PLAYBACK, 0)) < 0) {
fprintf(stderr, "无法打开PCM设备 %s: %s\n", PCM_DEVICE, snd_strerror(err));
return -1;
}
snd_pcm_hw_params_alloca(¶ms);
snd_pcm_hw_params_any(pcm_handle, params);
snd_pcm_hw_params_set_access(pcm_handle, params, SND_PCM_ACCESS_RW_INTERLEAVED);
snd_pcm_hw_params_set_format(pcm_handle, params, SND_PCM_FORMAT_S16_LE);