note:使用ffmpeg库对mp3文件进行解码,然后使用alsa库进行播放解码后的数据。
暂停/播放的核心是使用互斥锁加上条件变量阻塞进程,从而实现暂停/播放的效果,至于执行相应的歌曲模式选择在循环中判断读取数据是否完毕,完毕则执行相应的歌曲操作。以下为c语言例程源码。
#include <alsa/asoundlib.h>
#include <libavformat/avformat.h>
#include <libswresample/swresample.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#define PCM_DEVICE "default"
#define MAX_SONGS 3
// Song playlist
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: Single play, 1: Repeat single, 2: Repeat playlist
int is_paused = 0;
int stop_playback = 0;
int is_playing = 0;
//int64_t pause_pts = 0; // Track the position where playback was paused
pthread_mutex_t mutex;
pthread_cond_t cond;
pthread_t play_thread;
snd_pcm_t *pcm_handle;
AVFormatContext *format_ctx = NULL;
AVCodecContext *codec_ctx = NULL;
struct SwrContext *swr_ctx = NULL;
int audio_stream_index = -1;
AVPacket packet;
void *play_song_thread(void *arg);
// Cleanup resources
void cleanup() {
if (swr_ctx) {
swr_free(&swr_ctx);
}
if (codec_ctx) {
avcodec_free_context(&codec_ctx);
}
if (format_ctx) {
avformat_close_input(&format_ctx);
}
if (pcm_handle) {
snd_pcm_close(pcm_handle);
}
av_packet_unref(&packet);
}
// Setup ALSA
int setup_alsa(int rate, int channels) {
snd_pcm_hw_params_t *params;
int err;
if ((err = snd_pcm_open(&pcm_handle, PCM_DEVICE, SND_PCM_STREAM_PLAYBACK, 0)) < 0) {
fprintf(stderr, "Unable to open PCM device: %s\n", snd_strerror(err));
return -1;
}
snd_pcm_hw_params_alloca(¶ms);
snd_pcm_hw_params_any(pcm_handle, params);

最低0.47元/天 解锁文章
4035

被折叠的 条评论
为什么被折叠?



