PhoneGap, Play Audio, Stop Audio - javascript

I have created a mobile application using phonegap. I planned to create two buttons, one to play the sound and another one to stop the sound. i tried several methods but none worked. I tried using code stated below, but didn't work also.
Javascript:
function playAudio(src) {
if (device.platform == 'Android') {
src = '/android_asset/' + src;
}
var media = new Media(src, success, error_error);
media.play();
}
function success() {
// ignore
}
function error_error(e) {
alert('great error');
alert(e.message);
}
function stopAudio() {
if (media) {
var media = new Media(src, success, error_error);
media.stop();
}
}
HTML:
<button onclick="playAudio('BackgroundMusic.mp3') "id="play" ></button>
<button onclick="stopAudio()"id="pause" ></button>
Can anyone help me to sort this out?

Related

The element has no supported sources when assigning video later on execution

I understand that is a question that has been asked many times but after searching for a long time on "similar questions" none seemed to solve my problem. Here's my situation:
I need to play a video after the user clicks on a "Play Button". I can't use the video's location directly on src on the <video> tag.
<video id="videoPlayer" controls autoplay></video>
I also have a VideoPlayer class that handles some information, including the video element.
function VideoPlayer(root, play) {
this._play = play;
this._root = root;
this._root.style.display = "none";
}
Which is created with:
const videoPlayer = new VideoPlayer(document.getElementById("videoPlayer"), document.querySelector("#play"));
The second element being the play button.
I've also added to the prototype of VideoPlayer a play function:
VideoPlayer.prototype.play = function (url, immediate) {
const root = this._root;
const play = this._play;
root.style.visibility = "visible";
root.src = url;
play.style.display = null;
once(play, "click", function () {
root.play();
});
return new Promise(function (resolve, reject) {
function ok() {
play.style.display = "none";
root.style.display = null;
clear();
}
function fail(error) {
clear();
reject(error);
}
function clear() {
root.removeEventListener("play", ok);
root.removeEventListener("abort", fail);
root.removeEventListener("error", fail);
}
root.addEventListener("play", ok);
root.addEventListener("abort", fail);
root.addEventListener("error", fail);
once(root, "ended", function () {
root.style.display = "none";
resolve();
});
});
};
And, after I finally get the video's location, which is something like videos/video1.mp4 or videos/video2.mp4 I call the play function using:
const initialVideo = "videos/mov_bbb.mp4";
if (initialVideo.length > 0) {
videoPlayer.play(initialVideo);
}
Exactly after calling the function, an error in thrown. After using breaking points I've tracked to this line:
root.src = url;
The problem doesn't seem to happen with external videos, I've tested using this video from W3School: https://www.w3schools.com/html/mov_bbb.mp4 and then downloaded the video to use it locally. When it's external it works, when it's local, does not... throwing "The element has no supported sources".
I've tried to export the same video using different codecs and extensions. This problem only happens on Chrome, Mozilla is working just fine. I can access the file via localhost:port/videos/mov_bbb.mp4 but it does not play. I'm using static-server-advance to serve the files. But I've also added to a different server to test it.
My chrome version is: 83.0.4103.10 and I'm not using any extensions.
I'm unable to use php or node.

A-Frame - playing / pausing sound with a custom ('a-sound') source

Edit 2: Here is the working code. Many thanks to Piotr for his help I couldn't have done it so effortlessly without you guys.
sceneEl.querySelector('a-sound').setAttribute('sound', {src:url3});
let playing = false;
var el = document.querySelector('a-box');
let audioEl = document.querySelector("a-sound");
var audio = audioEl.components.sound;
el.addEventListener('click', () => {
if (!playing) {
audio.playSound();
} else {
audio.stopSound();
}
playing = !playing;
})
} );
request.send( null );
}
});
Edit: I've got the sound playing from a dynamic URL (in my JSON file), but I cant seem to get the event listener function right (for playing / pausing on click).
sceneEl.querySelector('a-sound').setAttribute('sound', {src:url3});
let audioEl = document.querySelector("a-sound");
let audio = audioEl.components.sound;
sceneEl.querySelector('a-box').addEventListener('click', function () {
if(!playing) {
audio.play();
} else {
audio.pause();
audio.currentTime = 0;
}
playing = !playing;
});
} );
request.send( null );
}
});
Original: I'm using this component in A-Frame, but I'm looking to play the sound from the src in the ('a-sound') entity rather than from the asset link. The reason is because I'm loading the sound files dynamically from a JSON array so they don't exist in any list of assets. I've got all my files loading but am having trouble getting this component to hook into my loaded sceneEl.querySelector('a-sound').setAttribute('sound', {src:url3}); code. I'm thinking its just a small syntax issue but I'm not 100% sure. Could someone please look over this for a minute and tell me if its doable? This is the code (same as the link except for the (a-sound) within the querySelector.
AFRAME.registerComponent('audiohandler', {
init:function() {
let playing = false;
let audio = document.querySelector('a-sound');
this.el.addEventListener('click', () => {
if(!playing) {
audio.play();
} else {
audio.pause();
audio.currentTime = 0;
}
playing = !playing;
});
}
})
</script>
Using the <a-sound> You must handle things a bit differently.
playing / stopping the sound should be done within the sound component. You need to access it via yourEntityName.components.sound and use the playSound() and stopSound() methods.
check it out on my glitch. I set the source via the setAttribute(), and make a play / stop button.
My <a-sound> has a geometry to be a button, but You can make a <a-sound> entity, and use it like this:
let audioEl = document.querySelector("a-sound");
audioEl.setAttribute("src", "sourceURL");
let audio = audioEl.components.sound;
// play = audio.playSound();
// stop = audio.stopSound():
Furthermore, there are many issues with the nodes not being fully loaded. Check out this example:
<a-entity component></a-entity>
<a-sound></a-sound>
If the component tries to grab a reference to the document.querySelector("a-sound").components.sound, it may be undefined. If so, You should try to wait until it emits the loaded signal.

Multiple Audio files on HTML page, need for only one to play at a time

I have multiple audio files that play when clicked using the following javascript code:
function playSound(el,soundfile) {
if (el.mp3) {
if(el.mp3.paused) el.mp3.play();
else el.mp3.pause();
} else {
el.mp3 = new Audio(soundfile);
el.mp3.play();
}
}
The problem is that when two are clicked both audio files will play simultaneously. I need for the first audio file to stop playing when the second is clicked.
What do I need to add to this code.
I haven't used the sound API from HTML5 yet, so this is just to get my point across.
So, Like I said in my comment, you could add all elements to a global array and pause them like that.
var audio = [];
function playSound(el,soundfile) {
// Pause all
if (el.mp3) {
if(el.mp3.paused) {
// Pause all sounds
pauseAllSounds();
el.mp3.play();
// Add the sound to the audio array
audio.push(el);
// You should probably clean up the audio array too,
// so no two identical audio files exists in the array,
// but that's up to you! :)
}
else el.mp3.pause();
} else {
el.mp3 = new Audio(soundfile);
el.mp3.play();
}
}
function pauseAllSounds(){
audio.forEach(function(el){
if(!el.mp3.paused) el.mp3.pause();
});
}

How to pause a youtube video on playing other video in page having multiples videos

I have 6 videos in a page which are created using SWFOBJECT API.
The requirement is to pause a video when another video is played.
for ex: swfobject for video is
<DIV id=ytcontainer></DIV>
<SCRIPT>
swfobject.embedSWF("http://www.youtube.com/v/erDxb4IkgjM?version=3&f=user_uploads&app=youtube_gdatafs=1&rel=0&enablejsapi=1&playerapiid=myytplayer", "ytcontainer", "660", "394", "8", null, null, {allowscriptaccess:"always",allowfullscreen:"true",wmode:"opaque"}, {id:"myytplayer"});
</SCRIPT>
like this way, i have 6 videos in a single page
below is the code for pausing video
<script>
swfobject.addLoadEvent(onYouTubePlayerReady);
var status;
var videostate2=0; var videostate1=0;
function onYouTubePlayerReady(playerId)
{
var myPlayer1 = document.getElementById('myytplayer');
var myPlayer2 = document.getElementById('qualityvideotrack');
myPlayer1.addEventListener("onStateChange", "onytplayerStateChange1");
myPlayer2.addEventListener("onStateChange", "onytplayerStateChange2");
}
function onytplayerStateChange1(newState)
{
if(newState1==1)
{
videostate1=1;
pause();
}
else
videostate1=0;
return videostate1;
}
function pause()
{
var state;
console.log("pause");
var myPlayer2 = document.getElementById('qualityvideotrack');
var myPlayer1 = document.getElementById('myytplayer');
if(videostate2==1)
{
state=onytplayerStateChange2(videostate2);
console.log("Player's new state:2 before pause "+state);
if(state==1)
myPlayer2.pauseVideo();
}
if(videostate1==1)
{
state=onytplayerStateChange1(videostate1);
console.log("Player's new state:1 before pause "+state);
if(state==1)
myPlayer1.pauseVideo();
}
}
function onytplayerStateChange2(newState2)
{
if(newState2==1)
{
videostate2=1;
pause();
}
else
videostate2=0;
return videostate2;
}
</script>
the above mentioned code won't work properly. However, if i write the code to stop one video while other is playing it works but vice versa not. Kindly suggest me.

How to mute/unmute sound of an audio using javascript

I have created a fiddle of my function here( http://jsfiddle.net/rhy5K/10/ ) . Now i want to provide the Sound "Mute/unpute" option for users. Example if i click on "a link then sound playing like Get ready,5,4,3,2,1 should be mute and vice-versa.
I am thinking like to call a to toggle_sound function on click, but i am confuse like what should i write inside the function to mute the sound.
Please provide me a logic, or a solution for my problem.
Explanation using code example:
I want to MUTE/UnMUTE this below sound playing
var playGetReady = function (done) {
var ids = ['audiosource', 'a_5', 'a_4', 'a_3', 'a_2', 'a_1'],
playNext = function () {
var id = ids.shift();
document.getElementById(id).play();
if (ids.length) {
setTimeout(playNext, 1000);
} else {
done();
}
};
playNext();
};
Warning: This JS fiddle demo may play sound on load
Try
HTML5 Video_tag for display video with audio
or
this below example along with html5 with jquery
window.my_mute = false;
$('#my_mute_button').bind('click', function(){
$('audio,video').each(function(){
if (!my_mute ) {
if( !$(this).paused ) {
$(this).data('muted',true); //Store elements muted by the button.
$(this).pause(); // or .muted=true to keep playing muted
}
} else {
if( $(this).data('muted') ) {
$(this).data('muted',false);
$(this).play(); // or .muted=false
}
}
});
my_mute = !my_mute;
});
I think you can use:
document.getElementById(id).volume = 1;
or
document.getElementById(id).volume = 0;

Categories

Resources