I try to use haxe (openfl) for blackberry development.
And I test PlayingSound sample - it works.
But when I try to load sound from url - doesn't work.
Here is my code:
public function PlaySong(url:String):Void{
var _url:URLRequest = new URLRequest(url);
if (_soundChannel != null) _soundChannel.stop();
_song = new Sound();
_song.load(_url); //<--Do not work
//_song = Assets.getSound("assets/stars.mp3"); <--work
_soundChannel =_song.play(0);
}
In the flash target this code is playing my sound from the url, but when I deploy app to my device - it have no sound. On the device, sound is playing correctly only if I load it from the asset folder.
Also, I see that soundChannel position is always 0 (on device);
I try firstly to load the sound with loader, and then play it, when the loading is complete, but it's not help me too.
Help me, please.
PS Sorry for my English.
Have you tried loading it using this:
var loader:URLLoader = URLLoader(new URLRequest("url"));
loader.data = DataFormat.BINARY;
then try
loader.addEventListener(Event.COMPLETE, onComplete);
function onComplete(e:Event):Void
{
sound.loadCompressedDataFromByteArray(e.data.content)
}
Try to load bytes first, then create sound from that.
Anyway, if your code works on other mobile devices(maybe emulators), then create new issue here:
https://github.com/openfl/openfl
Related
I use Video Player which attached 3D game object. This game object contain "Mesh Renderer" component too. Video Player Renderer-> this game object.
I try many method, but always crash game.
I try use in Update: Videoplayer().isplaying if false, then I load from Resources next video and play, but not working. (Unity Editor working fine, but in iPhone sometimes crash game.)
Then I try other method..
But sometimes crash too..
Okey, I think maybe loading and start playing too fast, maybe this cause the crash.
Then I try use Ienumerator waitforsecond every step, for debugging I set it 5 seconds.
I try first set video player.clip = null, maybe this is the problem.. But not..
Now the code:
void Start()
{
index = 0;
videoPlayer = gameObject.GetComponent<VideoPlayer>();
videoPlayer.loopPointReached += CheckOver;
}
IEnumerator Waitforseconds()
{
Debug.Log("Waitforseconds start");
videoPlayer.clip = null;
Debug.Log("Videoplayer clip null);
yield return new WaitForSeconds(5);
videoPlayer.clip = theVideo;
Debug.Log("Videoplayer set the video");
yield return new WaitForSeconds(5);
Debug.Log("Next play video player");
videoPlayer.Play();
Debug.Log("Play video player");
isPlaying = true;
}
void CheckOver(UnityEngine.Video.VideoPlayer vp)
{
Debug.Log("Checkover");
index += 1;
if (index >= videos.Length)
{
index = 0;
}
theVideo = videos[index];
Debug.Log("Set the video");
StartCoroutine(Waitforseconds());
}
The videos size 5-10 MB and 10-60 seconds.
The result: Unity Editor working good, I build to iOS and sometimes crash the game if I play next video (iPhone 12 Pro Max, supposedly the fastest smartphone chip, so if that doesn't work, there's a big problem..)
Debug:
I get last Debug.log before the game crash:
"Videoplayer clip null"
So I think the game crash here: videoPlayer.clip = theVideo;
But only iOS! Unity editor working good.
Xcode error:
I try find solution in google, but I can't find..
Maybe memory error? should I somehow delete the previous video from memory?
Or how can I solve this problem? Please help me.
Thank you very much!
EDIT: I see the problem is Audio. (Audio Output mode: Audio Source, this component attached to same gameobject. So same game object contain audio source and video player.) If I set Audio Output mode to "none", then game not crash, workin good. So the problem when "PrepareAudioTap". How can I solve this problem?
Solved!
I change Video Player component "Audio Output mode": Audio Source to Direct.
Then not crash game.
But I would like to use Audio Source, because I need 3D Sound. (not important, I'm glad it works, but if you have idea how to work with 3D sound, I would be glad.)
Thanks!
After searching around the net, I couldn't find a method to download a mp3 from a server, save it in the local storage (iPad) and then load and play it other than converting it to byteArray, saving it as .mp3 and then load it and read it back to mp3 to be able to play it in the flash application.
The problem is, although this method works fine, the uncompressed files (in byteArray format) saved in the local storage are too heavy and I suspect that the app is wasting memory.
My question is, is there any form of saving the mp3 directly, without any conversion, like a properly playable mp3? I can't use methods like download() or save() from FileReference.
Lots of thanks!!
SOLUTION!! (WORKING PERFECTLY):
I continued looking for a method to do it around the net, and some forums gave me a clue to do whick I was searching. It was finally pretty simple, but I spent almost 2 weeks to find it out... here is my code:
var queue:LoaderMax = new LoaderMax({name:"mainQueue", onProgress:progressHandler, onComplete:completeHandler, onError:errorHandler});
queue.append( new DataLoader("http://" + **url**, {name:**"example.mp3"**format:"binay"}));
queue.load();
// Complete Event:
private function completeHandler():void {
var file:File = new File(**your location**); // appData
var fr:FileStream = new FileStream();
fr.open(file.resolvePath(nameIn), FileMode.WRITE);
fr.writeObject(LoaderMax.getContent("example.mp3"));
fr.close();
fr = null;
// Now the mp3 is saved in local storage, we load it as Sound object so we can play it.
var loader:MP3Loader;
loader = new MP3Loader(**your location**, {autoPlay:false}) ;
loader.addEventListener(Event.COMPLETE, function():Sound {
loader.content.play(); // This line is the only one not checked, but I am completely sure you can do something like this to play the sound. For example, I introduce the loader.content in a Array of Sound and later I am capable to play any sound I want.
loader.dispose(true); // This is very important to free memory. You should do the same thing with queue when all items are downloaded.
});
loader.load();
}
I expect this help a lot of people!!
I've been running into an issue now for a while where on some ios devices my webaudio system only seems to work with headphones where as other devices (exact same os, model, etc) the audio plays perfectly fine through the speakers or headphones. I've searched for a solution to this but haven't found anything on this exact issue. The only thing I can think of is that maybe it's an audio channel issue or something.
How can I fix this?
#Alastair is correct, the mute toggle switch does mute WebAudio, but it does not mute HTML5 tags. Thanks to his work I managed to find a work around for the web which enables WebAudio to play even when the mute toggle switch is on. I'd post this as a comment on his reply, but I don't have the reputation.
In order to play WebAudio you must also play at least one WebAudio sound source node and one HTML5 tag during a user action. It is fine if these sounds are short bits of silence. I found that this self contained code works without any extra files needed:
EDIT 11/29/19:
Removed vestigial typescript typedefs. Thanks #Joep. I also realized the code below is woefully out of date and janky. Just consider it an example. Editing this post prompted me to create an open source solution for this. You can see a demo of it here: https://spencer-evans.com/share/github/unmute/ and check out the repo here: https://github.com/swevans/unmute
/**
* PLEASE DONT USE THIS AS IT IS, THIS IS JUST EXAMPLE CODE.
* If you want a drop in solution I have a script on git hub
* Demo:
* #see https://spencer-evans.com/share/github/unmute/
* Github Repo:
* #see https://github.com/swevans/unmute
*/
var isWebAudioUnlocked = false;
var isHTMLAudioUnlocked = false;
function unlock() {
if (isWebAudioUnlocked && isHTMLAudioUnlocked) return;
// Unlock WebAudio - create short silent buffer and play it
// This will allow us to play web audio at any time in the app
var buffer = myContext.createBuffer(1, 1, 22050); // 1/10th of a second of silence
var source = myContext.createBufferSource();
source.buffer = buffer;
source.connect(myContext.destination);
source.onended = function()
{
console.log("WebAudio unlocked!");
isWebAudioUnlocked = true;
if (isWebAudioUnlocked && isHTMLAudioUnlocked)
{
console.log("WebAudio unlocked and playable w/ mute toggled on!");
window.removeEventListener("mousedown", unlock);
}
};
source.start();
// Unlock HTML5 Audio - load a data url of short silence and play it
// This will allow us to play web audio when the mute toggle is on
var silenceDataURL = "data:audio/mp3;base64,//MkxAAHiAICWABElBeKPL/RANb2w+yiT1g/gTok//lP/W/l3h8QO/OCdCqCW2Cw//MkxAQHkAIWUAhEmAQXWUOFW2dxPu//9mr60ElY5sseQ+xxesmHKtZr7bsqqX2L//MkxAgFwAYiQAhEAC2hq22d3///9FTV6tA36JdgBJoOGgc+7qvqej5Zu7/7uI9l//MkxBQHAAYi8AhEAO193vt9KGOq+6qcT7hhfN5FTInmwk8RkqKImTM55pRQHQSq//MkxBsGkgoIAABHhTACIJLf99nVI///yuW1uBqWfEu7CgNPWGpUadBmZ////4sL//MkxCMHMAH9iABEmAsKioqKigsLCwtVTEFNRTMuOTkuNVVVVVVVVVVVVVVVVVVV//MkxCkECAUYCAAAAFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV";
var tag = document.createElement("audio");
tag.controls = false;
tag.preload = "auto";
tag.loop = false;
tag.src = silenceDataURL;
tag.onended = function()
{
console.log("HTMLAudio unlocked!");
isHTMLAudioUnlocked = true;
if (isWebAudioUnlocked && isHTMLAudioUnlocked)
{
console.log("WebAudio unlocked and playable w/ mute toggled on!");
window.removeEventListener("mousedown", unlock);
}
};
var p = tag.play();
if (p) p.then(function(){console.log("play success")}, function(reason){console.log("play failed", reason)});
}
window.addEventListener("mousedown", unlock);
This is likely because the iPhone's side switch is on "mute". It's very confusing - HTML5 <audio> tags still play fine when the phone is muted, but WebAudio does not. Why? Who knows. But it's a restriction I currently haven't found a way around.
If the iPhone mute button is down, meaning that the iPhone is muted, what is played through Web Audio Api will be muted.
Unfortunately there is no way to check if that physical button (located on the left edge towards the top of the iPhone) is on or off through Javascript.
This issue is completely independent from the fact that in iOS Safari the audio has to be started by a user action for it to be unmuted. There are some tricks that can be done to overcome that fact, including the one suggested by here Spencer, were you use "any action or a specific action" started by the user to "play" a silent audio file to allow subsequently playing audio files to play unmuted.
had same issue, and finally understood problem.
indeed WebView don't play sound on internal speakers if phone is in mute.
when i dig deeper i found a workaround :)
original post => https://stackoverflow.com/a/37874619/8064246
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
//print("AVAudioSession Category Playback OK")
do {
try AVAudioSession.sharedInstance().setActive(true)
//print("AVAudioSession is Active")
} catch _ as NSError {
//print(error.localizedDescription)
}
} catch _ as NSError {
//print(error.localizedDescription)
}
I can play a video from the local file system, but can't get it to play from an external URL. No error message. Just a blank dark screen. Any ideas?
var movieFile = NSUrl.FromString("http://apps.focusonsound.com/demo/AppleVideos/Xylophone.mp4");
mp = new MPMoviePlayerController(movieFile);
mp.AllowsAirPlay = false;
this.View.AddSubview(mp.View);
mp.SetFullscreen(true, true);
mp.ShouldAutoplay = true;
mp.PrepareToPlay();
mp.Play();
Your code works - but only when I replace your URL with one where a .mp4 file can be downloaded (e.g. using Safari).
Could your URL simply be dead / outdated ?
I am using the following code to play a .CAF file in an iPad application via Monotouch:
public void PlayClick()
{
PlaySound("Media/Click.caf");
}
private void PlaySound(string soundFile)
{
//var mediaFile = NSUrl.FromFilename(soundFile);
//var audioPlayer = new SystemSound(mediaFile);
//audioPlayer.PlaySystemSound();
var audioPlayer = new SystemSound(soundFile);
if (audioPlayer != null)
{
audioPlayer.PlaySystemSound();
}
}
It works find in the simulator - in fact, all variations I've tried (SystemSound, AVAudioPlayer, etc.) appear to work ok in the simulator, but I've not gotten a version to play on a real device yet. The sound files are all marked as Content and I checked the bundle uploaded to the iPad and the files are definitely there in a subfolder named "Media". If I change the code to use SystemSound (via the constructor with Url), I get an InvalidOperationException with the details:
Could not create system sound ID for url file://localhost/private/var/mobile/Applications/AC24496E-12E9-4690-B154-BA1AD1123EDC/Sample.app/Media/Click.caf; error=SystemSoundUnspecified
Anyone know what am I doing wrong? Thanks for any pointers to get me past this issue!
The simulator is case-aware, but the actual device is case-sensitive. This has tripped up many people.