note:使用ffmpeg库解码mp3文件,使用alsa播放解码后的数据。
与上一篇不同的是这个播放/暂停的核心是记录暂停解码的pts,重新播放时从暂停的pts开始解码,暂停就是结束线程,播放就是开始线程,至于其他部分跟上一篇一致,本文不做描述,以下为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>
#include <sys/prctl.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;
// 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);
snd_pcm_hw_params_set_access(pcm_handle, params, SND_PCM_ACCESS_RW_INTERLEAVE