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!
Related
i am building an app with ionic, i want to run a function whenever a video starts to play,like hide a button and etc. here's my code
let video = <HTMLVideoElement> document.getElementById(i)
if(video.paused) {
video.play()
video.oncanplay=()=>console.log('Starts playing');
}
The code is not working, please how can i run a function whenever any video on that page starts playing
var vid = document.getElementById("myVideo");
vid.onplay = function() {
alert("The video has started to play");
};
From here: https://www.w3schools.com/tags/av_event_play.asp
Try this, play returns a promise.
const video = document.getElementById("myVideo");
async function playVideo() {
try {
await video.play();
// video is playing, do your stuff here
} catch(err) {
// video is not playing
}
}
if(video.paused) {
playVideo()
}
For more info: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play
The javascript error is: Unhandled Promise Rejection: NotAllowedError: The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.
My setup works across other browsers, desktop and mobile.
The way it works is:
have a flag first_audio_played = false;
add a touch event listener that plays some audio, and sets first_audio_played = true; (then removes the touch listener)
all subsequent audio checks if(first_audio_played) some_other_audio.play();
this way, only the first audio played requires direct user input. after that, all audio is free to be triggered by in-game events, timing, etc...
this appears to be the "rule" for audio across most browsers. is the iOS "rule" that every audio needs to be triggered by user input? or is there some other step I'm missing?
For my javascript game, sounds stopped working on iOS recently. They all have readyState=4, but only the sound I played on tap works, the others won't play. Maybe you could play all the sounds on the first tap. But the solution I found that works for now for me is to load all the sounds from ajax arraybuffers and use decodeAudioData(). Then once you've played 1 sound from user tap (on not the body), they all play whenever.
Here is my working code where the second way of doing it is on bottom. When I tap to play sound2, sound1 starts working also.
<html>
<body>
<div id=all style='font-size:160%;background:#DDD' onclick="log('clicked');playSound(myAudio)">
Sound1 should be playing every couple seconds.
<br />Tap here to play sound1.
</div>
<div id=debug style='font-size:120%;' onclick="playSound(myAudio2)">
Tap here to play the sound2.
</div>
<script>
var url = "http://curtastic.com/drum.wav"
var url2 = "http://curtastic.com/gold.wav"
var myAudio, myAudio2
if(0)
{
var playSound = function(sound)
{
log("playSound() readyState="+sound.readyState)
log("gold readyState="+myAudio2.readyState)
sound.play()
}
var loadSound = function(url, callback)
{
var audio = new Audio(url)
audio.addEventListener('canplaythrough', function()
{
log('canplaythrough');
if(callback)
callback()
}, false)
audio.load()
if(audio.readyState > 3)
{
log('audio.readyState > 3');
if(callback)
callback()
}
return audio
}
myAudio = loadSound(url, startInterval)
myAudio2 = loadSound(url2)
}
else
{
var playSound = function(sound)
{
log("playSound()")
var source = audioContext.createBufferSource()
if(source)
{
source.buffer = sound
if(!source.start)
source.start = source.noteOn
if(source.start)
{
var gain = audioContext.createGain()
source.connect(gain)
gain.connect(audioContext.destination)
source.start()
}
}
}
var loadSound = function(url, callback)
{
log("start loading sound "+url)
var ajax = new XMLHttpRequest()
ajax.open("GET", url, true)
ajax.responseType = "arraybuffer"
ajax.onload = function()
{
audioContext.decodeAudioData(
ajax.response,
function(buffer)
{
log("loaded sound "+url)
log(buffer)
callback(buffer)
},
function(error)
{
log(error)
}
)
}
ajax.send()
}
var AudioContext = window.AudioContext || window.webkitAudioContext
var audioContext = new AudioContext()
loadSound(url, function(r) {myAudio = r; startInterval()})
loadSound(url2, function(r) {myAudio2 = r})
}
function startInterval()
{
log("startInterval()")
setInterval(function()
{
playSound(myAudio)
}, 2000)
}
function log(m)
{
console.log(m)
debug.innerHTML += m+"<br />"
}
</script>
</body>
</html>
You can use either [WKWebViewConfiguration setMediaTypesRequiringUserActionForPlayback:WKAudiovisualMediaTypeNone] or [UIWebView setMediaPlaybackRequiresUserAction:NO] depending on your WebView class (or Swift equivalent).
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 :(
The following script is playing a soundfile when i click on a img (onclick). How do i pause it by clicking on the same img? I´ve tried audio.pause(), but it won´t work.
function play(){
var audio = document.getElementById("myaudio");
audio.style.display="block";
audio.play();
}
<img src="Bilder/play2.png">
You should rename your function to audioHandler() for example which will handle whether to play or pause your audio.
Create a boolean to remember if your audio was playing or was on pause.
//initial status: audio is not playing
var status = false;
var audio = document.getElementById("myaudio");
function audioHandler(){
if(status == false || audio.paused){
audio.play();
status = true;
}else{
audio.pause();
status = false;
}
}
Check the media.paused property of your HTMLMediaElement
function play_pause(media) {
if (media.paused) {
media.play();
else {
media.pause();
}
}
Use this in the handler on the element you want to control the action
var elm = document.getElementById('play_button'),
audio = document.getElementById('myaudio');
elm.addEventListener('click', function (e) {
play_pause(audio);
});
I am workign with PhoneGap 3.0.0 and my confic.xml file does have the needed plugins. I can start saying that my sound do start when i run my code, and that everything else works. Just 1 thing dont want to work.
I am using Jquery Mobile.
I cant stop the audio.
I am calling a function called "stopAudio()" that read a global variable "my_audio" and fire of the "stop()" function.
Here is my code.
Index.html
Stop Audio
AudioHandler.js
document.addEventListener("deviceready", onDeviceReady, false);
var my_media = null;
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);
}
}
function stopAudio() {
my_media.stop();
}
controller.js
$("#stopaudio").click(function() {
stopAudio();
});
Example usage:
playAudio("/android_assets/www/mysound.mp3");
So i have these 3 files. What i posted is a small amount of the content, but the other content in those files have nothing to do with the audio. I did also try and comment everything out and so forth.
So, basicly the "controller.js" is the file where the click are detected, and from there the function "stopAudio()" are called that comes from AudioHandler.js.
My audio do start on startup of the phone.
I cant stop the audio.
Im running out of ideas, any help would be welcome :-)
Thanks :)
You've declared my_media as a local variable here:
try {
var my_media = new Media(url,
You want it to be global, so remove the var:
function playAudio(url) {
try {
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);
}
}