Autoplay of YouTube using iframe not working in android and iphones - android

I am using jquery to load YouTube Video through iframe to reduce the initial page load time. Using this approach – only the video thumbnail is loaded along with the page and the actual player loads when the user hits the play button. But AutoPlay is not working on Android and Iphones though it is perfectly working on desktops using windows. When I googled this problem, it turns out "Chrome and Safari browsers on iPhone and Android only allow playback of HTML5 video when initiated by a user interaction. They block embedded media from automatic playback to prevent unsolicited downloads over cellular networks." I want to autoplay the video. Please help.
Here is my jquery
document.addEventListener("DOMContentLoaded",
function() {
var div, n,
v = document.getElementsByClassName("youtube-player");
for (n = 0; n < v.length; n++) {
div = document.createElement("div");
div.setAttribute("data-id", v[n].dataset.id);
div.innerHTML = YouTubeThumb(v[n].dataset.id);
div.onclick = YouTubeIframe;
v[n].appendChild(div);
}
});
function YouTubeThumb(id) {
var thumb = '<img src="https://i.ytimg.com/vi/ID/mqdefault.jpg">',
play = '<div class="play"></div>';
return thumb.replace("ID", id) + play;
}
function YouTubeIframe() {
var iframe = document.createElement("iframe");
var embed = "https://www.youtube.com/embed/ID?autoplay=1";
iframe.setAttribute("src", embed.replace("ID", this.dataset.id));
iframe.setAttribute("frameborder", "0");
iframe.setAttribute("allowfullscreen", "1");
this.parentNode.replaceChild(iframe, this);
}
and the HTML
<div class="youtube-player" data-id="YouTube_Video_ID"></div>

try this example:-
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}

Related

Audio Play and Pause Ionic Creator app (Audio Streaming - Radio App )

I am developing a radio app using ionic creator.
audio play function works ok, but I need to pause to audio
Another question:
Double clicking to listen to two tunes at once?
this is audio play function,
function ($scope, $stateParams) {
$scope.playWebAudio = function(){
try{
$scope.audio = new Audio('Audio stream URL');
$scope.audio.play();
}
catch(e){
alert(e);
console.log(e);
}
}
play button
ng-click playWebAudio()
Strop Audio you have to use $cordovaMedia plugin instead of $cordovaNativeAudio
now you have to do like this:
module.controller('MyCtrl', function($scope, $cordovaMedia) {
var src = "/src/audio.mp3";
var media = $cordovaMedia.newMedia(src);
var iOSPlayOptions = {
numberOfLoops: 2,
playAudioWhenScreenIsLocked : false
}
media.play(iOSPlayOptions); // iOS only!
media.play(); // Android
media.pause();
media.stop();
media.release();
media.seekTo(5000); // milliseconds value
media.setVolume(0.5);
media.startRecord();
media.stopRecord();
media.getDuration();
media.getCurrentPosition().then(...);
});
for more detail refer to this tlink enter link description here

Cordova/Phonegap YouTube iframe_api error: XMLHttpRequest cannot load chrome-extension Cross origin requests are only supported for HTTP

I am trying to use the a YouTube iframe API with my cordova-android project. When I run the code in a browser on my computer it runs perfectly, but when i build my app and run it on my phone the page containing the iframe will not load, and i get the following error in my console:
XMLHttpRequest cannot load chrome-extension://boadgeojelhgndaghljhdicfkmllpafd/cast_sender.js. Cross origin requests are only supported for HTTP
Here is my code:
<div class='ui-body ui-body-a'>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
console.log('Loaded Video)
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
</div>
Thanks in advance!
I got it to work by using glitchbone's cordova plugin YoutubeVideoPlayer.

Big delay executing sound on iPad and Android

I want to play a sound when the user click on a image. I'm using SoudManager plugin.
Here you can check what I'm doing:
soundManager.setup({
url: 'swf',
onready: function() {
soundCarro = soundManager.createSound({
id: 'soundCarro',
url: 'sound/carro_camona.mp3'
});
soundMoto = soundManager.createSound({
id: 'soundMoto',
url: 'sound/moto_camona.mp3'
});
soundNautico = soundManager.createSound({
id: 'soundNautico',
url: 'sound/nautico_camona.mp3'
});
}
});
As you can see, I create 3 sound objects (soundCarro, soundMoto and soundNautico).
Here the action, where when the user clicks on it, the scrollTo function is called:
<img id="ca" class="ca logo" onclick="scrollTo('secao-carros',true);" src="images/svg/CAhome.svg">
Here you can see the scrollTo function:
function scrollTo(target,sound){
if(sound){
var delay = 0;
if(target == 'secao-carros'){
soundCarro.play();
delay = 700;
duration = 750;
}
if(target == 'secao-motos'){
soundMoto.play();
delay = 900;
duration = 750;
}
if(target == 'secao-nauticos'){
soundNautico.play();
delay = 850;
duration = 2000;
}
$('html, body').delay(delay).animate({ scrollTop: $('#'+target).offset().top }, {duration: duration});
}else{
$('html, body').animate({ scrollTop: $('#'+target).offset().top }, {duration: 750});
}
}
As you can see, in this function I execute the sound object created (ex: soundNautico.play();).
The issue is that on iPad and Android devices this sound gets a big delay to execute, but in desktop browsers it works perfect!
How can I prevent this delay?
That's because desktop browsers will preload the audio so when you call .play() the browser will begin playing it immediately because it has already buffered some (if not all) of the audio.
I know that iOS and most other mobile browsers will A) only allow you to play a single audio file at a time, B) not allow you to cache audio at all, and C) only allow you initialize/play an audio object if the user physically initiated the action on the same call stack. So you're basically out of luck if you don't want the delay.
Edit: You could add an event listener to the audio and only trigger the scroll after the audio had buffered. However, you cannot load more than one sound at a time.
audio.addEventListener("canplay", function(e) {
doScroll();
audio.play();
}, false);
```

Android html5 audio playback fail

I made a html page ,and put an audio tag in it then I try to use my android browser to play some music .
But it doesn't work. Here is my code:
<audio id='simple-audio-player' src="http://m.html5/baidu.mp3" controls="controls" preload="metadata"></audio>
window.onload = function () {
var au = document.getElementById("simple-audio-player");
au.load();
if(au.networkState != au.NETWORK_NO_SOURCE){
alert('au.networkState != au.NETWORK_NO_SOURCE');
try{
au.play();
}catch(err){
alert(err);
}
}else{
alert('au.networkState == au.NETWORK_NO_SOURCE');
}
};
I think it would be something wrong with my IIS config ,but I not sure.
You can't play audio from the window load event, it has to happen in response to a user interaction.
Like this...
window.addEventListener('ontouchstart', onStart);
function onStart()
{
var audio = new Audio(); // --or-- document.getElementById('id-of-audio-tag');
audio.src = "test.mp3";
audio.play();
}

html5 audio element return src with jquery

I am converting some HTML5 to work with Android. Android does not support the element, so the play method does not function.
I am using PhoneGap's media element, and that does play audio. What I want, is a way to find the first source of the audio tag, and then use that with media play, but this does not seem to work.
function playSound(whatToPlay) {
// removed since <audio does not work
// var snd = document.getElementById(whatToPlay);
// snd.play();
toPlaySrc = $("#"+whatToPlay+":first-child").eq(0).attr("src");
// next I will have to deal with /android_asset and my current partial path
myMedia = new Media("/android_asset/"+toPlaySrc, onSuccess,onError);
if (myMedia)
myMedia.play();
}
playSound("clockticking");
this is my audio element.
<audio id="clockticking" preload="auto" autobuffer onEnded="instructionFinsihed()">
<source src="../sound/tictoc.mp3" type="audio/mp3" />
<source src="../sound/tictoc.ogg" type="audio/ogg" />
</audio>
I have many existing audio elements, so a general solution would really be important, I can not, for instance just ad id tags to all the mp3 elements and solve it.
Okay, I'm working on some monkey patch code for the Android WebView, you can see the progress over on my corinthian github project. In the meantime what you'd want to do is setup a on deviceready listener:
document.addEventListener("deviceready", monkeypunch, true);
create an array to hold the media objects:
mediaObjs = [];
and in the monkeypunch method you would do:
function monkeypunch() {
var audioclips = document.getElementsByTagName("audio");
for (var i=0; i < audioclips.length; i++) {
// Create new Media object.
var audioSrc = audioclips[i].firstElementChild.src;
if (audioSrc.indexOf("file:///android_asset") == 0) {
audioSrc = audioSrc.substring(7);
}
mediaObjs[audioSrc] = new Media(audioSrc);
// Create the HTML
var newAudio = document.createElement('div');
var newImg = document.createElement('img');
newImg.setAttribute('src', 'images/play.png');
newAudio.appendChild(newImg);
// Set the onclick listener
newAudio.addEventListener("click", function() {
// figure out what image is displayed
if (newImg.src.indexOf("images/play.png", newImg.src.length - "images/play.png".length) !== -1) {
newImg.src = "images/pause.png";
mediaObjs[audioSrc].play();
} else {
newImg.src = "images/play.png";
mediaObjs[audioSrc].pause();
}
});
// replace the audio tag with out div
audioclips[i].parentNode.replaceChild(newAudio, audioclips[i]);
}
}
You can grab the play/pause images from my github project. I'm planning on adding more functionality when I have some more time.

Categories

Resources