AdaFruit Wave Shield Librairie AFwave

De MCHobby - Wiki
Sauter à la navigation Sauter à la recherche

Avoir plus de RAM et de Flash!

Note MCHobby: Les plateforme Arduino sont maintenant distribuée avec un ATmega328.

Cette section n'est vraiment pertinente que si vous ne possédez pas d'ATmega328.

Avant d'essayer de jouer de l'audio, vous aurez besoin de faire un peu de place

la mémoire RAM d'Arduino, cela évitera que cela se termine en vilain

dépassement de pile (stack-overflow).

Suivez ces instructions (anglais) pour savoir comment avoir plus

de RAM en réduisant la taille de la mémoire tampon de la librairie série (Serial library).

Vous n'aurez pas besoin de faire cela si vous avez un ATmega328.

Notez que la librairie est vraiment grosse (approximativement 10K). Si vous voulez faire beaucoup plus avec Arduino, il est vivement conseillé de faire un Upgrade vers un ATmega328. Ce shield a été développé en prévoyant la disponibilité d'un ATmega328.

Introduction de la librairie AF_Wave

Ceci est une description de la librairie AF_Wave library, qui est la librairie par 'défaut' pour le Shield Wave. Cependant, il y a une librairie 'mise-à-jour' et supérieure, WaveHC écrite par Mr Fat16 sur le forums d'AdaFruit. Cette librairie est puissante, fonctionne avec plus de cartes et formatage de carte et utilise moins d'espace.

Ce tutoriel est ici pour ceux qui veulent utiliser la librairie classique AF_Wave library mais nous suggérons d'également vérifier WaveHC (google code). Elle est vraiment similaire à la librairie AF_Wave, vous pourrez probablement passer de l'une à l'autre.

Nous avons également un article qui passe la librairie WaveHC en revue

Initialiser la carte

La première chose à faire est d'initialiser la carte SD en vue d'effectuer des lectures. Vous devriez copier et coller le code de l'exemple ci-dessous puisqu'il n'y a vraiment qu'une seule façon de le faire.

Notez que ce code ne contient de qu'un fragment, utilisez les exemples dans le librairie pour une 'listing complet'

AF_Wave card;


void setup() 
{
  ...
  
  if (!card.init_card()) {
    putstring_nl("Init. Carte échec!"); return;
  }
  if (!card.open_partition()) {
    putstring_nl("Pas de partition!"); return;
  }
  if (!card.open_filesys()) {
    putstring_nl("Echec Ouverture systeme fichier (filesys)"); return;
  }

 if (!card.open_rootdir()) {
    putstring_nl("Echec ouverture repertoir (open dir)"); return;
  }
}
...

Ce code va essayer d'initialiser la carte, ouvrir la table des partitions (partition table), ouvrir le système de fichier FAT16 (FAT16 filesystem) et finalement ouvrir le répertoire racine. S'il échoue, il imprime un message d'erreur.

Recherche des fichiers

Naviguer dans le répertoire principal à la recherche des fichiers ne réclame que peu de code. En principe, vous pouvez faire un reset du répertoire (redémarrer depuis le début) and prendre le nom du fichier suivant. Les fichiers ne sont sont pas organisés par ordre alphabétique mais plutôt dans l'ordre dans lequel ils ont été créés sur la carte.

Vous avez besoin d'un tableau de caratère (character array) de 13 caractères pour stocker le nom du fichier (8 caract. + "." + 3 caract. + caractère Null 0).

Voici un exemple qui affiche le nom de tous les fichiers disponibles. Quand c'est terminé, il fait un reset du répertoire.

void ls() {
  char name[13];
  int ret;
  
  card.reset_dir();
  putstring_nl("Fichier trouvé:");
  while (1) {
    ret = card.get_next_name_in_dir(name);
    if (!ret) {
       card.reset_dir();
       return;
    }
    Serial.println(name);
  }
}

Opening a file for playing

There are two steps to opening a file for playing. The first is to just open the file itself, then the file must be converted to a wavefile. That means the file is read and checked for a wavetable header. To open a file, you just need the name, you can pass in a string such as "MYSOUND.WAV" or read through the directory and use the name returned from get_next_name_in_dir(). Since long names arent supported (to keep the library smaller) you may want to use ls() function above to see what the 8.3 format name of the file is.

AF_Wave card;
File f;
Wavefile wave;      // only one!



void playfile(char *name) {
   f = card.open_file(name);
   if (!f) {
      putstring_nl(" Couldn't open file"); return;
   }
   if (!wave.create(f)) {
     putstring_nl(" Not a valid WAV"); return;
   }


  ...
}

Playing the file

Finally we can play the file! Its quite easy, once the wavefile has been opened as above, simply call wave.play() to being playback. The Arduino plays audio in an interrupt, which means that wave.play() returns immediately. You can then mess with sensors, print feedback or buttons or whatever.

While the wavefile is playing, you can check its status with the variable wave.isplaying . If the variable is 1 then the audio is playing. If its 0 that means it has finished playing

You can stop playback by calling wave.stop()

Closing the file

When you're done playing audio from a file, you must close it! You can close the file by calling card.close_file(f) where f is the file you created using card.open_file(name)

Changing sample rate

This is sort of strange, but may be useful if, say, you have a sine wave or sample that youd like to change the pitch of or if youd like to 'fast forward' through some music

The sample rate (i.g. 22kHz) is stored in wave.dwSamplesPerSec. It will be initially set to whatever the wave file is supposed to be. Simply assign a new sample rate to the variable to change it on the fly.

See here for more information.

Saving & restoring the play position

If, say, you want to know where along in the wave file you are, that information is also available in wave.getSize() (the number of bytes in the entire wave) and wave.remainingBytesInChunk (how many bytes are left to play)

You can set the current place to play from using wave.seek(), the Arduino will immediately start to fastforward to that location. For example, wave.seek(0) will take you to the beginning, wave.seek(wave.getSize()/2) will take you to the middle of the file.

Volume adjust

You can change the volume of the audio 'digitally' on the fly. Note that this doesn't change the volume control potentiometer, it actually just reduces the digital values going to the DAC. Thus the quality of the audio will be degraded. However, it may come in handy so it has been included. Since it slows down playback a bit, it is not enabled by default. To enable digital volume control, open up wave.cpp in the library folder and look for the line #define DVOLUME 0 and change the 0 to a 1. Then delete all the files in the library folder that end with .o, this will force the software to recompile the library when the sketch is compiled.

The volume is controlled by a variable in the Wavefile object. For example, if you have Wavefile wave at the top of your sketch, then you can set the volume by calling wave.volume = 4. The volume can be set from 0 to 12. A volume value of 0 is maximum, and 12 is silence. Anything higher than 12 will be the same as 12.

See here for more information.

Traduit avec l'autorisation d'AdaFruit Industries - Translated with the permission from Adafruit Industries - www.adafruit.com

Toute référence, mention ou extrait de cette traduction doit être explicitement accompagné du texte suivant : «  Traduction par MCHobby (www.MCHobby.be) - Vente de kit et composants » avec un lien vers la source (donc cette page) et ce quelque soit le média utilisé.

L'utilisation commercial de la traduction (texte) et/ou réalisation, même partielle, pourrait être soumis à redevance. Dans tous les cas de figures, vous devez également obtenir l'accord du(des) détenteur initial des droits. Celui de MC Hobby s'arrêtant au travail de traduction proprement dit.