Play sound on click in A-Frame - javascript

So I'm struggling to find a solution to play/stop/pause sound on "click" i.e. when focusing with a black dot with A-Frame sound entity... What I would like to have is a plain, shape or whatever with a play/pause image on it, which would trigger audio when focused. Did anyone encounter something similar perhaps?
<audio id="sound" crossorigin="anonymous" preload="auto" src="some-audio-file.mp3"></audio>
... would trigger something like sound="on: click; src: #sound"

try making a custom component
AFRAME.registerComponent('audiohandler', {
init:function() {
let playing = false;
let audio = document.querySelector("#audio");
this.el.addEventListener('click', () => {
if(!playing) {
audio.play();
} else {
audio.pause();
audio.currentTime = 0;
}
playing = !playing;
});
}
})
and use it within Your 'button"
<a-box audiohandler> </a-box>
You can check all media methods, properties etc here.
You can check this button here.

Related

Setting WebRTC stream in HTML5 video element sometimes shows no image and creates weird artifacts

I am making a small chatroulette clone where I have implemented a switch webcam feature. Most of the times it works, but sometimes I get no image at all including weird artifacts over whole page, not only video element.
Image: https://i.gyazo.com/87d089807c17314ff79cda2e8eaea454.png
Video: https://drive.google.com/file/d/0B3h9E32u9L9aU0lZZ0l1bUd5bDQ/view
Demo: https://codepen.io/grymer/pen/gxWzvw
Sometimes when I change the camera, ie. re-setting the video.srcObject, I get no image at all and diagonal black lines becomes visible overall the page.
This looks like a bug in Chrome. I've put together a small sample for anyone with two webcams to test (I have one real webcam and one virtual).
EDIT: Updated demo. I'm logging all events on the video element.
When everything is working like expected, I receive these events:
event: emptied
event: loadstart
event: durationchange
event: loadedmetadata
event: loadeddata
event: canplay
event: canplaythrough
When I get no image, these events have been execute:
event: emptied
event: loadstart
So why does it stop at loadstart?
Here are the demo source:
stackoverflow code snippets is not working with webrtc apparently. Go to codepen link
let deviceIds, currentDeviceId,
videoEl = document.getElementById('video'),
buttonEl = document.getElementById('button');
buttonEl.addEventListener('click', () => getUserMedia())
navigator.mediaDevices.enumerateDevices().then(devices => {
// get all video inputs
deviceIds = devices.filter(device => device.kind === 'videoinput').map(device => device.deviceId);
currentDeviceId = deviceIds.length > 0 ? 0 : -1;
}).then(() => {
getUserMedia();
});
function getUserMedia() {
const constraints = {
audio: true,
video: {
deviceId: deviceIds[currentDeviceId]
}
};
currentDeviceId = currentDeviceId === 0 ? 1 : 0;
navigator.mediaDevices.getUserMedia(constraints).then(stream => {
videoEl.srcObject = null;
videoEl.srcObject = stream;
});
}
body {
background: black;
color: white;
}
<video id="video" width=200 height=200></video>
<button id="button">change</button>
<p>You need two webcams for this demo.</p>
Add a .catch(e => console.error(e)) to the getUserMedia call. Possibly the device can not be opened yet which if I recall correctly results in a TrackStartError.
You might also want to stop all tracks of the current video object, i.e. videoEl.srcObject.getTracks.forEach(t => t.stop())
to avoid opening the device too often.

How to pause/stop playing audio and replace with new audio file

So when the user clicks a button an audio file plays from an array of audio files(around 2 sec clip), which works fine. However, if the user repeatedly clicks the button, the audio files start to play over each other. Ideally, I would like to stop/pause the previous audio file and then play the new audio file. This is what I've tried to avail:
$scope.sounder=function(){
$scope.rs=$scope.diff[$scope.workout_index].audiorep;
$scope.ms=$scope.diff[$scope.workout_index].audiomove;
//var movesound = new Audio ($scope.ms);
//ar repsound = new Audio ($scope.rs);
var movesound = new Media($rootScope.getMediaURL($scope.ms));
var repsound = new Media($rootScope.getMediaURL($scope.rs));
if($scope.muter==0){
movesound.pause();//DOES NOT WORK
movesound.stop();//STOPS ALL AUDIO FROM PLAYING, SO NOTHING PLAYS
$timeout(function() {
movesound.play();
}, 1000);
$timeout(function() {
repsound.play();
}, 3000);
}
if($scope.muter==1){
console.log("Rachel has been muted");
return;
}
}
You can achieve the functionalities with JavaScript in Cordova unless you specifically need AngularJS in your app.
<audio controls id="myAudio">
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the HTML5 audio tag.
</audio>
Now using script to add functionalities -
<script>
var aud= document.getElementById("myAudio");
function playAud() {
aud.play();
}
function pauseAud() {
aud.pause();
}
function myFunction() {
isSupp = aud.canPlayType("audio/mp3");
if (isSupp == "") {
aud.src = "audio.ogg";
} else {
aud.src = "audio.mp3";
}
aud.load();
}
</script>
See other answers of this question on for changing source of audio with JavaScript.
Refer w3schools HTML Audio Video DOM reference Page for further attributes and functions.

Turn off volume control and mute button in HTML5 video

We have some videos playing great in our HTML mobile app. However, our videos don't have sound, just subtitles, so we need to remove the volume slider and mute button but keep the timer bar.
Can this be done or toggled with HTML or CSS? Or is some javascript required to do this?
At the moment the setting within our html tag is just: controls="controls"
This has worked:
video::-webkit-media-controls-volume-slider {
display:none;
}
video::-webkit-media-controls-mute-button {
display:none;
}
Super easy:
Your html should be something like:
<video id="Video1">
<source src="..." type="video/mp4">
<source src="..." type="video/ogg">
Your browser does not support HTML5 video.
</video>
Add then a customized button to play the video:
<button id="play" onclick="vidplay()">></button>
Finally a progress bar:
<progress id="progressbar" value="0" max="100"></progress>
Then in javascript add a button to play
var video = document.getElementById("Video1");
function vidplay() {
var button = document.getElementById("play");
if (video.paused) {
video.play();
button.textContent = "||";
} else {
video.pause();
button.textContent = ">";
}
}
And a listener to update the progress bar:
video.addEventListener('timeupdate', updateProgressBar, false);
function updateProgressBar() {
var progressBar = document.getElementById('progressbar');
var percentage = Math.floor((100 / mediaPlayer.duration) * mediaPlayer.currentTime);
progressBar.value = percentage; progressBar.innerHTML = percentage + '% played';
}
So basically remove the "standard controls" and create your own ones.
If you wanted to achieve more complicated results, I would recommend you another option. This could be using a more configurable setting such as video.js.
Remove the controls attribute from the video element completely.
Try Here: http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_video_controls. Remove the "controls" attribute and the bar will disappear.

How to add a mute button to my app?

I have a few events in my app that make sounds.
For example,
Background music which is looped
Background on click makes a sound
When two rectangles collide it makes a sound
What i want to have is a button which when clicked toggles between letting the sounds play and not letting them play.
I don't want to have a load of if statements on each sound, so is there a way around this ?
Here is how im calling my sounds at the moment
//HTML
<div id='mainRight'></div>
//JS
var mainRight = $('#mainRight');
$(mainRight).width(windowDim.width/2).height(windowDim.height);
$(mainRight).addClass('mainRight');
var sounds = {
coinHit : new Audio('./sound/coinCollect.wav'),
playerClick : new Audio('./sound/playerClick.wav'),
gameOver : new Audio('./sound/gameOver.wav'),
backgroundMusic : new Audio('./sound/backgroundMusic.wav')
}
sounds.backgroundMusic.addEventListener('ended', function() {
this.currentTime = 0;
this.play();
}, false);
sounds.backgroundMusic.play();
sounds.backgroundMusic.volume = 0.01;
$('#mainRight').click(function()
{
sounds.playerClick.load();
sounds.playerClick.play();
}
Try this...
function toggleAudio() {
for(var key in sounds) {
sounds[key].muted = !sounds[key].muted;
}
}
Just fire that every time you hit the mute button. It will toggle the muted state of each Audio object in the sounds object.

Dailymotion video autoplay and muted

I am currently working on a project where i need to display a Dailymotion video that is automatically launched in muted mode. According to the documentation - http://www.dailymotion.com/doc/api/sdk-javascript.html - the DM.player is able to manipulate the volume of a video (method: setMuted(muted)). However, after many changes in my code, i cannot figure out how this works.
Have you ever done this before ? Could you provide some help please ?
Thanks
Here is my code:
<html>
<head>
<script src="http://api.dmcdn.net/all.js"></script>
</head>
<body>
<div id="myPlayer"></div>
<script>
// This function init the player once the SDK is loaded
window.dmAsyncInit = function() {
// PARAMS is a javascript object containing parameters to pass to the player if any (eg: {autoplay: 1})
var player = DM.player("myPlayer", {video: "xz0ytt", width: "480", height: "270"});
// 4. We can attach some events on the player (using standard DOM events)
player.addEventListener("apiready", function(e) {
// alert(e.target.muted);
// e.target.muted = true;
// alert(e.target.muted);
// e.target.play();
// player.setMuted(1);
player.setMuted("1");
e.target.play();
});
};
</script>
</body>
</html>
The method you are trying to use can only work after the video is playing. Hence, you have to listen to the event "play" to mute the video.
try the following:
player.addEventListener("apiready", function(e) {
e.target.play();
});
player.addEventListener('play', function(e){
e.target.setMuted(1);
});
the advertisement (if any) at the beginning can't be muted though,

Categories

Resources