Javascript/HTML5 - Save mute on localstorage - javascript

I'm creating 5 games with javascript and html5 and I'm using sound. I have a mute button that activates the function down bellow. Thing is, I want to make so that if I press the mute button and I move to another page, it will still be muted, but I can't seem to figure out how to integrate it in this function. If someone could help me out by editing the code, I'd really apreciate it :D
function init(){
audio = new Audio();
audio.src = "sound/paint_Music.mp3";
audio.loop = true;
audio.autoplay = true;
mutebtn = document.getElementById("mutebtn");
mutebtn.addEventListener("click", mute);
function mute(){
if (audio.muted){
audio.muted = false;
document.getElementById("mutebtn").src = "img/soundON.png";
} else {
audio.muted = true;
document.getElementById("mutebtn").src = "img/soundOFF.png";
}
}
}

Modify your function like this
function init() {
audio = new Audio();
audio.src = "sound/paint_Music.mp3";
audio.loop = true;
audio.autoplay = true;
var muteState = localStorage.getItem('muteState');
if (!muteState || muteState !== 'true') {
audio.muted = false;
document.getElementById("mutebtn").src = "img/soundON.png";
}
else {
audio.muted = true;
document.getElementById("mutebtn").src = "img/soundOFF.png";
}
mutebtn = document.getElementById("mutebtn");
mutebtn.addEventListener("click", mute);
function mute() {
if (audio.muted) {
audio.muted = false;
document.getElementById("mutebtn").src = "img/soundON.png";
} else {
audio.muted = true;
document.getElementById("mutebtn").src = "img/soundOFF.png";
}
localStorage.setItem('muteState', String(audio.muted));
}
}

Add the muted value to your localStorage in your 'mute' method.
function mute(){
...
audio.muted = false;
localStorage.setItem('muted', 'false');
} else {
audio.muted = true;
localStorage.setItem('muted', 'true');
}
}
}
Then on your init retrieve the localStorage value or default to false if it wasn't set prior.
function init(){
audio = new Audio();
audio.src = "sound/paint_Music.mp3";
audio.loop = true;
audio.autoplay = true;
var isMuted = (localStorage.getItem("muted") && localStorage.getItem("muted") == 'true') || false
audio.muted = isMuted;
mutebtn = document.getElementById("mutebtn");
mutebtn.addEventListener("click", mute);
}

Related

Recording voice and convert speech to text at the same time

I want to use the Web Speech API for speech recognition and record the user's voice in Android Devices at the same time (I mean user holds a button, his/her voice is recorded and transcript to text at the same time .
This is working perfectly in Windows but with Android it just returns the error :
no-speech
Seems like defining the MediaRecorder blocks access of microphone for Web Speech API in Android!
How can I fix this?
If I remove this line which is responsible for recording, speech recognition works again:
new MediaRecorder(stream); // adding this line ruins the speech recognition
Here is the code in action:
In the given code I didn't remove this, in order to show that the code won't work on Android devices:
Note: this code should be tested with an Android device, it is working fine in desktop.
CodePen: https://codepen.io/pixy-dixy/pen/GRddgYL?editors=1010
Demo here in SO:
let audioChunks = [];
let rec;
let stopRecognize;
const output = document.getElementById('output');
async function Recognize() {
console.log('Recognize')
let recognitionAllowed = true;
stopRecognize = function() {
if(recognitionAllowed) {
recognition.stop();
recognitionAllowed = false;
}
}
var SpeechRecognition = SpeechRecognition || webkitSpeechRecognition;
var SpeechGrammarList = SpeechGrammarList || webkitSpeechGrammarList;
var SpeechRecognitionEvent = SpeechRecognitionEvent || webkitSpeechRecognitionEvent;
var recognition = new SpeechRecognition();
var speechRecognitionList = new SpeechGrammarList();
recognition.grammars = speechRecognitionList;
recognition.lang = 'en-GB';
recognition.continuous = false;
recognition.interimResults = true;
recognition.maxAlternatives = 1;
recognition.start();
recognition.onresult = function(event) {
window.interim_transcript = '';
window.speechResult = '';
for(var i = event.resultIndex; i < event.results.length; ++i) {
if(event.results[i].isFinal) {
speechResult += event.results[i][0].transcript;
console.log(speechResult);
output.innerHTML = speechResult;
} else {
interim_transcript += event.results[i][0].transcript;
console.log(interim_transcript);
output.innerHTML = interim_transcript;
}
}
}
recognition.onerror = function(event) {
// restartRecognition();
console.log('recognition error: ' + event.error);
}
recognition.onend = async function(event) {
restartRecognition();
}
function restartRecognition() {
try { if(recognitionAllowed) recognition.start(); } catch(err) {}
}
}
const startRecognition = document.getElementById('start-recognition');
startRecognition.addEventListener('mousedown', handleRecognitionStart);
startRecognition.addEventListener('mouseup', handleRecognitionEnd);
startRecognition.addEventListener('touchstart', handleRecognitionStart);
startRecognition.addEventListener('touchend', handleRecognitionEnd);
function handleRecognitionStart(e) {
console.log('handleRecognitionStart', isTouchDevice)
const event = e.type;
if(isTouchDevice && event == 'touchstart') {
recognitionStart();
} else if(!isTouchDevice && event == 'mousedown') {
console.log('handleRecognitionStart')
recognitionStart();
}
}
const isTouchDevice = touchCheck();
function touchCheck() {
const maxTouchPoints = navigator.maxTouchPoints || navigator.msMaxTouchPoints;
return 'ontouchstart' in window || maxTouchPoints > 0 || window.matchMedia && matchMedia('(any-pointer: coarse)').matches;
}
function handleRecognitionEnd(e) {
const event = e.type;
console.log(':::', event == 'touchend');
if(isTouchDevice && event == 'touchend') {
recognitionEnd();
} else if(!isTouchDevice && event == 'mouseup') {
recognitionEnd();
}
}
function recognitionEnd() {
resetRecognition();
}
function recognitionStart() {
console.log('recognitionStart')
Recognize();
audioChunks = [];
voiceRecorder.start()
}
function resetRecognition() {
console.log('reset')
if(typeof stopRecognize == "function") stopRecognize();
// if(rec.state !== 'inactive') rec.stop();
voiceRecorder.stop()
}
const playAudio = document.getElementById('play');
playAudio.addEventListener('click', () => {
console.log('play');
voiceRecorder.play();
})
class VoiceRecorder {
constructor() {
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
console.log("getUserMedia supported")
} else {
console.log("getUserMedia is not supported on your browser!")
}
this.mediaRecorder
this.stream
this.playerRef = document.querySelector("#player")
this.recorderRef = document.querySelector("#recorder")
this.chunks = []
this.isRecording = false
this.constraints = {
audio: true,
video: false
}
}
handleSuccess(stream) {
this.stream = stream
this.stream.oninactive = () => {
console.log("Stream ended!")
};
this.recorderRef.srcObject = this.stream
this.mediaRecorder = new MediaRecorder(this.stream)
console.log(this.mediaRecorder)
this.mediaRecorder.ondataavailable = this.onMediaRecorderDataAvailable.bind(this)
this.mediaRecorder.onstop = this.onMediaRecorderStop.bind(this)
this.recorderRef.play()
this.mediaRecorder.start()
}
handleError(error) {
console.log("navigator.getUserMedia error: ", error)
}
onMediaRecorderDataAvailable(e) { this.chunks.push(e.data) }
onMediaRecorderStop(e) {
const blob = new Blob(this.chunks, { 'type': 'audio/ogg; codecs=opus' })
const audioURL = window.URL.createObjectURL(blob)
this.playerRef.src = audioURL;
this.chunks = [];
this.stream.getAudioTracks().forEach(track => track.stop());
this.stream = null;
}
play() { this.playerRef.play(); }
start() {
console.log('start')
if(this.isRecording) return;
console.log('33')
this.isRecording = true;
this.playerRef.src = '';
navigator.mediaDevices
.getUserMedia(this.constraints)
.then(this.handleSuccess.bind(this))
.catch(this.handleError.bind(this))
}
stop() {
if(!this.isRecording) return;
this.isRecording = false;
this.recorderRef.pause();
this.mediaRecorder.stop();
}
}
voiceRecorder = new VoiceRecorder();
<button id="start-recognition">Hold This Button and Speak In Android This should output the text and record your voice at the s</button>
<button id="play">Play Recorded Audio</button>
<h1 id="output">Voice over here</h1>
<audio id="recorder" muted hidden></audio>
<audio id="player" hidden></audio>

How should shufflePlaylist work in the javascript?

What is the right way to set it up?
Like this?
https://jsitor.com/E8JILS8mzZ
function shufflePlaylist(player) {
player.setShuffle(true);
player.playVideoAt(0);
player.pauseVideo();
}
function onPlayerReady(event) {
const player = event.target;
player.setVolume(100);
shufflePlaylist(player);
}
or should it be written like this?
https://jsitor.com/HjrwEdaVqe
let hasShuffled = false;
function onPlayerStateChange(event) {
player = event.target;
const shufflePlaylist = true;
if (!hasShuffled) {
player.setShuffle(shufflePlaylist);
player.playVideoAt(0);
hasShuffled = true;
}
}
or is there a more proper way for the code to be written?
YouTube Documentation:
https://developers.google.com/youtube/iframe_api_reference?hl=en

How can I write this audio playing code nicer?

I want you to play it as many times as I click on it.
(1 sec long audio only.)
function a() {
var elem = document.getElementById('musicplay');
var audio = document.getElementById('music');
var playing = false;
elem.addEventListener('click', function () {
if (playing) {
audio.play();
} else {
audio.play();
}
playing = !playing;
});
}
function playMusic() {
let playBtn= document.getElementById('musicplay');
let audio = document.getElementById('music');
let playing = false;
playBtn.addEventListener('click', ()=> {
if (playing) {
audio.pause();
playing = !playing;
} else {
audio.play();
playing = !playing;
}
});
}

Javascript audio currentTime doesn't work on non-Chrome browsers

I have a problem when I use currentTime; my code below only works in google chrome. I tried other ways but with no results. Have I missed something?
function togglePlay(tid, tname) {
if (myAudio.src == 'http://yoursite.com' + tname) {
tem = myAudio.currentTime;
} else {
tem = 0;
}
myAudio.src = tname;
rid = tid;
if (isPlaying) {
myAudio.currentTime = tem;
myAudio.pause();
isPlaying = false;
document.getElementById(tid).className = "start";
} else {
myAudio.currentTime = tem;
myAudio.play();
isPlaying = true;
document.getElementById(tid).className = "stop";
}
};
I solved the problem by myself. The error was in putting out of the if myAudio.src = tname; rid = tid;
function togglePlay(tid, tname) {
if (myAudio.src == 'http://yoursite.com' + tname) {
tem = myAudio.currentTime;
} else {
tem = 0;
myAudio.src = tname;
rid = tid;
}
if (isPlaying) {
myAudio.currentTime = tem;
myAudio.pause();
isPlaying = false;
document.getElementById(tid).className = "start";
} else {
myAudio.currentTime = tem;
myAudio.play();
isPlaying = true;
document.getElementById(tid).className = "stop";
}
};

Play/pause audio file with javascript command

I have some javascript code that gets executed once somebody enters the konami code, and I want it to play if it isn't playind, and pause if it is playing. My code seems to be just wrong. Please help!
var rick = false;
var audio = new Audio('rick_roll.mp3');
var kkeys = [],
konami = "38,38,40,40,37,39,37,39,66,65,13";
$(document).keydown(function(e) {
kkeys.push(e.keyCode);
if (kkeys.toString().indexOf(konami) >= 0) {
$(document).unbind('keydown', arguments.callee);
if (rick == false) {
rick = true;
audio.play();
} else if (rick == true) {
rick = false;
audio.stop();
}
}
});
You should be doing something like this:
var rick = false;
var audio = new Audio('rick_roll.mp3');
var kkeys = [],
konami = "38,38,40,40,37,39,37,39,66,65,13";
$(document).keydown(function(e) {
kkeys.push(e.keyCode);
if (kkeys.toString().indexOf(konami) >= 0) {
kkeys = []; // <-- Change here
if (rick == false) {
rick = true;
audio.play();
} else if (rick == true) {
rick = false;
audio.pause(); // <-- another issue
}
}
});
You're unbinding the event listener after you get the code entered. You should instead clean old data and start waiting for it again.

Categories