Repository navigation
Expand file tree
/
Copy pathAudioPlayer.cpp
More file actions
445 lines (375 loc) · 12.9 KB
/
Copy pathAudioPlayer.cpp
File metadata and controls
445 lines (375 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
/**
* @file AudioPlayer.cpp
* @brief 音频播放器实现,用于控制MAX98357A
*/
#include "AudioPlayer.h"
#include "SDCard.h"
#include "MP3Decoder.h"
#include "bflb_i2s.h"
#include "bflb_gpio.h"
#include "bflb_dma.h"
#include "bflb_mtimer.h"
#include "ff.h"
#include "stdio.h"
#include "string.h"
#include <vector>
#include <string>
// 定义I2S引脚
#define PIN_I2S_BCLK GPIO_PIN_16
#define PIN_I2S_LRCK GPIO_PIN_17
#define PIN_I2S_DIN GPIO_PIN_18
#define PIN_I2S_DOUT GPIO_PIN_19
// 定义音频缓冲区
#define AUDIO_BUFFER_SIZE 4096
static uint16_t audio_buffer[2][AUDIO_BUFFER_SIZE];
static int current_buffer = 0;
// 定义DMA和I2S设备
static struct bflb_device_s *i2s;
static struct bflb_device_s *dma_i2s_tx;
// 定义全局音频播放器实例
AudioPlayer* audioPlayer = nullptr;
// 存储音频文件列表
static std::vector<std::string> audioFiles;
// MP3解码器实例
static MP3Decoder mp3Decoder;
// 文件系统对象
static FIL audioFile;
// DMA传输完成回调
static void dma_i2s_tx_callback(void *arg)
{
// 切换缓冲区
current_buffer = 1 - current_buffer;
// 如果正在播放,读取下一块数据
if (audioPlayer && audioPlayer->isPlaying()) {
// 检查文件类型
const char *ext = strrchr(audioPlayer->currentFile, '.');
bool isMP3 = (ext && strcasecmp(ext, ".mp3") == 0);
if (isMP3) {
// MP3解码
int decoded = mp3Decoder.decode((int16_t*)audio_buffer[current_buffer], AUDIO_BUFFER_SIZE);
// 检查是否到达文件末尾或解码错误
if (decoded <= 0 || mp3Decoder.isEOF()) {
// 文件结束,检查是否需要循环播放
if (audioPlayer->isLoopMode) {
// 重置解码器并重新开始播放
mp3Decoder.reset();
decoded = mp3Decoder.decode((int16_t*)audio_buffer[current_buffer], AUDIO_BUFFER_SIZE);
if (decoded <= 0) {
// 解码失败,播放下一首
audioPlayer->playNext();
return;
}
} else {
// 播放下一首
audioPlayer->playNext();
return;
}
}
} else {
// WAV文件处理
UINT bytesRead;
f_read(&audioFile, audio_buffer[current_buffer], AUDIO_BUFFER_SIZE * 2, &bytesRead);
// 如果到达文件末尾,循环播放或停止
if (bytesRead < AUDIO_BUFFER_SIZE * 2) {
if (audioPlayer->isLoopMode) {
// 重新开始播放
f_lseek(&audioFile, 44); // 跳过WAV头
f_read(&audioFile, audio_buffer[current_buffer], AUDIO_BUFFER_SIZE * 2, &bytesRead);
} else {
// 播放下一首
audioPlayer->playNext();
return;
}
}
}
// 应用音量控制
uint8_t volume = audioPlayer->getVolume();
float volumeFactor = volume / 100.0f;
// 调整音量
for (int i = 0; i < AUDIO_BUFFER_SIZE; i++) {
audio_buffer[current_buffer][i] = (uint16_t)(audio_buffer[current_buffer][i] * volumeFactor);
}
}
// 启动下一次DMA传输
bflb_dma_channel_start(dma_i2s_tx);
}
// 音频播放器实现
AudioPlayer::AudioPlayer() : volume(50), _isPlaying(false), currentTrackIndex(0), totalTracks(0),
sample_rate(44100), channels(2), isLoopMode(false)
{
memset(currentFile, 0, sizeof(currentFile));
}
AudioPlayer::~AudioPlayer()
{
stop();
}
void AudioPlayer::init()
{
// 初始化I2S
i2s = bflb_device_get_by_name("i2s0");
// 配置I2S
struct bflb_i2s_config_s i2s_cfg = {
.bclk_freq_hz = 44100 * 32, // 44.1kHz采样率,32位
.role = I2S_ROLE_MASTER,
.format_mode = I2S_MODE_LEFT_JUSTIFIED,
.channel_mode = I2S_CHANNEL_MODE_NUM_2,
.frame_width = I2S_FRAME_WIDTH_16,
.data_width = I2S_DATA_WIDTH_16,
.fs_offset_cycle = 0,
};
bflb_i2s_init(i2s, &i2s_cfg);
// 配置I2S引脚
struct bflb_device_s *gpio = bflb_device_get_by_name("gpio");
bflb_gpio_init(gpio, PIN_I2S_BCLK, GPIO_FUNC_I2S | GPIO_ALTERNATE | GPIO_PULLUP | GPIO_SMT_EN | GPIO_DRV_2);
bflb_gpio_init(gpio, PIN_I2S_LRCK, GPIO_FUNC_I2S | GPIO_ALTERNATE | GPIO_PULLUP | GPIO_SMT_EN | GPIO_DRV_2);
bflb_gpio_init(gpio, PIN_I2S_DOUT, GPIO_FUNC_I2S | GPIO_ALTERNATE | GPIO_PULLUP | GPIO_SMT_EN | GPIO_DRV_2);
// 初始化DMA
dma_i2s_tx = bflb_device_get_by_name("dma0_ch0");
struct bflb_dma_channel_config_s dma_cfg = {
.direction = DMA_MEMORY_TO_PERIPH,
.src_req = DMA_REQUEST_NONE,
.dst_req = DMA_REQUEST_I2S_TX,
.src_addr_inc = DMA_ADDR_INCREMENT_ENABLE,
.dst_addr_inc = DMA_ADDR_INCREMENT_DISABLE,
.src_burst_count = DMA_BURST_INCR1,
.dst_burst_count = DMA_BURST_INCR1,
.src_width = DMA_DATA_WIDTH_16BIT,
.dst_width = DMA_DATA_WIDTH_16BIT,
};
bflb_dma_channel_init(dma_i2s_tx, &dma_cfg);
bflb_dma_channel_irq_attach(dma_i2s_tx, dma_i2s_tx_callback, NULL);
// 扫描音频文件
scanAudioFiles();
// 设置默认音量
setVolume(50);
printf("Audio Player initialized\n");
}
void AudioPlayer::scanAudioFiles()
{
// 清空文件列表
audioFiles.clear();
// 打开根目录
DIR dir;
FILINFO fno;
FRESULT res;
res = f_opendir(&dir, "/music");
if (res != FR_OK) {
// 如果music目录不存在,尝试创建
res = f_mkdir("/music");
if (res != FR_OK) {
printf("Failed to create music directory\n");
return;
}
res = f_opendir(&dir, "/music");
if (res != FR_OK) {
printf("Failed to open music directory\n");
return;
}
}
// 遍历目录
while (1) {
res = f_readdir(&dir, &fno);
if (res != FR_OK || fno.fname[0] == 0) {
break; // 读取完毕或出错
}
// 检查是否是MP3文件
if (!(fno.fattrib & AM_DIR)) {
char *ext = strrchr(fno.fname, '.');
if (ext && (strcasecmp(ext, ".mp3") == 0 || strcasecmp(ext, ".wav") == 0)) {
char fullPath[128];
sprintf(fullPath, "/music/%s", fno.fname);
audioFiles.push_back(fullPath);
}
}
}
f_closedir(&dir);
// 更新总曲目数
totalTracks = audioFiles.size();
printf("Found %d audio files\n", totalTracks);
}
void AudioPlayer::play(const char* filename)
{
// 停止当前播放
stop();
// 保存当前文件名
strncpy(currentFile, filename, sizeof(currentFile) - 1);
// 检查文件类型
const char *ext = strrchr(filename, '.');
bool isMP3 = false;
if (ext && strcasecmp(ext, ".mp3") == 0) {
isMP3 = true;
}
if (isMP3) {
// MP3文件处理
if (!mp3Decoder.open(filename)) {
printf("Failed to open MP3 file: %s\n", filename);
return;
}
// 获取MP3文件信息
sample_rate = mp3Decoder.getSampleRate();
channels = mp3Decoder.getChannels();
// 更新I2S配置以匹配MP3采样率
struct bflb_i2s_config_s i2s_cfg = {
.bclk_freq_hz = sample_rate * 16 * 2, // 采样率 * 位宽 * 声道数
.role = I2S_ROLE_MASTER,
.format_mode = I2S_MODE_LEFT_JUSTIFIED,
.channel_mode = channels == 1 ? I2S_CHANNEL_MODE_NUM_1 : I2S_CHANNEL_MODE_NUM_2,
.frame_width = I2S_FRAME_WIDTH_16,
.data_width = I2S_DATA_WIDTH_16,
.fs_offset_cycle = 0,
};
bflb_i2s_init(i2s, &i2s_cfg);
// 解码第一帧数据填充缓冲区
int decoded = mp3Decoder.decode((int16_t*)audio_buffer[0], AUDIO_BUFFER_SIZE);
if (decoded <= 0) {
printf("Failed to decode MP3 data\n");
mp3Decoder.close();
return;
}
// 解码第二帧
decoded = mp3Decoder.decode((int16_t*)audio_buffer[1], AUDIO_BUFFER_SIZE);
if (decoded <= 0) {
// 如果只有一帧数据,复制到第二个缓冲区
memcpy(audio_buffer[1], audio_buffer[0], AUDIO_BUFFER_SIZE * 2);
}
} else {
// WAV文件处理
FRESULT res = f_open(&audioFile, filename, FA_READ);
if (res != FR_OK) {
printf("Failed to open audio file: %s\n", filename);
return;
}
// 跳过WAV文件头
// 这里简化处理,实际应该解析文件头
f_lseek(&audioFile, 44); // 跳过WAV头
// 读取初始数据
UINT bytesRead;
f_read(&audioFile, audio_buffer[0], AUDIO_BUFFER_SIZE * 2, &bytesRead);
f_read(&audioFile, audio_buffer[1], AUDIO_BUFFER_SIZE * 2, &bytesRead);
}
// 应用音量控制
float volumeFactor = volume / 100.0f;
for (int i = 0; i < AUDIO_BUFFER_SIZE; i++) {
audio_buffer[0][i] = (uint16_t)(audio_buffer[0][i] * volumeFactor);
audio_buffer[1][i] = (uint16_t)(audio_buffer[1][i] * volumeFactor);
}
// 配置DMA传输
struct bflb_dma_channel_lli_pool_s lli[1];
struct bflb_dma_channel_lli_transfer_s transfers[1];
transfers[0].src_addr = (uint32_t)audio_buffer[0];
transfers[0].dst_addr = (uint32_t)&i2s->base->fifo_wdata;
transfers[0].nbytes = AUDIO_BUFFER_SIZE * 2;
bflb_dma_channel_lli_reload(dma_i2s_tx, lli, 1, transfers, 1);
bflb_dma_channel_start(dma_i2s_tx);
// 启动I2S传输
bflb_i2s_link_txdma(i2s, true);
bflb_i2s_enable(i2s);
// 设置播放状态
_isPlaying = true;
printf("Playing: %s (SR: %d, CH: %d)\n", filename, sample_rate, channels);
}
void AudioPlayer::playByIndex(int index)
{
if (index >= 0 && index < totalTracks) {
currentTrackIndex = index;
play(audioFiles[index].c_str());
}
}
void AudioPlayer::pause()
{
if (_isPlaying) {
// 暂停I2S传输
bflb_i2s_disable(i2s);
_isPlaying = false;
printf("Playback paused\n");
}
}
void AudioPlayer::resume()
{
if (!_isPlaying) {
// 恢复I2S传输
bflb_i2s_enable(i2s);
_isPlaying = true;
printf("Playback resumed\n");
}
}
void AudioPlayer::stop()
{
if (_isPlaying) {
// 停止I2S传输
bflb_i2s_disable(i2s);
bflb_i2s_link_txdma(i2s, false);
// 检查文件类型
const char *ext = strrchr(currentFile, '.');
bool isMP3 = (ext && strcasecmp(ext, ".mp3") == 0);
if (isMP3) {
// 关闭MP3解码器
mp3Decoder.close();
} else {
// 关闭WAV文件
f_close(&audioFile);
}
_isPlaying = false;
printf("Playback stopped\n");
}
}
void AudioPlayer::setVolume(uint8_t vol)
{
// 限制音量范围
if (vol > 100) {
vol = 100;
}
volume = vol;
printf("Volume set to %d%%\n", volume);
// 如果正在播放,应用新的音量
// 注意:这里不会立即改变当前正在播放的音频,
// 而是在下一个DMA传输开始时应用新的音量
}
uint8_t AudioPlayer::getVolume()
{
return volume;
}
void AudioPlayer::nextTrack()
{
if (totalTracks > 0) {
currentTrackIndex = (currentTrackIndex + 1) % totalTracks;
play(audioFiles[currentTrackIndex].c_str());
}
}
void AudioPlayer::prevTrack()
{
if (totalTracks > 0) {
currentTrackIndex = (currentTrackIndex + totalTracks - 1) % totalTracks;
play(audioFiles[currentTrackIndex].c_str());
}
}
void AudioPlayer::playNext()
{
if (totalTracks > 0) {
currentTrackIndex = (currentTrackIndex + 1) % totalTracks;
playByIndex(currentTrackIndex);
}
}
void AudioPlayer::playPrev()
{
if (totalTracks > 0) {
currentTrackIndex = (currentTrackIndex - 1 + totalTracks) % totalTracks;
playByIndex(currentTrackIndex);
}
}
bool AudioPlayer::isPlaying()
{
return _isPlaying;
}
const char* AudioPlayer::getCurrentFile()
{
return currentFile;
}
int AudioPlayer::getCurrentTrackIndex()
{
return currentTrackIndex;
}
int AudioPlayer::getTotalTracks()
{
return totalTracks;
}