How does Media.release() work. Looking at the docs it feels that you have to use it like this:
MediaService.loadMedia('sounds/connection-error.wav').then(function(media){
media.play();
media.release();
});
But I googled enough to know that is wrong. We have to explicitly release the core instances on Android.
But how to do that? If I have 8 views in my app and if I play a sound file on each of those views does that count as 8 core instances being used? And can I go back to say view number 1 and again play the sound associated with that view? If so, would that count as a 9th instances ?
Straight away calling media.release() just like above does not play any sound at all.
Most common way to play sounds using Cordova Media plugin is following:
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);
}
}
Related
I have created a sound app for Android using Cordova. Everything was perfect, at least in the Android Studio's emulator, until I found something strange happening while testing on a real device.
My app contains more than 100 sounds one second each. You click to play sounds till you get 32 clicks that play audios without problems. But starting from thirty-third (33rd) click I get a message error:
code: -19 message: undefined
I must mention that you can reply the previous clicked sounds that still work. But other sounds get the error above.
If I close and reopen the app, sounds that gave error work again until I get to 33rd click and start getting the error message even for sounds that used to work.
Here is the code I use to play my sounds:
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
var my_media = new playAudio();
}
// Audio player
//
var my_media = null;
var mediaTimer = null;
// Play audio
//
my_media = {}; // init the play object
function playAudio(src, id) {
if (!my_media[id]) { // check if media already created
my_media[id] = new Media(src, onSuccess, onError);
}
my_media[id].play();
}
//playAudio('file:///android_asset/www/media/1.mp3');
// 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;
}
Any IDEA?
thanks
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
So, i have made an app with phonegap build, where the goal is to read a xml file that contains info about audio tracks, and includes the path for each audio track.
I proceed to input the data of xml file into html, and before it was working fine. After i imported my project into phonegap build, no more audio plays. The controls work, but the audio doesn't play.
Here is the code:
<script>
document.addEventListener('play', function(e){
var audios = document.getElementsByTagName('audio');
for(var i = 0, len = audios.length; i < len;i++){
if(audios[i] != e.target){
audios[i].pause();
}
}
}, true);
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","teste.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
document.write("<table><tr><th>Track</th><th>Description</th<th>URL</th></tr>");
var x=xmlDoc.getElementsByTagName("CD");
for (i=0;i<x.length;i++){
document.write("<tr><td>");
document.write(x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("DESCRIPTION")[0].childNodes[0].nodeValue);
document.write("</td><td>");
var audio = x[i].getElementsByTagName("URL")[0].childNodes[0].nodeValue;
document.write('<audio controls><source src="'+audio +'" type="audio/mpeg"></audio>');
document.write("</td></tr>");
}
document.write("</table>");
</script>
The XML file is simply structured like this:
<CD>
<TITLE>Track one</TITLE>
<DESCRIPTION>Bob Dylan</DESCRIPTION>
<URL>files/test.mp3</URL>
</CD>
I have read some similar questions and find that most mistakes are in the PATH of the audio file. What should i do for the audio to play?
Thanks
EDIT: I have updated my code:
var path = '/android_asset/www/';
var audio = x[i].getElementsByTagName("URL")[0].childNodes[0].nodeValue;
var audioPath = path+audio;
alert(audioPath);
document.write('PLAY<br/>');
document.write('PAUSE<br/>');
document.write('STOP');
document.write('<p id="audio_position"></p>');
The alert(audioPath) returns the correct path and it works when I use this function:
function onDeviceReady() {
playAudio('/android_asset/www/files/test1.mp3');
}
The audioPath is the same as the path above.
But the app doesn't play the sound when i press Play...
Any ideas?
playAudio function:
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);
}
}
FOUND my problem! It was the 'onclick'. I now import jQuery and built the following code:
$(".btPlay").on("click",function (e) {
// body...
console.log("Play");
playAudio(audioPath);
});
It now works!
Try to install the cordova Media plugin org.apache.cordova.media (http://docs.phonegap.com/en/edge/cordova_media_media.md.html)
And then, try this :
//src is your path to your file
var my_media = new Media(src, function(){
alert("Success");
}, function(){
alert("Fail");
});
my_media.play();
Try it with all the paths yuo already tried, but this plugin works for me with online files.
EDIT: You may need to add '/android_asset/www/' in front of your src
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();
}
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);
}
}