Accueil > > > CLASSE CSOUND
CLASSE CSOUND
Information sur la source
Description
Une classe pour l'acquisition et le traitement du son
Traitements :
Acquisition, Fichiers Wave, Lecture, Mixage, Collage, Découpage, FFT...
Effets :
Echo, Réverbération, Chorus, Pitch, Voix codée...
Filtres :
Passe-bas, passe-bande, équalizer...
Source
- class CSound
- {
- friend CSoundProcessing;
-
- static const int NB_BUFFER = 32;
- static const int TAILLE_BUFFER = 4096;
-
- //en-tête du fichier wave
- typedef struct WAVEHEADER
- {
- //identification du format (RIFF)
- char strFileType[4];
- //taille du fichier (taille du fichier - 8)
- DWORD dwFileSize;
- //type de fichier (Wave)
- char strFileId[4];
-
- //identification du chunk format (fmt )
- char strChunkFmtId[4];
- //taille du chunck format (16)
- DWORD dwChunkFmtSize;
- //format (1)
- WORD wFormat;
- //nombre de canaux (mono:1 ou stéréo:2)
- WORD wNbChannels;
- //fréquence d'échantillonnage (44,1 kHz)
- DWORD dwSamplingFreq;
- //nombre de bits par secondes (wDepth * wNbChannels / 8)
- DWORD dwBytesPerSec;
- //nombre de bits par échantillonnage (dwBytesPerSec * wDepth)
- WORD wBytesPerSample;
- //nombre de bits par échantillonnage (8 ou 16 bits)
- WORD wDepth;
- };
-
- //handle sur la carte son (entrée)
- HWAVEIN m_hWaveIn;
-
- //flag d'acquisition
- BOOL m_bRecord;
-
- //structure Wave
- WAVEFORMATEX m_WaveFormat;
-
- //pour le formatage des données
- void Formate(const CTab<BYTE>& dataIn, CTab<short> dataOut[2]);
- void Unformate(CTab<short> dataIn[2], CTab<BYTE>& dataOut);
-
- //fontions callback pour l'acquisition
- friend void CALLBACK WaveInProc(HWAVEIN hWaveIn, UINT uMsg, DWORD dwInstance, DWORD dwParam1, DWORD dwParam2);
- void AddData(const CTab<BYTE>& data);
-
- //buffers d'entrée
- WAVEHDR m_WaveInHeader[NB_BUFFER];
- BYTE m_pWaveInBuffer[NB_BUFFER * TAILLE_BUFFER];
-
- //données formatées du son
- CTab<short> m_Buffer[2];
-
- //lock du buffer
- CMutex m_Mutex;
- CSem m_Semaphore;
-
- //listener
- CSoundListener* m_pListener;
-
- public :
- //constructeur et destructeur
- CSound(void); //constructeur par défaut
- CSound(DWORD freq, WORD format, WORD nbChannel); //constructeur avec arguments
- CSound(const CSound& Wave); //constructeur de copie
- ~CSound(void); //destructeur
-
- //listener
- void SetListener(CSoundListener* listener);
-
- //paramétrage
- void Reset();
- void SetFreq(DWORD freq);
- void SetFormat(WORD format);
- void SetNbChannels(WORD nbChannel);
-
- //acquisition
- BOOL StartRecord(void);
- BOOL StopRecord(void);
- BOOL InRecord(void) const;
-
- //lock/unlock
- void LockBuffer();
- void UnlockBuffer();
-
- //méthode de sauvegarde
- BOOL SaveToFile(const CStr& strNomFichier);
-
- //méthodes de restitution
- BOOL Play(void);
- BOOL PlayFile(const CStr& strNomFichier);
-
- //méthode d'ouverture fichier wave
- BOOL OpenFile(const CStr& strNomFichier);
-
- //méthode pour obtenir la durée d'un son (en secondes)
- float GetTime();
-
- //méthode d'information
- BOOL IsValid() const;
- DWORD GetFreq(void) const;
- WORD GetFormat(void) const;
- WORD GetNbChannels(void) const;
- };
-
- class CSoundProcessing
- {
- public:
- static const int TAILLE_FFT = 2048;
-
- //type enuméré pour les filtres fenêtrés
- enum TFiltre
- {
- FRect,
- FHanning,
- FHamming,
- FBlackman,
- FBartlett
- };
-
- //structure pour les bandes de fréquences
- typedef struct TBande
- {
- float fFreqBas;
- float fFreqHaut;
- float fCoef;
- }Bande;
-
- private:
- CSound* m_pSound;
-
- //FFT et FFT inverse
- static UINT InverseBits(UINT uIndex, UINT uNbBits);
- static UINT GetNbBits(UINT uTaille);
- static BOOL FFT(UINT uTaille, BOOL bInverse, double* pfReIn, double* pfImIn, double* pfReOut, double* pfImOut);
-
- public:
- CSoundProcessing(void);
- virtual ~CSoundProcessing(void);
-
- void SetSound(CSound* pSound);
-
- //méthode obtenir pour la FFT
- BOOL GetFFT(CTab<double> fTabFFT[2]);
-
- //méthodes d'effet
- BOOL Gain(float fGain);
- BOOL Echo(float fPeriode, float fAttenuation);
- BOOL Reverb(float fPeriode, float fAttenuation);
- BOOL CodeVoice(void);
- BOOL Pitch(float fPitch);
- BOOL Retard(float fRetard);
- BOOL Chorus(float fAttenuation);
- BOOL Tremolo(float fAmplitude, DWORD dwFreq);
- BOOL Disto(CTab<float>* pTabDisto = NULL);
- BOOL FadeIn(float fLowGain, float fHighGain);
- BOOL FadeOut(float fLowGain, float fHighGain);
- BOOL Inverse(void);
-
- //méthodes de traitement
- static CSound Mix(const CSound& snd1, const CSound& snd2);
- static CSound Colle(const CSound& snd1, const CSound& snd2);
- static CSound Coupe(const CSound& snd, float fDebut, float fFin);
-
- //fonction de filtrage (fenêtre)
- static BOOL Filtrage(CTab<double>& TabFFT, int filtre);
-
- //filtres
- BOOL PasseBas(float fGain, DWORD dwFc);
- BOOL PasseHaut(float fGain, DWORD dwFc);
- BOOL PasseBande(TBande tBandeFreq);
- BOOL Noise(void);
- BOOL Equalizer(const CTab<TBande>& TabBande);
- };
-
- class CSoundListener
- {
- public:
- CSoundListener(void);
- virtual ~CSoundListener(void);
-
- virtual void OnData(CTab<short> data[2]){};
- };
class CSound
{
friend CSoundProcessing;
static const int NB_BUFFER = 32;
static const int TAILLE_BUFFER = 4096;
//en-tête du fichier wave
typedef struct WAVEHEADER
{
//identification du format (RIFF)
char strFileType[4];
//taille du fichier (taille du fichier - 8)
DWORD dwFileSize;
//type de fichier (Wave)
char strFileId[4];
//identification du chunk format (fmt )
char strChunkFmtId[4];
//taille du chunck format (16)
DWORD dwChunkFmtSize;
//format (1)
WORD wFormat;
//nombre de canaux (mono:1 ou stéréo:2)
WORD wNbChannels;
//fréquence d'échantillonnage (44,1 kHz)
DWORD dwSamplingFreq;
//nombre de bits par secondes (wDepth * wNbChannels / 8)
DWORD dwBytesPerSec;
//nombre de bits par échantillonnage (dwBytesPerSec * wDepth)
WORD wBytesPerSample;
//nombre de bits par échantillonnage (8 ou 16 bits)
WORD wDepth;
};
//handle sur la carte son (entrée)
HWAVEIN m_hWaveIn;
//flag d'acquisition
BOOL m_bRecord;
//structure Wave
WAVEFORMATEX m_WaveFormat;
//pour le formatage des données
void Formate(const CTab<BYTE>& dataIn, CTab<short> dataOut[2]);
void Unformate(CTab<short> dataIn[2], CTab<BYTE>& dataOut);
//fontions callback pour l'acquisition
friend void CALLBACK WaveInProc(HWAVEIN hWaveIn, UINT uMsg, DWORD dwInstance, DWORD dwParam1, DWORD dwParam2);
void AddData(const CTab<BYTE>& data);
//buffers d'entrée
WAVEHDR m_WaveInHeader[NB_BUFFER];
BYTE m_pWaveInBuffer[NB_BUFFER * TAILLE_BUFFER];
//données formatées du son
CTab<short> m_Buffer[2];
//lock du buffer
CMutex m_Mutex;
CSem m_Semaphore;
//listener
CSoundListener* m_pListener;
public :
//constructeur et destructeur
CSound(void); //constructeur par défaut
CSound(DWORD freq, WORD format, WORD nbChannel); //constructeur avec arguments
CSound(const CSound& Wave); //constructeur de copie
~CSound(void); //destructeur
//listener
void SetListener(CSoundListener* listener);
//paramétrage
void Reset();
void SetFreq(DWORD freq);
void SetFormat(WORD format);
void SetNbChannels(WORD nbChannel);
//acquisition
BOOL StartRecord(void);
BOOL StopRecord(void);
BOOL InRecord(void) const;
//lock/unlock
void LockBuffer();
void UnlockBuffer();
//méthode de sauvegarde
BOOL SaveToFile(const CStr& strNomFichier);
//méthodes de restitution
BOOL Play(void);
BOOL PlayFile(const CStr& strNomFichier);
//méthode d'ouverture fichier wave
BOOL OpenFile(const CStr& strNomFichier);
//méthode pour obtenir la durée d'un son (en secondes)
float GetTime();
//méthode d'information
BOOL IsValid() const;
DWORD GetFreq(void) const;
WORD GetFormat(void) const;
WORD GetNbChannels(void) const;
};
class CSoundProcessing
{
public:
static const int TAILLE_FFT = 2048;
//type enuméré pour les filtres fenêtrés
enum TFiltre
{
FRect,
FHanning,
FHamming,
FBlackman,
FBartlett
};
//structure pour les bandes de fréquences
typedef struct TBande
{
float fFreqBas;
float fFreqHaut;
float fCoef;
}Bande;
private:
CSound* m_pSound;
//FFT et FFT inverse
static UINT InverseBits(UINT uIndex, UINT uNbBits);
static UINT GetNbBits(UINT uTaille);
static BOOL FFT(UINT uTaille, BOOL bInverse, double* pfReIn, double* pfImIn, double* pfReOut, double* pfImOut);
public:
CSoundProcessing(void);
virtual ~CSoundProcessing(void);
void SetSound(CSound* pSound);
//méthode obtenir pour la FFT
BOOL GetFFT(CTab<double> fTabFFT[2]);
//méthodes d'effet
BOOL Gain(float fGain);
BOOL Echo(float fPeriode, float fAttenuation);
BOOL Reverb(float fPeriode, float fAttenuation);
BOOL CodeVoice(void);
BOOL Pitch(float fPitch);
BOOL Retard(float fRetard);
BOOL Chorus(float fAttenuation);
BOOL Tremolo(float fAmplitude, DWORD dwFreq);
BOOL Disto(CTab<float>* pTabDisto = NULL);
BOOL FadeIn(float fLowGain, float fHighGain);
BOOL FadeOut(float fLowGain, float fHighGain);
BOOL Inverse(void);
//méthodes de traitement
static CSound Mix(const CSound& snd1, const CSound& snd2);
static CSound Colle(const CSound& snd1, const CSound& snd2);
static CSound Coupe(const CSound& snd, float fDebut, float fFin);
//fonction de filtrage (fenêtre)
static BOOL Filtrage(CTab<double>& TabFFT, int filtre);
//filtres
BOOL PasseBas(float fGain, DWORD dwFc);
BOOL PasseHaut(float fGain, DWORD dwFc);
BOOL PasseBande(TBande tBandeFreq);
BOOL Noise(void);
BOOL Equalizer(const CTab<TBande>& TabBande);
};
class CSoundListener
{
public:
CSoundListener(void);
virtual ~CSoundListener(void);
virtual void OnData(CTab<short> data[2]){};
};
Conclusion
Encore beaucoup plus simple d'utilisation. N'hésitez pas à poser des questions si besoin est.
Un petit exemple d'utilisation suite à des demandes :
CSoundProcessing process;
CSound snd1;
//acquisition de 10 secondes
snd1.StartRecord();
Sleep(10000);
snd1 .StopRecord();
//init process sur snd1
process.SetSound(&snd1);
//appliquer un écho toutes les 1s, diminuant de moitié
process.Echo(1.0, 2.0);
CSound snd2;
//ouvrir un fichier Wave
snd2.OpenFile("monfichier.wav");
//init process sur snd2
process.SetSound(&snd2);
//multiplier par deux les fréquences comprises entre 500Hz et 2kHz
CSoundProcessing::TBande bande;
bande.fCoef = 2.0;
bande.fFreqBas = 500;
bande.fFreqHaut = 2000;
process.PasseBande(bande);
//obtenir la FFT du signal
/*
Note :
mono : tabFFT[0] et tabFFT[1] sont identiques
stéréo : tabFFT[0] contient le canal gauche et tabFFT[1] le canal droit
*/
CTab<double> tabFFT[2];
if(process.GetFFT(tabFFT))
{
int indexFreqMax = 0;
double max = 0.0;
//trouver la fréquence dominante (en amplitude)
for(int i=0;i<tabFFT[0].Size();i++)
{
if(tabFFT[0] > max)
{
max = tabFFT[0];
indexFreqMax = i;
}
}
//calcul de la fréquence correspondante
double freqMax = (double)(indexFreqMax * snd2.GetFreq() / CSoundProcessing::TAILLE_FFT);
}
//mixer avec le fichier wave
CSound snd3 = CSoundProcessing::Mix(snd1, snd2);
//si pas d'erreurs
if(snd3.IsValid())
{
//jouer le son
snd3.Play();
//sauvegarder dans un fichier wave 16 bits stéréo
snd3.SetFormat(16);
snd3.SetNbChannels(2);
snd3.SaveToFile("mix.wav");
}
Historique
- 02 août 2006 12:07:49 :
- J'ai revu tout le fonctionnement de la classe.
Le stockage des données s'effectue désormais en mémoire sans passer par des "fichiers buffer". L'usage est donc beaucoup plus rapide.
J'ai corrigé ensuite certains bugs et facilité l'utilisation de la classe.
Enfin, la classe est désormais utilisable sous Dev-C++ et Visual C++.
- 03 août 2006 18:37:06 :
- ...
- 20 août 2006 00:13:48 :
- ...
- 15 mars 2008 14:55:01 :
- Uniformisation des données.
Possibilité de convertir un son 8bits mono en 16bits stéréo par exemple.
Possibilité de modifier en direct les donnée acquises à l'aide d'un listener.
Correction de quelques bugs.
Optimisations.
- 15 mars 2008 15:13:11 :
- oups...
- 20 mars 2008 11:46:00 :
- Exemple d'utilisation
- 20 mars 2008 11:48:03 :
- ...
Sources du même auteur
Sources de la même categorie
Commentaires et avis
Discussions en rapport avec ce code source dans le forum
comment lire un son.wave sous c [ par dosal ]
bonjour, s'il vous plait aidez moi, j'ai un projet de fin d'étude sur le codage et décodage d'un base de données audio sous cou c++, je cherche une fo
[BATCH ]Problème sur création fichier bat [ par hossec2006 ]
Bonjou à tous, J'ai récupéré un tuto ici : http://www.zebulon.fr/dossiers/128-15-vaccination-noms-reserves-windows.html Il est destiné à la créatio
volume d'un sample audio [ par oeildedinde ]
Salut, Je cherche une solution pour abaisser le niveau sonore d'un sample audio (dans un filtre directshow). J'ai testé 2 solutions qui me font appar
Convertir un fichier audio G711 en G729 [ par debass42 ]
Bonjour a toute la communauté. Je désire convertir un fichier audio G711 en un autre fichier audio G729... et inversement bien sur. Problème, je n'
Taquin - audio [ par julan2074 ]
Quelqu'un peut-il prendre le temps de m'aider à réaliser à jeu ? j'aimerai fabriqué un taquin... sonore : une fois le visuel correctement réalisé, une
Afficher les fréquence d'un fichier audio [ par PriMe2302 ]
Bonjour, je voudrais faire un programme permettant d'afficher les fréquences d'un fichier audio. Comment faire? Merci
[Bar] Audio + Bluetooth [ par buno ]
Hello les gens! L'un(e) d'entre vous a-t-il eu le loisir de coder une appli envoyant un fichier audio à un renderer en Bluetooth? Je vois 2 grandes
creer un echo sur un .wav [ par titixe ]
bonjour et merci de me lire.je cherche a realiser un prog pouvant creer un echo sur un fichier .wav mais je n ai aucune idee comment le faire si vous
Fonction $gettok (mIRC) sous cpp [ par mast ]
Salut j'aui une variable qui retourne par exemple: allo sa va oui toi? /echo -a allo /echo -a bye et je voudrais enregistrer les 2 commen (/..) dans c
Problème pour lire les fichiers audio dans un programme C++ [ par Nicolas ]
Pour un projet C++ (linéaire),il souhaiterais réalisé une bibliothèque musical(.mp3, .wav). J'aurais besoin pour ca de lire les fichiers audio mais je
|
Derniers Blogs
[FRAMEWORK 4] LES TASKS ET LE THREAD UI[FRAMEWORK 4] LES TASKS ET LE THREAD UI par fathi
Je viens de passer quelques temps au TechDay's et j'ai pu voir pas mal de session intéressante. Par contre une chose m'a un peu étonné lors de certaines de ces sessions qui abordaient les améliorations du framework .NET (donc le 4.5) : en gros, bea...
Cliquez pour lire la suite de l'article par fathi WORKFLOW FOUNDATION 3 A UN PIED DANS LA TOMBEWORKFLOW FOUNDATION 3 A UN PIED DANS LA TOMBE par JeremyJeanson
Depuis déjà un an, je conseille vivement les utilisateurs de Workflow Foundation 3 à migrer vers la version 4. L'information qui va suivre ne devrait donc pas trop prendre au dépourvu les personnes qui m'ont suivi. Je profite de ce poste, pour faire le re...
Cliquez pour lire la suite de l'article par JeremyJeanson TECHDAYS PARIS 2012 : NOUVELLES TENDANCES DU POSTE DE TRAVAIL - BRING YOUR OWN PCTECHDAYS PARIS 2012 : NOUVELLES TENDANCES DU POSTE DE TRAVAIL - BRING YOUR OWN PC par ROMELARD Fabrice
Speakers: Thierry Rapatout, Antoine Petit et Xavier Trebbia Cette session entre dans le cadre des RDV Décideurs des TechDays 2012, elle est liée à la consumérisation de l'IT et la mise en place du "DeskTop as a Service" dans de plus en ...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice TECHDAYS PARIS 2012 : SYSTEM CENTER SERVICE MANAGER 2012 VUE D'ENSEMBLETECHDAYS PARIS 2012 : SYSTEM CENTER SERVICE MANAGER 2012 VUE D'ENSEMBLE par ROMELARD Fabrice
Speakers: Julien Marechal, Gautier Confiant, Sébastien MEYER La session débute par le positionnement de la solution System Center par rapport aux concepts d'organisation ITIL. Le portail du catalogue de se...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice TECHDAYS PARIS 2012 : PLEINIèRE SECOND JOURTECHDAYS PARIS 2012 : PLEINIèRE SECOND JOUR par ROMELARD Fabrice
Après une première journée dédiée aux développeurs, cette seconde journée est dédiée au monde des entreprises et de ses applications. Ainsi, cette pleinière est dédiée à faire un 360 de l'évolution des applications Business aux demandes ac...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice
Logiciels
Academy System (17.2.1.0)ACADEMY SYSTEM (17.2.1.0)Logiciel de gestion des établissements.
- élèves/étudiants (inscription, dossier, absence...)
-... Cliquez pour télécharger Academy System Easy-Planning (1.0.0.1)EASY-PLANNING (1.0.0.1)Basé sur les mêmes principes que MyPlanning, Easy-Planning permet de créer des plannings sous la ... Cliquez pour télécharger Easy-Planning COLLECTOR PLUS (3.00B)COLLECTOR PLUS (3.00B)COLLECTOR PLUS version 3.00B est un logiciel utilisant une base de données alimentée par :
- L... Cliquez pour télécharger COLLECTOR PLUS PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V7.4)PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V7.4)PONAMEDIA TV DEVIENS HELLLOOO FLASH
LA TV SUR VOTRE ORDINATEUR.
Toute une plateforme Multi... Cliquez pour télécharger PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO LettresFaciles 2011 (8.0.0.1)LETTRESFACILES 2011 (8.0.0.1)LettresFaciles est un logiciel facilitant la création et la rédaction de lettres types.
Son inte... Cliquez pour télécharger LettresFaciles 2011
|