Υποενότητα 10.3: Ήχος στο p5
Υποενότητα 10.3: Ήχος στο p5
- Φόρτωση - load και αναπαραγωγή - play sound
- Κουμπιά play και pause
- Καταγραφή ήχου - capture sound
Φόρτωση - load και αναπαραγωγή - play 'ηχουε
Το p5.js διαθέτει ενσωματωμένη βιβλιοθήκη ήχου p5.js, η οποία μας επιτρέπει να χειριζόμαστε τον ήχο.
Για να φορτώσουμε τον ήχο, χρησιμοποιούμε τη συνάρτηση loadSound() . Παρόμοια με άλλα μέσα, βάζουμε αυτή τη λειτουργία μέσα σε preload().
Για να παίξουμε πραγματικά τον ήχο θα πρέπει να χρησιμοποιήσουμε τη συνάρτηση play().
Επιπλέον, μπορούμε να ρυθμίσουμε το επίπεδο ήχου χρησιμοποιώντας τη συνάρτηση setVolume() . Αυτή η συνάρτηση λαμβάνει τιμές από 0,0 (ελάχιστο) έως 1,0 (μέγιστο).
Παράδειγμα
Ακολουθεί ένα παράδειγμα κώδικα όπου φορτώνουμε και παίζουμε έναν ήχο:
function preload() {
mySound = loadSound('sounds/Sg.mp3');
}
function setup() {
// define the sound level
mySound.setVolume(0.1);
// play the sound
mySound.play();
}
Μπορείτε να δείτε το αποτέλεσμα του παραπάνω κώδικα here
Exercise
- Open your Visual Studio editor and the
p5yourNamefolder. - Open the file
ex812.jsin your editor and save it asex1031.js - Open the file
ex812.htmlin your editor and save it asex1031.html - In the
ex1031.htmlfile, update the link toex1031.jsfrom exersice812.js - Go to the
index.htmlfile and create, underModule 10, alinkto theex1031.htmlfile with the title "load and play sound".
Modify the ex1031.jsfile and use as a base the above example to load a sound. The sound volume should increase as long as the mouse is pressed and when released, should return to the original volume. You can see here an example.
function preload() {
mySound = loadSound('sounds/Sg.mp3');
}
function setup() {
// define the sound level
mySound.setVolume(0.1);
// play the sound
mySound.play();
}
function mousePressed() {
// increase sound level when mouse is pressed
mySound.setVolume(0.5);
}
function mouseReleased() {
// return to the original sound level
mySound.setVolume(0.1);
}
Κάντε μια Git commit με το μήνυμα "load and play sound".
- Δείτε περισσότερα για την loadSound() function
- Δείτε περισσότερα για την play() function
- Δείτε περισσότερα για την setVolume() function