Android html5 audio playback fail - android

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();
}

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

Autoplay of YouTube using iframe not working in android and iphones

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();
}

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.

phonegap media sound stop playing after 5 times

I need to play the "correct" sound if user answer the question correctly and "wrong" if incorrect. The sound is playing at first but after at the fifth time I answer correctly which output the fourth time "correct" sound already the fifth time, no sound can be heard. It seems the music can only played at most 4th times.
What is the possible reason that cause this?
updated*
I added media.release in my stopAudio() but so far the sound can be heard for 6th (improved) but it is still not suits my case. (Many questions that need the same sound effect)
Js.file
// Audio player
var my_media = null;
var mediaTimer = null;
// Play audio
function playAudio(src) {
// Create Media object from src
my_media = new Media(src, null, soundCB);
my_media.play();
}
function soundCB(err){
console.log("playAudio():Audio Error: "+err);
}
// Stop audio
//
function stopAudio() {
if (my_media) {
alert("AQA");
my_media.stop();
my_media.release();
}
clearInterval(mediaTimer);
mediaTimer = null;
}
/////question part//////
$("#answer").live('tap', function(event){
if(buttonAns==true) {
$this= $(this);
buttonAns = false;
var choice = $this.attr("class");
if((correctAnsNo == 0 && choice =="answer0")||(correctAnsNo == 1 && choice =="answer1")||(correctAnsNo == 2 && choice =="answer2")){
playAudio('/android_asset/www/audio/fall.mp3'); //falling sound
correct = parseInt(correct)+2;
playAudio('/android_asset/www/audio/correct.mp3'); //dingdong
}else{
playAudio('/android_asset/www/audio/wrong1.wav');
}
if(quesNo < wordsNo ){
setTimeout(function() {
buttonAns = true;
db.transaction(queryQuesDB, errorCB);
},1800);
}else{
endLevel();
}
} else {
event.preventDefault();
}
});
Android has a finite amount of resources in order to play sounds. You keep creating a new Media object each time you want to play a file. You need to release the sounds you are not using. If you need to play those sounds multiple times each then consider creating separate media objects to hold a reference to those sounds.
Read up on media.release.
I had the same problem.
The solution I did.:
if(media){
media.stop();
media.release();
}
media = new Media(...);
Here's my trick: I released it upon it finished playing or an error occurred.
function playAudio(url) {
try {
var my_media = new Media(url,
// success callback
function () {
**my_media.release();**
},
// error callback
function (err) {
**my_media.release();**
});
// Play audio
my_media.play();
} catch (e) {
alert(e.message);
}
}

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