I'm building an app in Ionic that needs to be able to play 2 audio files at the same time.
At first I tried to use the HTML5 Audio capabilities which allowed me to do that. However: on the web it played two sounds concurrently as desired but when running on my Android phone only 1 audio file gets played.
I looked further and found ngCordova's $cordovaMedia.
So I went ahead and used the info on ngCordova's website: http://ngcordova.com/docs/plugins/media/
(and I included the js files)
Resulting in the following code:
angular.module('starter.controllers', ['ngCordova'])
.controller('HomeCtrl', function($scope, $cordovaMedia, $ionicLoading) {
$scope.play = function() {
var media = $cordovaMedia.newMedia('http://www.tonycuffe.com/mp3/tail%20toddle.mp3');
media.play();
var media2 = $cordovaMedia.newMedia('http://www.tonycuffe.com/mp3/saewill.mp3');
media2.play();
console.log(media);
console.log(media2);
}
});
Both objects play fine seperate, but when played together only media2 is heard.
Anyone knows why this is and if I can fix it? I'm surely open to alternatives as well.
Related
Its possible there's no solution to this but I thought I'd inquire anyway. Sometimes a video is really quiet and if I turn the volume of my computer up accordingly then other sounds I have become way too loud as a result. It would be nice to be able to boost the volume above maximum.
I did a search on google which literally turned up nothing at all, not even results related to videojs at all in fact. Some videos my Mac is almost at max volume to hear the video's speech well so it would not be feasible to start with everything at a lower volume and adjust accordingly.
I tried with:
var video = document.getElementById("Video1");
video.volume = 1.0;
And setting it to anything above 1.0 but the video then fails to open at all:
var video = document.getElementById("Video1");
video.volume = 1.4; /// 2.0 etc
Based on: http://cwestblog.com/2017/08/17/html5-getting-more-volume-from-the-web-audio-api/
You can adjust the gain by using the Web Audio API:
function amplifyMedia(mediaElem, multiplier) {
var context = new(window.AudioContext || window.webkitAudioContext),
result = {
context: context,
source: context.createMediaElementSource(mediaElem),
gain: context.createGain(),
media: mediaElem,
amplify: function(multiplier) {
result.gain.gain.value = multiplier;
},
getAmpLevel: function() {
return result.gain.gain.value;
}
};
result.source.connect(result.gain);
result.gain.connect(context.destination);
result.amplify(multiplier);
return result;
}
amplifyMedia(document.getElementById('myVideo'), 1.4);
The multiplier you pass to the function is at same level as the video volume, 1 being the 100% volume, but in this case you can pass a higher number.
Can't post any working demo or JSFiddle because Web Audio API requires a source from the same origin (or CORS compatible). You can see the error in the console: https://jsfiddle.net/yuriy636/41vrx1z7/1/
MediaElementAudioSource outputs zeroes due to CORS access restrictions
But I have tested locally and it works as intended.
If you have access to the source files, rather than trying to boost on the fly using Javascript (for that the Web Audio API answer from #yuriy636 is the best solution) then you can process the video locally using something like ffmpeg.
ffmpeg -i input.mp4 -filter:a "volume=1.5" output.mp4
This will apply a filter to the input.mp4 file that just adjusts the volume to 1.5x the input and creates a new file called output.mp4.
You can also set a decibel level:
ffmpeg -i input.mp4 -filter:a "volume=10dB" output.mp4
or review the instructions to normalize audio etc.
A simple usage of the Web Audio API:
var UnprefixedAudioContext = window.AudioContext || window.webkitAudioContext;
var context;
var volumeNode;
var soundBuffer;
context = new UnprefixedAudioContext();
volumeNode = context.createGain();
volumeNode.connect(context.destination);
volumeNode.gain.value = 1;
context.decodeAudioData(base64ToArrayBuffer(getTapWarm()), function (decodedAudioData) {
soundBuffer = decodedAudioData;
});
function play(buffer) {
var source = context.createBufferSource();
source.buffer = buffer;
source.connect(volumeNode);
(source.start || source.noteOn).call(source, 0);
};
function playClick() {
play(soundBuffer);
}
inside a UIWebView works fine (plays the sound); but when you switch to the Music app and play a song, and then come back to the app with the UIWebView the song stops playing.
The same code inside Safari doesn't have this problem.
Is there a workaround to avoid this behavior?
Here's the full fiddle:
http://jsfiddle.net/gabrielmaldi/4Lvdyhpx/
Are you on iOS? This sounds like an audio session category issue to me. iOS apps define how their audio interacts with audio. From Apple's documentation:
Each audio session category specifies a particular pattern of “yes”
and “no” for each of the following behaviors, as detailed in Table
B-1:
Interrupts non-mixable apps audio: If yes, non-mixable apps will be
interrupted when your app activates its audio session.
Silenced by the Silent switch: If yes, your audio is silenced when the
user moves the Silent switch to silent. (On iPhone, this switch is
called the Ring/Silent switch.)
Supports audio input: If yes, app audio input (recording), is allowed.
Supports audio output: If yes, app audio output (playback), is
allowed.
Looks like the default category silences audio from other apps:
AVAudioSessionCategorySoloAmbient—(Default) Playback only. Silences
audio when the user switches the Ring/Silent switch to the “silent”
position and when the screen locks. This category differs from the
AVAudioSessionCategoryAmbient category only in that it interrupts
other audio.
The key here is in the last sentence: "it interrupts other audio".
There are a number of other categories you can use depending on whether or not you want your audio silenced when the screen is locked, etc. AVAudioSessionCategoryAmbient does not silence audio.
Give this a try in the objective-c portion of your app:
NSError *setCategoryError = nil;
BOOL success = [[AVAudioSession sharedInstance]
setCategory: AVAudioSessionCategoryAmbient
error: &setCategoryError];
if (!success) { /* handle the error in setCategoryError */ }
We have a set of HTML blocks -- say around 50 of them -- which are iteratively parsed and have Audio objects dynamically added:
var SomeAudioWrapper = function(name) {
this.internal_player = new Audio();
this.internal_player.src = this.determineSrcFromName(name);
// ultimately an MP3
this.play = function() {
if (someOtherConditionsAreMet()) {
this.internal_player.play();
}
}
}
Suppose we generate about 40 to 80 of these on page load, but always the same set for a particular configuration. In all browsers tested, this basic strategy appears to work. The audio load and play successfully.
In IE's 9 and 10, a transient bug surfaces. On occasion, calling .play() on the inner Audio object fails. Upon inspection, the inner Audio object has a .error.code of 4 (MEDIA_ERR_SRC_NOT_SUPPORTED). The file's .duration shows NaN.
However, this only happens occasionally, and to some random subset of the audio files. E.g., usually file_abc.mp3 plays, but sometimes it generates the error. The network monitor shows a successful download in either case. And attempting to reload the file via the console also fails -- and no requests appears in IE's network monitor:
var a = new Audio();
a.src = "the_broken_file.mp3";
a.play(); // fails
a.error.code; // 4
Even appending a query value fails to refetch the audio or trigger any network requests:
var a = new Audio();
a.src = "the_broken_file.mp3?v=12345";
a.play(); // fails
a.error.code; // 4
However, attempting the load the broken audio file in a new tab using the same code works: the "unsupported src" plays perfectly.
Are there any resource limits we could be hitting? (Maybe the "unsupported" audio finishes downloading late?) Are there any known bugs? Workarounds?
I think we can pretty easily detect when a file fails. For other compatibility reasons we run a loop to check audio progress and completion stats to prevent progression through the app (an assessment) until the audio is complete. We could easily look for .error values -- but if we find one, what do we do about it!?
Addendum: I just found a related question (IE 9/10/11 sound file limit) that suggests there's an undocumented limit of 41 -- not sure whether that's a limit of "41 requests for audio files", "41 in-memory audio objects", or what. I have yet to find any M$ documentation on the matter -- or known solutions.
Have you seen these pages on the audio file limits within IE? These are specific to Sound.js, but the information may be applicable to your issue:
https://github.com/CreateJS/SoundJS/issues/40 ...
Possible solution as mentioned in the last comment: "control the maximum number of audio tags depending on the platform and reuse these instead of recreating them"
Additional Info: http://community.createjs.com/kb/faq/soundjs-faq (see the section entitled “I load a lot of sounds, why am running into errors in Internet Explorer?”)
I have not experienced this problem in Edge or IE11. But, I wrote a javascript file to run some tests by looping through 200 audio files and seeing what happens. What I found is that the problem for IE9 and IE10 is consistent between ALL tabs. So, you are not even guaranteed to be able to load 41 files if other tabs have audio opened.
The app that I am working on has a custom sound manager. Our solution is to disable preloading audio for IE9 and IE10 (just load on demand) and then when the onended or onpause callback gets triggered, to run:
this.src = '';
This will free up the number of audio that are contained in IE. Although I should warn that it may make a request to the current page the user is on. When the play method in the sound manager is called again, set the src and play it.
I haven't tested this code, but I wrote something similar that works. What I think you could do for your implementation, is resolve the issue by using a solution like this:
var isIE = window.navigator.userAgent.match(/MSIE (9|10)/);
var SomeAudioWrapper = function(name) {
var src = this.determineSrcFromName(name);
this.internal_player = new Audio();
// If the browser is IE9 or IE10, remove the src when the
// audio is paused or done playing. Otherwise, set the src
// at the start.
if (isIE) {
this.internal_player.onended = function() {
this.src = '';
};
this.internal_player.onpause = this.internal_player.onended;
} else {
this.internal_player.src = src;
}
this.play = function() {
if (someOtherConditionsAreMet()) {
// If the browser is IE, set the src before playing.
if (isIE) {
this.internal_player.src = src;
}
this.internal_player.play();
}
}
}
I am using Monaca.mobi to build a hybrid app. When I build the app for IOS everything is fine; however, when I build it for an android device (Nexus 7) audio does come through. In the Monaca debugger; however, the audio works fine. Is there something about android devices that I am not aware about, maybe some permissions of the app?
Sound is played through an angularJS function called on certain button clicks. I know that this code is correct, just thought I might share it:
function DontAsk($scope){
$scope.play = function(){
var audio = new Audio();
audio.src = 'sounds/DontEventAsk.mp3';
audio.play();
}}
Thanks for any insight.
your above code is only working with iOS. For Android, the path to your local audio file is not recognized. The following code will work for both OSes. I've already tested with the built app too.
$scope.play= function(){
var os = navigator.platform;
if (os=='iPhone'){
var url = "sounds/DontEventAsk.mp3";
}
else{
var url = getPhoneGapPath() + "sounds/DontEventAsk.mp3";
}
var my_media = new Media(url,
// success callback
function() {
console.log("playAudio():Audio Success");
},
// error callback
function(err) {
console.log("playAudio():Audio Error: "+JSON.stringify(err));
});
// Play audio
my_media.play();
}
The big question here is what browser does the Monaca.mobi app use internally? The default Android browser is notorious for not supporting newer codecs like Audio that require HTML5. You might be better off setting some kind of flag that the app can watch and then use the app to play the sound instead of relying on the browser.
I'm not sure what this could be... it's kind of hard to debug.
Basically when using jPlayer, each track ends a few seconds too early (mp3 format only).
I'm using S3/Cloudfront CDN for distribution, but I don't think that has anything to do with it (unless there is some weird header issue that could create symptoms like this). Ive tried it on about 5 different mp3's so far, all to the same effect.
Also, the .progress-bar doesn't get to 100% either, it ends at about 95% and then goes to the next playlist item.
var fnmApp = (function() {
var player = function() {
var options = {
swfPath : '<%= asset_path 'Jplayer.swf' %>'
, supplied : 'mp3'
, solution : 'html,flash'
, wmode : 'transparent'
, smoothPlayBar : false
};
var fnmPlaylist = new jPlayerPlaylist({
jPlayer: '#fnmp'
, cssSelectorAncestor: '#fnmp-container'
}, mixtapePlaylist, options);
$('.fnmp-container .jp-gui a').click(function(e) {
e.preventDefault();
});
};
return {
player: player
};
})();
Streaming MP3 files over HTTP is a bit problematic because it isn't typically possible to know how big that file is (in time or samples) until it is completely downloaded, and frames counted. Most players get around this by estimating time and then either updating that estimate as playback continues or simply rolling past the end of the file, should there still be data to play even after the original estimated length.
It sounds like what is happening is that the original estimated length is being used for the playback length. This is likely a bug with whatever is playing back audio, or the codec it is using. With jPlayer, you could be using either Flash or the browser via HTML5 for playback. Since forcing Flash over HTML5 is working in your case, I believe this is a bug in the build of Chrome that you are using. Unfortunately, there is no direct way to fix this problem, since it is out of your control. You can only work around it.