Hi i try to add sound to my game i used aphoneGap code to do it :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Media Example</title>
<script type="text/javascript" charset="utf-8" src="js/phonegap-1.4.1.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//
function onDeviceReady() {
playAudio("http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3");
}
// Audio player
//
var my_media = null;
var mediaTimer = null;
// Play audio
//
function playAudio(src) {
// Create Media object from src
my_media = new Media(src, onSuccess, onError);
// Play audio
my_media.play();
// Update my_media position every second
if (mediaTimer == null) {
mediaTimer = setInterval(function() {
// get my_media position
my_media.getCurrentPosition(
// success callback
function(position) {
if (position > -1) {
setAudioPosition((position) + " sec");
}
},
// error callback
function(e) {
console.log("Error getting pos=" + e);
setAudioPosition("Error: " + e);
}
);
}, 1000);
}
}
// Pause audio
//
function pauseAudio() {
if (my_media) {
my_media.pause();
}
}
// Stop audio
//
function stopAudio() {
if (my_media) {
my_media.stop();
}
clearInterval(mediaTimer);
mediaTimer = null;
}
// onSuccess Callback
//
function onSuccess() {
console.log("playAudio():Audio Success");
}
// onError Callback
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
// Set audio position
//
function setAudioPosition(position) {
document.getElementById('audio_position').innerHTML = position;
}
</script>
</head>
<body>
<a href="#" class="btn large"
onclick="playAudio('http://audio.ibeat.org/content/p1rj1s/p1rj1s_-
_rockGuitar.mp3');">Play Audio</a>
Pause Playing Audio
Stop Playing Audio
<p id="audio_position"></p>
</body>
</html>
it works fine , but when i change the source of sound it didn't work here's the code :
playAudio("file:///android_asset/www/sounds/introDino.mp3");
Any idea please,
Thank you in advance
Change your path to "/android_asset/www/sounds/introDino.mp3" and it will be fine. Read my mini tutorial for Android:
http://simonmacdonald.blogspot.com/2011/05/using-media-class-in-phonegap.html
This function will play sound using the HTML5 Audio API if available, with fallback to the PhoneGap Media API if not:
function playAudio(src) {
// HTML5 Audio
if (typeof Audio != "undefined") {
new Audio(src).play() ;
// Phonegap media
} else if (typeof device != "undefined") {
// Android needs the search path explicitly specified
if (device.platform == 'Android') {
src = '/android_asset/www/' + src;
}
var mediaRes = new Media(src,
function onSuccess() {
// release the media resource once finished playing
mediaRes.release();
},
function onError(e){
console.log("error playing sound: " + JSON.stringify(e));
});
mediaRes.play();
} else {
console.log("no sound API to play: " + src);
}
}
Due fact that Audio object on new Android versions (may be on other platforms) available and not 'undefined' both previous answers will not work. So I upgraded code to :
function playSound(src){
var devicePlatform = (typeof device !== 'undefined' && device.platform)? device.platform: null;
if (typeof Audio !== "undefined" && devicePlatform === null) { // HTML5 Audio
new Audio(src).play() ;
} else if ( devicePlatform ) { // Phonegap media
if (devicePlatform === 'Android') { // Android needs the search path explicitly specified
src = '/android_asset/www/' + src;
}
var media = new Media(src,
function onSuccess() {
media.release(); // Release the media resource once finished playing
},
function onError(e){
console.log("error playing sound: " + JSON.stringify(e));
}
);
media.play({numberOfLoops: 1});
} else {
console.log("no sound API to play: " + src);
}
}
Also must say that before all you must add to cordova build 'device' and 'media' plugins otherwise nothing will work. Plugins available here
Related
I am working on media source extension to play the video in a seamless loop without any delay. I have done an extensive r&d about it and also done different things. Now i am working on this code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<video controls></video>
<script>
var video = document.querySelector('video');
var assetURL = 'test1.mp4';
// Need to be specific for Blink regarding codecs
// ./mp4info frag_bunny.mp4 | grep Codec
var mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
if ('MediaSource' in window && MediaSource.isTypeSupported(mimeCodec)) {
var mediaSource = new MediaSource;
//console.log(mediaSource.readyState); // closed
video.src = URL.createObjectURL(mediaSource);
mediaSource.addEventListener('sourceopen', sourceOpen);
} else {
console.error('Unsupported MIME type or codec: ', mimeCodec);
}
function sourceOpen (_) {
//console.log(this.readyState); // open
var mediaSource = this;
var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
fetchAB(assetURL, function (buf) {
sourceBuffer.addEventListener('updateend', function (_) {
mediaSource.endOfStream();
video.play();
//console.log(mediaSource.readyState); // ended
});
sourceBuffer.appendBuffer(buf);
});
};
function fetchAB (url, cb) {
console.log(url);
var xhr = new XMLHttpRequest;
xhr.open('get', url);
xhr.responseType = 'arraybuffer';
xhr.onload = function () {
cb(xhr.response);
};
xhr.send();
};
</script>
</body>
</html>
It is working fine but the video is playing again with a slight delay. I want to play the video without any delay and I know that it is possible with media source extensions but after spending a lot of time still didn't get any idea that how to do it. Any help would be really appreciated. Thanks
Setting the mode value to sequence worked for me, it ensures continuous media playback, no matter if the media segment timestamps were discontinuous.
sourceBuffer.mode = 'sequence';
May be this code solve Your Problem ....play the video in a seamless loop without any delay
for (let chunk of media) {
await new Promise(resolve => {
sourceBuffer.appendBuffer(chunk.mediaBuffer);
sourceBuffer.onupdateend = e => {
sourceBuffer.onupdateend = null;
sourceBuffer.timestampOffset += chunk.mediaDuration;
console.log(mediaSource.duration);
resolve()
}
})
}
if you need more information visit this link.....
http://www.esjay.org/2020/01/01/videos-play-without-buffering-in-javascript/
You can't really do that because it really depends on how fast your PC runs. Its delay should only be there if you have a slow PC but if not it shouldn't have a noticeable delay. Maybe the video that you have is big or it just delays inside the video because only thing I could tell you is autoplay loop inside the videos element as a attribute unless you find a way to replay the video before the video ends but even if it doesn't delay for you it may delay big or just play over the video for others
#CoolOppo
The simplest thing to do is to just rewind the video when it reaches it's end time (duration).
See demo here: https://vc-lut.000webhostapp.com/demos/public/mse_loop_example1.html
(to play video just click the picture part, since no controls for looping background)
The code:
<!DOCTYPE html>
<html>
<head> <meta charset="utf-8"/> </head>
<body>
<div>
<video id="video_mse" > </video>
</div>
<script>
var assetURL = "testloop.mp4";
//# use correct mime/codecs or else Error is "source not open"...
var mimeCodec = 'video/mp4; codecs="avc1.42C01E"';
var mediaSource; var sourceBuffer;
var video = document.getElementById( "video_mse" );
video.onclick = vid_togglePlay; //# for playing/pausing
video.ontimeupdate = vid_checkTime; //# for looping
//# handle play/pause (because controls are hidden)
function vid_togglePlay()
{
if( video.paused == true ) { video.play(); }
else { video.pause(); }
}
//# handle looping...
function vid_checkTime()
{
if( video.currentTime == video.duration)
{
video.currentTime = 0;
video.play();
}
}
if ( 'MediaSource' in window && MediaSource.isTypeSupported(mimeCodec) )
{
mediaSource = new MediaSource;
video.src = URL.createObjectURL(mediaSource);
mediaSource.addEventListener('sourceopen', sourceOpen);
}
else
{ console.error('Unsupported MIME type or codec: ', mimeCodec); }
function sourceOpen()
{
//console.log(this.readyState); // open
var mediaSource = this;
sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
fetchAB(assetURL, function (buf) {
sourceBuffer.addEventListener('updateend', function() {
mediaSource.endOfStream();
video.play();
});
sourceBuffer.appendBuffer(buf);
});
};
function fetchAB (url, callbackfunc )
{
console.log("loading file: " + url);
var xhr = new XMLHttpRequest;
xhr.open('get', url);
xhr.responseType = 'arraybuffer';
xhr.onload = function() { callbackfunc( xhr.response ); }
xhr.send();
}
</script>
</body>
</html>
For some reason i do not know my audio files fails to play after compiling. I upload my files over to the build over some months ago and after the compilation, the audio was playing.
Just yesterday i upload the same files again with a little bit of changes but no changes made to the audio script and its failing to playing after the download.
I get this error code:1 message undefined
music.js
// JavaScript Document
`enter code here` // Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
//function onDeviceReady() {
// playAudio(cordova.file.applicationDirectory + "Playlist/music/Eminado.mp3");
// }
function play2face() {
playAudio('/android_asset/www/Playlist/music/African Queen.mp3');
}
// Audio player
var my_media = null;
var mediaTimer = null;
// Play audio
//
function playAudio(url) {
// Create Media object from url
stopAudio()
my_media = new Media(url, onSuccess, onError);
// Play audio
my_media.play();
}
// Pause audio
//
function pauseAudio() {
if (my_media) {
this.my_media.pause();
}
}
// Stop audio
//
function stopAudio() {
if (my_media) {
this.my_media.stop();
}
clearInterval(mediaTimer);
mediaTimer = null;
}
// onSuccess Callback
//
function onSuccess() {
console.log("playAudio():Audio Success");
}
// onError Callback
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
HTML
Play Music | Stop Music
I've got cordova.js too in the head section of my index.html
also i have these plugins included in the config.xml
<plugin name="nl.nilscorver.cordova.media" spec="0.2.18" source="pgb" />
<plugin name="br.com.paveisitemas.splashscreen" spec="2.1.1" source="pgb" />
<plugin name="org.apache.cordova.inappbrowser" spec="0.6.0" source="pgb" />
<plugin name="com.surfernetwork.fileplugin" spec="1.0.2" source="pgb" />
any help on how to make it play?
I'm not a JS expert so I can't really help you there, but I will add that android has a built-in Music player class that you should use when playing audio. I'm sorry I can't help more :(
I have a simple mobile app designed using PhoneGap. I am some mp3 in it and I am using the Media plugin of PhoneGap. Everything is working fine, the audio is playing and so on.
The issue, I noticed after playing 8-12 times, the audio stops playing. I do not get sound. Here are my codes:
JavaScript
<script>
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
}
// Audio player
var media = null;
var audioP = false;
// Play audio
function playAudio(src) {
if (audioP === false) {
media = new Media(src, onSuccess, onError);
media.play();
audioP = true;
} else {
media.release();
}
}
// onSuccess Callback
function onSuccess() {
console.log("playAudio():Audio Success");
audioP = false;
}
// onError Callback
function onError(error) {
}
</script>
Help please!
I'm having problems enqueuing a playlist using the YouTube IFrame API.
(https://developers.google.com/youtube/iframe_api_reference#Queueing_Functions)
I'm using flash to show the youtube videos. Using HTML5 shows another issue where the videoplayback call is called multiple times before the video loads.
On loading the playlist, the video itself doesn't load. It shows up in the network tab
as a call to videoplayback that is 'pending' until it times out after 7.5 minutes at which point it tries again and everything works. The playlist, incidentally, has loaded successfully - mousing over the youtube iframe shows a loaded playlist.
The code to replicate this is below, and the issue is found following these steps:
1. Click a channel
2. If channel loads, goto 1, else check network tab.
I know the method of replication is contrived, however I'm seeing this 'sometimes'
on first load.
The playing channel isn't at fault - this has been seen with many different channels.
Is it my code? Is there a work around? Is there a fix?
Tested on Windows 7 32bit using Chrome 28, Firefox 22.0 and IE 10
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<title>
Youtube Test
</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type='text/javascript'>
var collection = [];
var player = null;
var playlistEnqueued = false;
function clear() {
// Removes the iframe.
if (player !== null) {
player.destroy();
}
collection = [];
playlistEnqueued = false;
player = null;
}
function createYT(videoId) {
// Clear anything that's up currently
clear();
// Yes, this could be $.ajax, however this way reduces the dependency on jQuery
// further for the purposes of this test.
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
parseJSONResponse(JSON.parse(xmlhttp.responseText));
}
}
xmlhttp.open("GET", "https://gdata.youtube.com/feeds/users/" + videoId + "/uploads?alt=json", true);
xmlhttp.send();
}
function parseJSONResponse(data) {
var feed = data.feed;
$.each(feed.entry, function(index, entry, list) {
collection.push(entry.id.$t.match('[^/]*$')[0]);
});
playVideo();
}
function playVideo(videoId) {
try {
if (videoId === undefined || videoId === null) {
videoId = collection[0];
}
if (typeof(YT) == 'undefined' || typeof(YT.Player) == 'undefined') {
window.onYouTubeIframeAPIReady = function() {
playVideo(videoId);
};
$.getScript('//www.youtube.com/iframe_api');
} else {
if (playlistEnqueued === true) {
player.playVideoAt(0);
} else {
player = new YT.Player('video', {
events: {
'onReady':function(event) {
try {
player.cuePlaylist(collection);
} catch (e) {
console.error(e);
}
},
'onError':function(error) {
console.error(error);
}
},
videoId: videoId,
width: 425,
height: 356,
playerVars: {
autoplay: 1,
}
});
// Attaching event listener after object creation due to
// http://stackoverflow.com/questions/17078094/youtube-iframe-player-api-onstatechange-not-firing
player.addEventListener('onStateChange', function(state) {
try {
stateChanged(state);
} catch (e) {
console.error(e);
}
});
}
}
} catch (e) {
console.error(e);
}
}
function stateChanged(state) {
// This state will be called on enqueueing a playlist
if (state.data == 5) {
playlistEnqueued = true;
playVideo();
}
}
$(document).on('ready', function() {
var player = $(document).find("#player");
$("a").on('click', function() {
var channel = $(this).attr('data-channel');
createYT(channel);
return false;
});
});
</script>
</head>
<body>
<div class='test'>
<div id='video'>
</div>
<a href='#' data-channel='mit'>MIT</a>
<a href='#' data-channel='tedtalksdirector'>TED</a>
<a href='#' data-channel='minutephysics'>Minute Physics</a>
</div>
</body>
</html>
When using flash, and on waiting for the video connection to timeout and try again the following is seen in the network tab. As you can see it's 'pending', failed, and then tried again after 7.5 minutes.
Chrome network tab once the video starts playing:
Chrome network tab on video playback
More images when I get past 10 reputation...
I've got this up and running on jsFiddle (http://jsfiddle.net/3Bm2V/5/) and it seems to be working ok. I did have to change the
$(document).on('ready', function () {
to
$(function() {
to get it to work in jsFiddle, so try the link above and see if it works for you now?
hey guys i am using the media phonegap api to play,pause and stop the audio. so far i managed to play,stop and pause, but i do not know how to resume please help me
below is the code i have written till now
var my_media = null;
var mediaTimer = null;
var pausePos = 0;
var counter=0;
var playing=false;
function playAudio(src) {
// Create Media object from src
my_media = new Media(src, onSuccess, onError);
// Play audio
my_media.play();
// get audio duration
var duration = my_media.getDuration();
// set slider data
if( duration > 0 ){
$('#slider').attr( 'max', Math.round(duration) );
$('#slider').slider('refresh');
}
// Update my_media position every second
if (mediaTimer == null) {
mediaTimer = setInterval(function() {
// get my_media position
my_media.getCurrentPosition(
// success callback
function(position) {
if (position > -1) {
setAudioPosition(position);
}
},
// error callback
function(e) {
console.log("Error getting pos=" + e);
setAudioPosition("Error: " + e);
}
);
}, 1000);
}
}
/* pause audio */
function pauseAudio() {
if (my_media) {
my_media.pause();
}
}
function resumeAudio()
{
}
/* stop audio */
function stopAudio() {
if (my_media) {
my_media.stop();
playing = false;
my_media.release();
}
clearInterval(mediaTimer);
mediaTimer = null;
pausePos = 0;
}
// onSuccess Callback
function onSuccess() {
console.log("playAudio():Audio Success");
}
// onError Callback
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
// Set audio position
function setAudioPosition(position) {
pausePos = position;
position = Math.round(position);
$('#slider').val(position);
$('#slider').slider('refresh');
}
function player(id)
{
//alert(id);
playAudio("/sdcard/MuseumCache/"+id+"/"+id+".mp3");
//alert("end");
}
Please help me to write the resume function. they said the media.play() plays and resumes playing audio file
ok I fond the solution: Phonegap's Docs are terrible...badly explained
so their example is sloppy
the point is: you must not reinitialize the media everytime you play otherwise it starts form beginning
var my_media == null;
function playAudio(url) {
if (my_media === null){
// so only is your media handler is empty you initialiaze it otherwise you just play
my_media = new Media(url, function() {
console.log("Audio Success");
}, function(err) {
console.log("Audio Error");
});
}
my_media.play();
}
As per the documentation of PhoneGap media.play starts or resume the audio file.
media.play: Start or resume playing audio file.
you can find the link here
Francesco your solution work only if you have one sound to play, if you have multi sound on the same page each player will get the property of the first media...