|
| 1 | +// Copyright (c) 2018 ml5 |
| 2 | +// |
| 3 | +// This software is released under the MIT License. |
| 4 | +// https://opensource.org/licenses/MIT |
| 5 | + |
| 6 | +/* === |
| 7 | +ml5 Example |
| 8 | +Sound classification using pre-trained custom SpeechCommands18w and p5.js |
| 9 | +This example uses a callback pattern to create the classifier |
| 10 | +=== */ |
| 11 | + |
| 12 | +const modelJson = 'https://storage.googleapis.com/tm-speech-commands/eye-test-sound-yining/model.json'; |
| 13 | +// Two variable to hold the label and confidence of the result |
| 14 | +let label; |
| 15 | +let confidence; |
| 16 | +// Initialize a sound classifier method. |
| 17 | +let classifier; |
| 18 | + |
| 19 | +function preload() { |
| 20 | + // Load the pre-trianed custom SpeechCommands18w sound classifier model |
| 21 | + classifier = ml5.soundClassifier(modelJson); |
| 22 | +} |
| 23 | + |
| 24 | +function setup() { |
| 25 | + noCanvas(); |
| 26 | + // ml5 also supports using callback pattern to create the classifier |
| 27 | + // classifier = ml5.soundClassifier(modelJson, modelReady); |
| 28 | + |
| 29 | + // Create 'label' and 'confidence' div to hold results |
| 30 | + label = createDiv('Label: ...'); |
| 31 | + confidence = createDiv('Confidence: ...'); |
| 32 | + // Classify the sound from microphone in real time |
| 33 | + classifier.classify(gotResult); |
| 34 | +} |
| 35 | + |
| 36 | +// If you use callback pattern to create the classifier, you can use the following callback function |
| 37 | +// function modelReady() { |
| 38 | +// classifier.classify(gotResult); |
| 39 | +// } |
| 40 | + |
| 41 | +// A function to run when we get any errors and the results |
| 42 | +function gotResult(error, results) { |
| 43 | + // Display error in the console |
| 44 | + if (error) { |
| 45 | + console.error(error); |
| 46 | + } |
| 47 | + // The results are in an array ordered by confidence. |
| 48 | + console.log(results); |
| 49 | + // Show the first label and confidence |
| 50 | + label.html('Label: ' + results[0].label); |
| 51 | + confidence.html('Confidence: ' + nf(results[0].confidence, 0, 2)); // Round the confidence to 0.01 |
| 52 | +} |
0 commit comments