반응형

SDL 기본 라이브러리는 WAV 형식의 오디오만 처리할 수 있다. mp3, ogg 등의 형식을 처리하기 위해서는 SDL_mixer 라이브러리가 필요하다.

 

우선 SDL 기본 라이브러리로 WAV 사운드를 출력해 보자.

 

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
#include <iostream>
#include "SDL.h"
 
#pragma comment(lib, "sdl2.lib")
#pragma comment(lib, "sdl2main.lib")
 
int main(int argc, char* argv[]) {
    SDL_Init(SDL_INIT_AUDIO);
 
    SDL_AudioSpec wav_spec;
    Uint8* wav_buffer;
    Uint32 wav_length;
 
    if (SDL_LoadWAV("sound.wav"&wav_spec, &wav_buffer, &wav_length) == NULL) {
        // Use this function to load a WAVE from a file.
        printf("SDL_LoadWAV Error: %s\n", SDL_GetError());
        return -1;
    }
 
    int bitDepth = SDL_AUDIO_BITSIZE(wav_spec.format);
    int bytesPerSecond = (bitDepth * wav_spec.channels * wav_spec.freq) / 8;
    float durationSec = (float)wav_length / bytesPerSecond;
    printf("Duration: %f\n", durationSec);
    // wav 파일 재생 시간 구하기.
 
    SDL_AudioDeviceID dev = SDL_OpenAudioDevice(NULL0&wav_spec, NULL0);
    // Open a specific audio device.
    if (dev == NULL) {
        printf("SDL_AudioDeviceID Error: %s\n", SDL_GetError());
        return -1;
    }
 
    if (SDL_QueueAudio(dev, wav_buffer, wav_length) != 0) {
        // Queue more audio on non-callback devices.
        printf("SDL_QueueAudio Error: %s\n", SDL_GetError());
        return -1;
    }
 
    SDL_PauseAudioDevice(dev, 0);
    // Use this function to pause and unpause audio playback on a specified device.
    // dev: a device opened by SDL_OpenAudioDevice()
    // pause_on: non-zero to pause, 0 to unpause
    SDL_Delay(durationSec * 1000);
    // Wait a specified number of milliseconds before returning.
 
    SDL_FreeWAV(wav_buffer);
    // Free data previously allocated with SDL_LoadWAV() or SDL_LoadWAV_RW().
    SDL_CloseAudioDevice(dev);
    //Use this function to shut down audio processing and close the audio device.
    SDL_Quit();
 
    return 0;
}
 

 

코드를 작성하고 빌드한다.

 

실행하면 재생 시간이 표시되고 사운드가 출력된다.

 

※ 참고

SDL_AudioFormat

 

이번엔 SDL_mixer를 이용해 mp3, ogg 등의 사운드를 출력해 보자. 아래 링크에서 SDL_mixer를 다운받고 적당히 설치한다.

SDL Libraries

 

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
#include <iostream>
#include "SDL.h"
#include "SDL_mixer.h"
 
#pragma comment(lib, "sdl2.lib")
#pragma comment(lib, "sdl2main.lib")
#pragma comment(lib, "sdl2_mixer.lib")
 
int main(int argc, char* argv[]) {
    SDL_Init(SDL_INIT_AUDIO);
 
    if (Mix_OpenAudio(48000, MIX_DEFAULT_FORMAT, 22048!= 0) {
        // Open the default audio device for playback.
        printf("Mix_OpenAudio Error: %s\n", Mix_GetError());
        return -1;
    }
 
    Mix_Music* music = Mix_LoadMUS("sound.mp3");
    // Load a supported audio format into a music object.
    if (music == NULL) {
        printf("Mix_LoadMUS Error: %s\n", Mix_GetError());
        return -1;
    }
    printf("Duration: %f\n", Mix_MusicDuration(music));
    // Get a music object's duration, in seconds.
 
    Mix_PlayMusic(music, 0);
    // Play a new music object. (0 means "play once and stop")
    SDL_Delay(int(Mix_MusicDuration(music) * 1000));
 
    Mix_FreeMusic(music);
    // Free a music object. If this music is currently playing,
    // it will be stopped.
    Mix_CloseAudio();
    // Close the mixer, halting all playing audio.
 
    SDL_Quit();
 
    return 0;
}
 

 

코드를 작성하고 빌드한다.

 

실행하면 재생시간이 표시되고 사운드가 출력된다.

 

※ 참고

SDL_mixer API

 

반응형
Posted by J-sean
:
반응형

C#에서 Windows Media Player를 이용해 오디오 파일을 플레이 해 보자.

 

아래 링크를 참고해 Windows Media Player COM Component를 가져오고 빌드시 메세지가 발생하지 않도록 하자.

(Windows Media Player 컴포넌트를 폼에 배치할 필요는 없다)

2021.11.21 - [C#] - C# Windows Media Player Audio/Video Play #1

 

폼과 버튼을 적당히 배치한다.

 

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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
using WMPLib;
 
namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private string time;
 
        WindowsMediaPlayer wmp;
 
        public Form1()
        {
            InitializeComponent();
            
            wmp = new WindowsMediaPlayer();
 
            Timer T = new Timer();
            T.Interval = 1000;
            T.Tick += new EventHandler(Form1_Timer);
            T.Start();
        }
 
        private void Form1_Timer(object sender, System.EventArgs e)
        {
            if (wmp.playState == WMPPlayState.wmppsPlaying)
            {
                //time = wmp.controls.currentPositionString + " / " + wmp.controls.currentItem.durationString;
                //time = wmp.controls.currentPosition.ToString() + " / " + wmp.controls.currentItem.duration.ToString();
                time = TimeSpan.FromSeconds((int)wmp.controls.currentPosition).ToString() + " / "
                    + TimeSpan.FromSeconds((int)wmp.controls.currentItem.duration);
 
                Graphics G = CreateGraphics();
                //G.DrawString(time, Font, System.Drawing.Brushes.Black, 20, 70); // 글자가 겹친다.
                TextRenderer.DrawText(G, time, Font, new Point(2070), ForeColor, BackColor);
                G.Dispose();
            }
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog dlg = new OpenFileDialog();
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    wmp.URL = dlg.FileName;
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }
 
        private void button2_Click(object sender, EventArgs e)
        {
            if (wmp.playState == WMPPlayState.wmppsPlaying)
            {
                wmp.controls.stop();
            }
        }
    }
}
 

 

소스를 입력한다.

 

오디오/비디오 파일을 플레이 할 수 있다. (비디오 파일은 오디오만 출력된다)

실행 파일과 함께 Interop.WMPLib.dll 파일이 존재해야 한다.

 

Using the Windows Media Player Control in a .NET Framework Solution

 

반응형
Posted by J-sean
:
반응형

 

2021.11.21 - [C#] - C# Windows Media Player Audio/Video Play #2

 

C#에서 Windows Media Player를 이용해 오디오/비디오 파일을 플레이 해 보자.

 

Toolbox의 원하는 곳에서 우클릭 - Choose Items...

 

COM Components - Windows Media Player 선택.

 

폼, 버튼, Windows Media Player를 적당히 배치한다.

 

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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
using WMPLib;
 
namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog dlg = new OpenFileDialog();
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    axWindowsMediaPlayer1.URL = dlg.FileName;
                    axWindowsMediaPlayer1.Ctlcontrols.stop();   // 자동 재생 방지.
                    // The managed-code wrapper for the Windows Media Player control exposes
                    // the Controls object as Ctlcontrols to avoid collision with the Controls
                    // property inherited from System.Windows.Forms.Control.
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }
    }
}
 

 

소스를 입력한다.

 

 

이대로 빌드해도 문제는 없지만 위와 같은 메세지가 나온다.

 

References - WMPLib - Properties - Embed Interop Types - False 선택

다시 빌드하면 아무 메세지도 나오지 않는다.

 

MP3등 오디오 파일 재생.

 

AVI, MP4등 비디오 파일 재생.

 

 

이번엔 실행하면 아무것도 보이지 않다가 오디오/비디오 파일을 선택하면 UI없이 플레이 하는 프로그램을 만들어 보자.

 

폼, 버튼, Windows Media Player를 배치한다.

 

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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
using WMPLib;
 
namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
 
            axWindowsMediaPlayer1.Visible = false;
            axWindowsMediaPlayer1.uiMode = "none";
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog dlg = new OpenFileDialog();
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    axWindowsMediaPlayer1.URL = dlg.FileName;
                    axWindowsMediaPlayer1.Visible = true;
                }
            } catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }
 
        private void button2_Click(object sender, EventArgs e)
        {
            if (axWindowsMediaPlayer1.playState == WMPPlayState.wmppsPlaying)
            {
                axWindowsMediaPlayer1.Ctlcontrols.stop();
                // The managed-code wrapper for the Windows Media Player control exposes
                // the Controls object as Ctlcontrols to avoid collision with the Controls
                // property inherited from System.Windows.Forms.Control.
                
                axWindowsMediaPlayer1.Visible = false;
            }            
        }
    }
}
 

 

소스를 입력하고 빌드한다.

 

WMP가 보이지 않는다. Play 버튼을 클릭하고 비디오 파일을 선택한다.

 

비디오가 UI없이 플레이된다.

 

실행 파일과 함께 Interop.WMPLib.dll 파일이 존재해야 한다.

 

Using the Windows Media Player Control in a .NET Framework Solution

 

반응형
Posted by J-sean
:

C# Media Player Mp3

C# 2021. 11. 21. 13:27 |
반응형

C#에서 MP3파일을 플레이 해 보자.

 

Solution Explorer - References 우클릭 - Add Reference... 클릭

 

PresentationCore 선택.

 

WindowsBase 선택.

 

폼과 버튼을 적당히 배치한다.

 

 

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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
using System.Windows.Media;
 
namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        enum STATE {PLAYING, STOPPED, PAUSED }
 
        STATE state;
        private string time;
 
        MediaPlayer MP;
 
        public Form1()
        {
            InitializeComponent();
 
            state = STATE.STOPPED;
            MP = new MediaPlayer();
 
            Timer T = new Timer();
            T.Interval = 1000;
            T.Tick += new EventHandler(Form1_Timer);
            T.Start();            
        }
 
        private void Form1_Timer(object sender, System.EventArgs e)
        {
            if (state == STATE.PLAYING && MP.NaturalDuration.HasTimeSpan)
            {
                time = MP.Position.ToString(@"hh\:mm\:ss"+ " / "
                    + MP.NaturalDuration.TimeSpan.ToString(@"hh\:mm\:ss");
 
                Graphics G = CreateGraphics();
                //G.DrawString(time, Font, System.Drawing.Brushes.Black, 20, 90); // 글자가 겹친다.
                TextRenderer.DrawText(G, time, Font, new Point(2090), ForeColor, BackColor);
                G.Dispose();
            }            
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog dlg = new OpenFileDialog();
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    MP.Open(new Uri(dlg.FileName));
                    MP.Play();
                    state = STATE.PLAYING;
                }
            } catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }            
        }
 
        private void button2_Click(object sender, EventArgs e)
        {
            MP.Stop();
            MP.Close();
            state = STATE.STOPPED;
        }
    }
}
 

 

소스를 입력한다.

 

프로그램을 실행하고 파일을 선택하면 플레이 된다.

 

반응형
Posted by J-sean
:
반응형

아래 링크의 제품과 거의 같지만 조금 더 심플한 MP3 디코더다. 


2020/11/29 - [Review] - MP3 Decoder with Built-in Amplifier Module


스위치나 터미널이 달려 있지 않아 그냥 사용하기 불편할 수 있지만 원하는 형태의 MP3 플레이어를 만들기는 더 좋다.


Micro SD카드 슬롯만 있는 작고 간단한 형태의 MP3 디코더 보드.


Pin assignment


1. V33REG DVDD33: Digital power 3.3V.

2. V50REG VMCU/BAT: Lithium battery input, 3.3V~5V.

3. VSSREG DVSS: Digital ground.

4. DACOL DACL: Left audio signal output.

5. VCOM: Center audio signal Vref, please plug 1uF capacitor voltage.

6. DACOR DACR: Right channel audio output.

7. LINEIN_R LineInR + L: LineIn left + right input.

8. IOA4: AD-key buttons.

9. IOA3 FMCLK: If IOA3 pull-down resistor to ground, IOA3 will output clock signal to the outside Hanging FM radio IC. If IOA3 is vacant, FM radio IC will take their 32768Hz crystal.

10. IOA2 Mute: Mute the external amplifier.

11. DM: USB of DM.

12. DP: USB of DP.

13. IOA0: IO-key/LED.

(1) Plug-in LED light: Output “1” represents the lit LED.

(2) IO-key1.

(3) Options are used to define the key mode.

14. IOB1 SD_CLK: Clock output T card/SD card. SD_DET: detecting whether there is an SD card is inserted, to read “0” on behalf of insertion. Please connect a 3.3KΩ resistance.

15. IOB0 SD_CMD: T card/SD card command and response. I2C_CLK: I2C the clock; the external EEPROM, and FM.

16. IOB2 SD_DAT: data input T card/SD Card/output. I2C_DAT: I2C of data; and external EEPROM FM.


3.7V 배터리나 (USB)5V 전원으로 작동 가능하며 Micro SD 카드에 듣고 싶은 음악을 담아 플레이 할 수 있다. 위 다이어그램과 같이 스위치와 4Ω 3W 스피커를 연결해 사용한다.


■ Previous/Volume--: 이전 곡 / 길게 누르면(약 2초) 소리 작게

■ Play/Stop: 플레이 / 정지

■ Next/Volume++: 다음 곡 / 길게 누르면 소리 크게


반응형
Posted by J-sean
:
반응형

컴퓨터에 사운드 카드가 기본 사양이 되기 전, 큰 결심을 하고서야 구입할 수 있었던 옥소리나 사운드 블래스터등의 고가 사운드 카드를 컴퓨터에 설치하고 듣던 게임 음악은 정말 놀라웠다. 삐~ 소리만 나는 줄 알았던 컴퓨터에서 이런 소리가 날 수 있다니..


옥소리(사운드 카드)를 광고하는 옥소리(배우)


옥소리 사운드 카드


그리고는 MP3로 대표되는 여러가지 오디오 압축 포맷 덕분에 작은 용량으로도 많은 노래를 저장할 수 있게 되었고 컴퓨터가 아닌 작은 기기에서도 노래를 재생할 수 있는 플레이어들이 등장하기 시작했다. 물론 저렴한 가격은 아니었던거 같다.


최초의 MP3 플레이어


지금은 중국에서 한국까지 오는 배송비를 포함해도 천원이 조금 넘는 저렴한 가격에 MP3 디코더를 구입해 직접 간단한 MP3 플레이어를 만들 수 있다.



앰프가 포함된 MP3 디코더


알리 익스프레스에서는 Nondestructive Decoder Board 라는 이름으로 판매되고 있다. 왜 nondestructive 일까.. 무슨 의미로 nondestructive를 붙인걸까.. 알 수가 없다.


어쨌든 USB 2.0 type A, Micro 5 pin, 또는 3.7~5.5V 배터리로 작동 가능하며 Micro SD 카드에 듣고 싶은 음악을 담아 플레이 할 수 있다. 3.5mm 이어폰 잭을 연결하거나 4Ω 3W의 스피커를 연결해 듣는다.


■ Prev/V--: 이전 곡 / 길게 누르면(약 2초) 소리 작게

■ Next/V++: 다음 곡 / 길게 누르면 소리 크게

■ P/P/Mode: 플레이 / 정지, 길게 누르면 U Disk, Micro SD 카드 전환 (U Disk는 5V 전원 필요)

■ Repeat: 1곡 반복 / 전체 반복


U Disk를 지원한다고 적혀 있어서 FAT, FAT32 파일 시스템으로 포맷한 USB 드라이브에 음악음 담아 시도해 봤지만 플레이 되지 않았다. Micro SD 카드는 문제없이 플레이 되었다.


간단한 MP3 플레이어가 필요한 경우 유용하게 사용할 수 있을거 같다.


※ 참고: 2020/12/09 - [Review] - MP3 Decoder with Built-in Amplifier Module (GPD2846A)


반응형
Posted by J-sean
:
반응형

DFPlayer Mini MP3 Player For Arduino를 이용해 아두이노로 MP3 파일을 재생할 수 있다.


마이크로 SD 카드보다 약간 크다.


DFPlayer Mini Pin Map


Pin Description


배터리, 스피커, 푸시버튼을 연결해 아두이노 없이도 사용할 수 있다.


Specifications

  • supported sampling rates (kHz): 8/11.025/12/16/22.05/24/32/44.1/48

  • 24 -bit DAC output, support for dynamic range 90dB, SNR support 85dB

  • fully supports FAT16, FAT32 file system, maximum support 32G of the TF card, support 32G of U disk, 64M bytes NORFLASH

  • a variety of control modes, I/O control mode, serial mode, AD button control mode

  • advertising sound waiting function, the music can be suspended. when advertising is over in the music continue to play

  • audio data sorted by folder supports up to 100 folders, every folder can hold up to 255 songs

  • 30 level adjustable volume, 6 -level EQ adjustable


위 다이어그램과 같이 연결한다. MP3 파일 재생시 노이즈가 심하다면 RX에 1KΩ 저항을 연결한다.



아두이노IDE - Library manager에서 DFRobotDFPlayerMini를 검색하고 설치한다.


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
/***************************************************
DFPlayer - A Mini MP3 Player For Arduino
 <https://www.dfrobot.com/product-1121.html>
 
 ***************************************************
 This example shows the basic function of library for DFPlayer.
 
 Created 2016-12-07
 By [Angelo qiao](Angelo.qiao@dfrobot.com)
 
 GNU Lesser General Public License.
 See <http://www.gnu.org/licenses/> for details.
 All above must be included in any redistribution
 ****************************************************/
 
/***********Notice and Trouble shooting***************
 1.Connection and Diagram can be found here
 <https://www.dfrobot.com/wiki/index.php/DFPlayer_Mini_SKU:DFR0299#Connection_Diagram>
 2.This code is tested on Arduino Uno, Leonardo, Mega boards.
 ****************************************************/
 
#include "Arduino.h"
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h"
 
SoftwareSerial mySoftwareSerial(1011); // RX, TX
DFRobotDFPlayerMini myDFPlayer;
void printDetail(uint8_t type, int value);
 
void setup()
{
  mySoftwareSerial.begin(9600);
  Serial.begin(115200);
  
  Serial.println();
  Serial.println(F("DFRobot DFPlayer Mini Demo"));
  Serial.println(F("Initializing DFPlayer ... (May take 3~5 seconds)"));
  
  if (!myDFPlayer.begin(mySoftwareSerial)) {  //Use softwareSerial to communicate with mp3.
    Serial.println(F("Unable to begin:"));
    Serial.println(F("1.Please recheck the connection!"));
    Serial.println(F("2.Please insert the SD card!"));
    while(true){
      delay(0); // Code to compatible with ESP8266 watch dog.
    }
  }
  Serial.println(F("DFPlayer Mini online."));
  
  myDFPlayer.volume(20);  //Set volume value. From 0 to 30
  myDFPlayer.play(1);  //Play the first mp3
}
 
void loop()
{
  static unsigned long timer = millis();
  
  if (millis() - timer > 30000) {
    timer = millis();
    myDFPlayer.next();  //Play next mp3 every 30 second.
  }
  
  if (myDFPlayer.available()) {
    printDetail(myDFPlayer.readType(), myDFPlayer.read()); //Print the detail message from DFPlayer to handle different errors and states.
  }
}
 
void printDetail(uint8_t type, int value){
  switch (type) {
    case TimeOut:
      Serial.println(F("Time Out!"));
      break;
    case WrongStack:
      Serial.println(F("Stack Wrong!"));
      break;
    case DFPlayerCardInserted:
      Serial.println(F("Card Inserted!"));
      break;
    case DFPlayerCardRemoved:
      Serial.println(F("Card Removed!"));
      break;
    case DFPlayerCardOnline:
      Serial.println(F("Card Online!"));
      break;
    case DFPlayerUSBInserted:
      Serial.println("USB Inserted!");
      break;
    case DFPlayerUSBRemoved:
      Serial.println("USB Removed!");
      break;
    case DFPlayerPlayFinished:
      Serial.print(F("Number:"));
      Serial.print(value);
      Serial.println(F(" Play Finished!"));
      break;
    case DFPlayerError:
      Serial.print(F("DFPlayerError:"));
      switch (value) {
        case Busy:
          Serial.println(F("Card not found"));
          break;
        case Sleeping:
          Serial.println(F("Sleeping"));
          break;
        case SerialWrongStack:
          Serial.println(F("Get Wrong Stack"));
          break;
        case CheckSumNotMatch:
          Serial.println(F("Check Sum Not Match"));
          break;
        case FileIndexOut:
          Serial.println(F("File Index Out of Bound"));
          break;
        case FileMismatch:
          Serial.println(F("Cannot Find File"));
          break;
        case Advertise:
          Serial.println(F("In Advertise"));
          break;
        default:
          break;
      }
      break;
    default:
      break;
  }
  
}


위 소스를 컴파일하고 업로드하면 모든 노래가 30초씩 플레이된다.


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
bool begin(Stream& stream, bool isACK = truebool doReset = true);
bool waitAvailable(unsigned long duration = 0);
bool available();
uint8_t readType();
uint16_t read();
void setTimeOut(unsigned long timeOutDuration);
void next();
void previous();
void play(int fileNumber=1);
void volumeUp();
void volumeDown();
void volume(uint8_t volume);
void EQ(uint8_t eq);
void loop(int fileNumber);
void outputDevice(uint8_t device);
void sleep();
void reset();
void start();
void pause();
void playFolder(uint8_t folderNumber, uint8_t fileNumber);
void outputSetting(bool enable, uint8_t gain);
void enableLoopAll();
void disableLoopAll();
void playMp3Folder(int fileNumber);
void advertise(int fileNumber);
void playLargeFolder(uint8_t folderNumber, uint16_t fileNumber);
void stopAdvertise();
void stop();
void loopFolder(int folderNumber);
void randomAll();
void enableLoop();
void disableLoop();
void enableDAC();
void disableDAC();
int readState();
int readVolume();
int readEQ();
int readFileCounts(uint8_t device);
int readCurrentFileNumber(uint8_t device);
int readFileCountsInFolder(int folderNumber);
int readFileCounts();
int readFolderCounts();
int readCurrentFileNumber();


그 외 다른 기능은 DFRobotDFPlayerMini.h를 참고한다.


※ 제작사 홈페이지를 보면 아래와 같은 문구가 있다.


NOTE: The order you copy the mp3 into micro SD card will affect the order mp3 played, which means play(1) function will play the first mp3 copied into micro SD card.


파일명을 0001.mp3, 0002.mp3... 이런식으로 변경해서 SD카드에 넣어도 play(1) 함수 실행 시 0001.mp3가 아닌, 제일 먼저 복사된 파일이 첫 번째로 재생되는거 같다.


반응형
Posted by J-sean
:
반응형

You can stream an audio file with MediaPlayer.


<AndroidManifest.xml>

1
    <uses-permission android:name="android.permission.INTERNET"/>



<MainActivity.java>

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
public class MainActivity extends AppCompatActivity {
 
    MediaPlayer mediaPlayer;
    int position = 0;
    boolean isPaused = false;   // To prevent false resume.
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // Play
        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                if (mediaPlayer != null) {
                    mediaPlayer.release();
                }
                try {
                    mediaPlayer = new MediaPlayer();
                    mediaPlayer.setDataSource("http://nexoft.tk/download/Davich.mp3");  // or your audio file url.
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                    isPaused = false;
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
                Toast.makeText(getApplicationContext(), "Media player started", Toast.LENGTH_SHORT).show();
            }
        });
 
        // Stop
        Button button2 = findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer != null) {
                    mediaPlayer.stop();
                    isPaused = false;
                    Toast.makeText(getApplicationContext(), "Media player stopped", Toast.LENGTH_SHORT).show();
                }
            }
        });
 
        // Pause
        Button button3 = findViewById(R.id.button3);
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    position = mediaPlayer.getCurrentPosition();
                    mediaPlayer.pause();
                    isPaused = true;
                    Toast.makeText(getApplicationContext(), "Media player paused at " + position / 1000 + " sec", Toast.LENGTH_SHORT).show();
                }
            }
        });
 
        // Resume
        Button button4 = findViewById(R.id.button4);
        button4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer != null && !mediaPlayer.isPlaying() && isPaused == true) {
                    mediaPlayer.start();
                    mediaPlayer.seekTo(position);
                    isPaused = false;
                    Toast.makeText(getApplicationContext(), "Media player resumed at " + position / 1000 + " sec", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
 
        if (mediaPlayer != null) {
            mediaPlayer.release();
        }
    }
}




Run the app and start the audio file.


반응형
Posted by J-sean
: