note:前面的播放/暂停都是使用互斥锁加条件变量阻塞线程,现在播放/暂停是结束线程,记录暂停的位置,播放时从暂停的位置继续播放。关键点在于记录暂停位置的函数pause_position = mpg123_tell(mh);播放重新定位到这个位置:mpg123_seek(mh, pause_position, SEEK_SET);
以下为我的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;
off_t pause_position = 0; // 记录暂停位置
// 清理函数,释放资源
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_INT