Les Snippets

Connexion

Jouer et arrêter un son wav

Niveau requis pour utiliser/comprendre cette source : 1 ( Débutant )
Créé le 25/03/2006 16:58:54 et initié par Willi [Liste]
Date de mise à jour : 09/08/2006 23:10:50
Vue : 34605
Catégorie(s) : Multimédia
Langages dispo pour ce code :
- VB6, VBA
- VB 2005
- C# 2.x
- VB 2005, VB.NET 1.x
- C
- Delphi 5
- Java
- VB.NET 1.x
- VB.NET 1.x
- C++ .NET 2.x
- VBScript



Langage : VB6 , VBA
Date ajout : 25/03/2006
Posté par Willi [Liste]
DateMAJ : 25/03/2006
'Déclaration
Private Const SND_ASYNC = &H1 'Joue le son en arrière-plan.
Private Const SND_FILENAME = &H20000 'Le son provient d'un fichier externe
Private Const SND_LOOP = &H8 ' Répète le son jusqu'au prochain appel de PlaySound
Private Const SND_PURGE = &H40 'Stop la lecture du fichier

Private Declare Function PlaySound Lib "winmm.dll" Alias "PlaySoundA" (ByVal lpszName As String, ByVal hModule As Long, ByVal dwFlags As Long) As Long


'Exemple d'utilisation
'Joue en boucle un fichier wav
PlaySound "C:\fichier1.wav", ByVal 0&, SND_FILENAME Or SND_ASYNC Or SND_LOOP

'Arrete de jouer le wav
PlaySound vbNullString, ByVal 0&, SND_PURGE
Langage : VB 2005
Date ajout : 25/03/2006
Posté par Willi [Liste]
DateMAJ : 25/03/2006

'Joue un fichier wav
My.Computer.Audio.Play("c:\fichier1.wav", AudioPlayMode.Background)

'Joue un fichier wav en boucle
My.Computer.Audio.Play("c:\fichier1.wav", AudioPlayMode.BackgroundLoop)

'Arrete la lecture du wav
My.Computer.Audio.Stop()


Langage : C# 2.x
Date ajout : 26/03/2006
Posté par Bidou [Liste]
DateMAJ : 09/08/2006

// Create the SoundPlayer object
System.Media.SoundPlayer s = new System.Media.SoundPlayer(); 
// Set the location of the wav file to play
s.SoundLocation = @"C:\Program Files\messenger\newalert.wav"; 
// Play looping
s.PlayLooping();
// Play normal
s.Play();
// Stop
s.Stop();


Langage : VB.NET 1.x , VB 2005
Date ajout : 10/04/2006
Posté par Charles Racaud [Liste]

Dim Snd As New System.Media.SoundPlayer("Chemin\De\Votre\Fichier.wav")
Snd.Play()

Langage : C
Date ajout : 10/04/2006
Posté par SAKingdom [Liste]
DateMAJ : 02/08/2006
BOOL PlayWave (LPCSTR FileName)
{
    return sndPlaySound(FileName, SND_ASYNC);
}
 
 BOOL StopWave (void)
 {
    return sndPlaySound(0, SND_SYNC);
 }

Remarque :
Utilise l'API Windows
Langage : Delphi 5
Date ajout : 14/04/2006
Posté par Matt 261 [Liste]
En Delphi pour jouer un son Wav, c'est très simple.
Pour commencer ajoutez mmSystem dans uses.
Le programme n'attend pas la fin que la lecture du son soit finie pour jouer un autre son Wav :
sndPlaySound('c:\monSon.wav', SND_ASYNC); 
Le programme attend la fin de la lecture pour jouer le son :
sndPlaySound('c:\monSon.wav', SND_SYNC); 
Le programme joue le son Wav en boucle :
sndPlaySound('c:\monSon.wav', SND_LOOP or SND_ASYNC); 
Le programme joue un son sauf si un autre son Wav et entrain d'être joué :
sndPlaySound('c:\monSon.wav', SND_NOSTOP or SND_ASYNC);
Par exemple : 
uses mmSystem;
procedure TForm1.Button1Click(Sender: TObject); 
begin
sndPlaySound('c:\Windows\Media\Notify.wav', SND_ASYNC); 
end; 

Langage : Java
Date ajout : 01/08/2006
Posté par Twinuts [Liste]
import java.io.File;
 
 import javax.sound.sampled.AudioFormat;
 import javax.sound.sampled.AudioInputStream;
 import javax.sound.sampled.AudioSystem;
 import javax.sound.sampled.Clip;
 import javax.sound.sampled.DataLine;
 
 
 public class WavPlayer {    
 
     private Clip clip = null;
     private AudioInputStream audioStream = null;
     
     public WavPlayer(File f) throws Exception{
         audioStream = AudioSystem.getAudioInputStream(f);//recuperation d'un stream de type audo sur le fichier
         AudioFormat audioFormat = audioStream.getFormat();//recuperation du format de son
         //recuperation du son que l'on va stoquer dans un oblet de type clip
         DataLine.Info info = new DataLine.Info(
                 Clip.class, audioStream.getFormat(),
                 ((int) audioStream.getFrameLength() * audioFormat.getFrameSize()));
         //recuperation d'une instance de type Clip
         clip = (Clip) AudioSystem.getLine(info);
         
     }
     
     /**
      * Ouverture du flux audio
      * @return On retourne <code>false</code> si il y a eu une erreure
      */
     public boolean open(){
         if(clip != null && !clip.isOpen())//teste pour ne pas le faire dans le vent
             try {
                 clip.open(audioStream);
             } catch (Exception e) {
                 e.printStackTrace();//pour le debugage
                 return false;
             }
         return true;
     }
     
     /**
      * Fermeture du flux audio
      */
     public void close(){
         if(clip != null && clip.isOpen())//teste pour ne pas le faire dans le vent
             clip.close();
     }
     
     /**
      * On joue le son
      */
     public void play(){
         if(clip != null && clip.isOpen())
             clip.start();
     }
     
     /**
      * On arrete le son
      */
     public void stop(){
         if(clip != null && clip.isOpen())
             clip.stop();
     }
     
     
     public static void main(String [] args){
         try {
             WavPlayer wp = new WavPlayer(new File("fichier.wav"));
             wp.open();//ouverture du flux
             wp.play();//lecture
             wp.stop();//arret
             wp.close();//pour etre propre on ferme le flux quand il n'est plus utile :D
         } catch (Exception e) {
             e.printStackTrace();
         }
         
     }
 }
Remarque :
C'est assez long en terme de code mais c'est portable :D
Langage : VB.NET 1.x
Date ajout : 20/11/2006
Posté par OneHacker [Liste]
Public Class SoundClass
    Declare Auto Function PlaySound Lib "winmm.dll" (ByVal name _
    As String, ByVal hmod As Integer, ByVal flags As Integer) As Integer
    ' name specifies the sound file when the SND_FILENAME flag is set.
    ' hmod specifies an executable file handle.
    ' hmod must be Nothing if the SND_RESOURCE flag is not set.
    ' flags specifies which flags are set. 
    ' The PlaySound documentation lists all valid flags.
    Public Const SND_SYNC = &H0          ' play synchronously
    Public Const SND_ASYNC = &H1         ' play asynchronously
    Public Const SND_FILENAME = &H20000  ' name is file name
    Public Const SND_RESOURCE = &H40004  ' name is resource name or atom
    Public Shared Sub PlaySoundFile(ByVal filename As String)
        ' Plays a sound from filename.
        PlaySound(filename, Nothing, SND_FILENAME Or SND_ASYNC)
    End Sub
End Class
Exemple d'appel SoundClass.PlaySoundFile("C:\MonSon.wav")

Remarque :
Les fichier joués doivent être des sons wavs ou d'autres sons qui n'ont pas de codes spécifiques.
Langage : VB.NET 1.x
Date ajout : 20/11/2006
Posté par OneHacker [Liste]
Public Class SoundClass
    Declare Auto Function PlaySound Lib "winmm.dll" (ByVal name _
    As String, ByVal hmod As Integer, ByVal flags As Integer) As Integer
    ' name specifies the sound file when the SND_FILENAME flag is set.
    ' hmod specifies an executable file handle.
    ' hmod must be Nothing if the SND_RESOURCE flag is not set.
    ' flags specifies which flags are set. 
    ' The PlaySound documentation lists all valid flags.
    Private Const SND_SYNC As Long = 0          ' play synchronously
    Public Const SND_ASYNC As Long = 1         ' play asynchronously
    Public Const SND_FILENAME = &H20000  ' name is file name 8192(10)
    Public Const SND_RESOURCE = &H40004  ' name is resource name or atom
    Private Const SND_LOOP = &H8 ' Répète le son jusqu'au prochain appel de PlaySound
    Private Const SND_MEMORY = 4 ' Enregistre en mémoire l'image du son
    Private Const SND_STOP As Long = 64 ' Stop la lecture du fichier
    Private Const SND_NODEFAULT As Long = 2 ' Ne joue pas
    Private Const SND_NOWAIT As Long = 8192 ' Pas d'attente
    Public Shared FileName As String
    Public Enum ReadMode
        Synchronously = SND_SYNC ' Exécuté sans thread ' (fait ramer)
        Asynchronously = SND_ASYNC ' Exécuté avec thread (éxécution fluide)
    End Enum
    Public Shared Sub PlaySoundFile(ByVal FileName As String, ByVal ReadMode As ReadMode)
        ' Plays a sound from filename.
        PlaySound(FileName, Nothing, ReadMode)
    End Sub
    Public Shared Sub StopSoundFile(ByVal FileName As String, ByVal ReadMode As ReadMode)
        ' Stops a sound from filename.
        PlaySound(String.Empty, Nothing, SND_STOP)
    End Sub
    Public Shared Sub PlaySoundFileLoop(ByVal FileName As String, ByVal ReadMode As ReadMode)
        '' Plays a soundloop from filename.
        PlaySound(FileName, Nothing, ReadMode Or SND_LOOP)
    End Sub
    Public Shared Function GetSoundWavePicture() As Image
        ' Plays a sound from filename.
        PlaySound(String.Empty, Nothing, SND_MEMORY)
        Return Clipboard.GetDataObject.GetData(DataFormats.Bitmap, True)
    End Function
End Class
Langage : C++ .NET 2.x
Date ajout : 13/06/2007
Posté par snake9 [Liste]
// Crée un object de type SoundPlayer
System::Media::SoundPlayer^ Player = gcnew System::Media::SoundPlayer();
// Indiquer le chemin d'acces au fichier a lire
Player->SoundLocation = "C:\\son\\sound.wav"; 
// Lance la lecture du son
Player->Play();
// Arrete la lecture du son
Player->Stop(); 

Langage : VBScript
Date ajout : 24/10/2007
Posté par us_30 [Liste]
Function PlaySound(FichierSon) 
Set objShell = CreateObject("Wscript.Shell") 
strCommand = "sndrec32 /play /close " & "" & FichierSon & ""
objShell.Run strCommand, 0, True 
End Function 
WScript.Echo ("Ecouter...") 
PlaySound ("C:\windows\media\chimes.wav") 
WScript.Quit
Remarque :
Il n'existe pas de possibilité de stopper l'exécution en cours avec SNDREC32. Selon les versions de Windows, SNDREC32 peut porter un nom approchant (SNDREC, par exemple).

Snippets en rapport avec : Audio, Jouer, Arreter, Wav, Son



Codes sources en rapport avec : Audio, Jouer, Arreter, Wav, Son

{Visual Basic, VB6, VB.NET, VB 2005} JOUER DU SON EN DUR (DIRECTX8)
C'est un exemple très simple de l'utilisation de la methode Writebuffer de directsound. J'ai posté c...

{JAVA / J2EE} POUR LIRE DU SON
Pour lire des fichiers sons. Fonctionnent avec le wav, au, midi, et quelques autres. Pour fonctionne...

{JAVA / J2EE} LIRE LES FICHIERS .WAV
Cette classe permet de lire les fichiers .wav, de les mettre en pause, et de les reprendre en cours ...

{JAVA / J2EE} JOUER UN SON WAV (A PARTIR DU CODE SOURCE DE NOUNOU21)
Il s'agit d'un lecteur de musique au format wav mis au point a partir du code source de nounou21 (ht...

{Visual Basic, VB6, VB.NET, VB 2005} GESTION DU VOLUME SONORE EN VB NET
C'est un module en VB Net qui assure le contrôle du volume sonore des enceintes de votre PC Cette c...

{PDA / PocketPC} JOUER UN FICHIER WAV SUR MULTI-PLATEFORMES DE PDA
J'ai développé un outil de localisation Gps sur cartes scannées en Pocket PC 2003 SE. (http://sites...

{Flash} BOUTON DE VOLUME
"petite" source faite en 3 heures et 20 min de dessin (histoire de me défouler un peu). Il s'agit...

{Visual Basic, VB6, VB.NET, VB 2005} LECTURE DES CHIFFRES D'UN TEXTE (LECTURE ROBOTIQUE)
Salut, voici un petit code qui pourrait être util pour ceux qui font des logiciels de gestion de pay...

{C / C++ / C++.NET} CONTROLEUR DE VOLUME SONORE EN C [ API WINDOWS ]
Controleur de volume sonore en C --------------------------------------- Programmé avec API Wind...

{C / C++ / C++.NET} MPEG AUDIO -> WAVE FILE (DEV-C++)
Mpeg Audio -> Wave File : Cette source vous permet de convertir un fichier mpeg audio tel que le m...