innovationOUtside / ou-logger-py

Simple logger for use in Jupyter notebooks
MIT License
0 stars 0 forks source link

Allow SpeechSynthesis voice to be set to an alternative voice #3

Open psychemedia opened 4 months ago

psychemedia commented 4 months ago

The SpeechSynthesis module supports various voices.

In JS, we can get the list of voices as speechSynthesis.getVoices():

# Via ChatGPT
# THe complexity arises becuase Chrom does not simply return the voices...
from IPython.display import Javascript, display
import json
import time

# JavaScript code to get the list of SpeechSynthesis voices
js_code = """
var waitForVoices = new Promise(function(resolve, reject) {
    var voices = window.speechSynthesis.getVoices();
    if (voices.length !== 0) {
        resolve(voices);
    } else {
        window.speechSynthesis.onvoiceschanged = function() {
            voices = window.speechSynthesis.getVoices();
            resolve(voices);
        };
    }
});

waitForVoices.then(function(voices) {
    var voices_list = voices.map(function(voice) {
        return {
            name: voice.name,
            lang: voice.lang,
            default: voice.default,
            localService: voice.localService
        };
    });

    var voices_list_str = JSON.stringify(voices_list);
    # In simple classic notebook days, propagate the value back to the IPython environment
    #IPython.notebook.kernel.execute(`voices_list = ${voices_list_str}`);

    alert(voices_list_str)
});
"""

# Execute the JavaScript code
display(Javascript(js_code))

# But i'm not sure if there is a simple hack for this in JupyterLab?

To change the voice, we then call SpeechSynthesisUtterance.voice= but this needs to match one of the names in the voices list. Which may be different on different browsers? (Or is there a common set of voice names across browsers?)

psychemedia commented 4 months ago

Related issue in JupyterLab repo: https://github.com/jupyterlab/jupyterlab/issues/16400