[ Qt 프로그래밍 ]QAudioOutput 예제

Colored By Color Scripter

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
#ifndef GILAUDIO_H
#define GILAUDIO_H
 
#include <QAudioOutput>
#include <QFile>
#include <QDebug>
#include <QFileDialog>
#include <QBuffer>
 
class GilAudio : public QObject
{
    Q_OBJECT
public:
    GilAudio(QString fileName)
    {
        isLoop=false;
        sourceFile.setFileName(fileName);
 
        QAudioFormat format;
        // Set up the format, eg.
        format.setSampleRate(22050);
        format.setChannelCount(1);
        format.setSampleSize(16);
        format.setCodec("audio/pcm");
        format.setByteOrder(QAudioFormat::LittleEndian);
        format.setSampleType(QAudioFormat::UnSignedInt);
 
        QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice());
        if (!info.isFormatSupported(format)) {
            qWarning() << "Raw audio format not supported by backend, cannot play audio.";
            return;
        }
 
        audio = new QAudioOutput(format, this);
        connect(audio, SIGNAL(stateChanged(QAudio::State)), this, SLOT(handleStateChanged(QAudio::State)));
 
 
    }
private:
    QFile sourceFile;   // class member.
    QAudioOutput* audio; // class member.
    bool isLoop;
 
    public Q_SLOTS:
    void playSound()
    {
 
        if(sourceFile.isOpen()==false)
        {
            audio->stop();
            sourceFile.close();
            sourceFile.open(QIODevice::ReadOnly);
            audio->start(&sourceFile);
 
        }
 
 
    }
    void stopSound()
    {
        audio->stop();
    }
    void setRepeat(bool rp)
    {
        isLoop=rp;
    }
 
    void handleStateChanged(QAudio::State newState)
    {
        switch (newState) {
            case QAudio::IdleState:
                // Finished playing (no more data)
                audio->stop();
 
                sourceFile.close();
                if(isLoop==true)
                {
                    playSound();
                    return;
                }
                //delete audio;
                break;
 
            case QAudio::StoppedState:
                // Stopped for other reasons
                if (audio->error() != QAudio::NoError) {
                    // Error handling
                }
                break;
 
            default:
                // ... other cases as appropriate
                break;
        }
    }
};
 
#endif // GILAUDIO_H