Playing Music on Roblox locally - audio

I'm a tad stuck with local music playing on my Roblox game.
I've got a setup on my game where a script inserts five sound files into a player's GUI. When a sever is made these sounds do make it to the players gui.
To play the sounds there are parts setup that check for collisions with players and when they detect a player they will start one of the five sounds in the player's GUI.
This is what the code in one of the parts looks like:
script.Parent.Touched:connect(function(hit)
if hit.Parent:FindFirstChild('Humanoid') then
if game.Players[hit.Parent.Name].PlayerGui.Sound2.TimePosition < 1 then
game.Players[hit.Parent.Name].PlayerGui.Sound2.Volume = 1
game.Players[hit.Parent.Name].PlayerGui.Sound2:Play()
game.Players[hit.Parent.Name].PlayerGui.Sound1:Stop()
game.Players[hit.Parent.Name].PlayerGui.Sound4:Stop()
game.Players[hit.Parent.Name].PlayerGui.Sound3:Stop()
game.Players[hit.Parent.Name].PlayerGui.Sound5:Stop()
end
end
end)
This script does detect players just fine as I have tested it. The system does work in the Roblox Studio testing area however when a server is launched with it none of the sounds are played.
The server does in fact set the sounds to playing and they appear as playing on the client side from the server side however the client side does not see them as playing and they do not play.
I do have filtering enabled turned on but this shouldn't effect it...

I believe it is something quite simple. I think it is a function of the SoundService. Correct me if this doesnt work, but i believe this is it
soundobj = game.Players[hit.Parent.Name].PlayerGui.Sound2
game:GetService('SoundService'):PlayLocalSound(soundobj)
see https://wiki.roblox.com/index.php?title=API:Class/SoundService/PlayLocalSound for more info

A way to do that is parenting the sounds to PlayerGui (I think you needed a ScreenGui) and then :Play() them.

Filtering enabled is the reason this doesn't work.
To solve this you can use a RemoteEvent located in the ReplicatedStorage of your game.
The sounds must be placed in the StarterGUI and there should be a localscript with this code:
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local event = ReplicatedStorage:WaitForChild("REMOTE EVENT NAME")
script.Parent.Sound2.Playing = true
local function onNewPlayerFired(sound)
script.Parent.Sound1.Playing = false
script.Parent.Sound2.Playing = false
script.Parent.Sound3.Playing = false
script.Parent.Sound4.Playing = false
script.Parent.Sound5.Playing = false
script.Parent[sound].Playing = true
end
event.OnClientEvent:Connect(onNewPlayerFired)
and in the part for each sound trigger part there should be this code:
local debounce = false
script.Parent.Touched:connect(function(hit)
if debounce == true then return end
debounce = true
if hit.Parent:FindFirstChild('Humanoid') then
local plr = game.Players:FindFirstChild(hit.Parent.Name)
game.ReplicatedStorage.REMOTE EVENT NAME:FireClient(plr,"SOUND NAME")
end
wait(2)
debounce = false
end)

I recently ran into this issue while making a music player. It ended up being the silliest thing and had everything to do with FE. My player worked in Test Studio, but gave me a whole laundry list of error codes that I was able to fix simply by changing the script to a local script. Literally all the same code worked as it did in studio but client side. It took me a entire day of head scratching and wiki searching to figure out my mistake. FE was initially a nightmare for me, but I have come to love the security it provides my games. :)

Related

get_node crashing game when node is deleted

First of all, I'm new to programming in general so I'm kind of assuming there's a simple answer to this question, I just couldn't seem to find it anywhere.
I'm making a simple platformer game with enemies that move toward the player. I used this code in the enemy's script underneath the physics process to get the player position:
player_position = get_parent().get_node("Player").get_position
However, upon the player being queue_freed when health reaches 0, the game crashes immediately and I get a null error due to there being no Player node. How can I work around this?
You could just set $Player.visibility to false instead of freeing, or you could check if the player exists first using get_parent().has_node("Player")
When you destroy the player, the physics process function is still trying to get the player node, even though it doesn't exist. So, as Lucas said, you could replace:
player_position = get_parent().get_node("Player").get_position
with something like...
if get_parent().has_node("Player"):
player_position = get_parent().get_node("Player").get_position
(Before setting player_position, it will check if the player node even exists)
I think you could use weakref (documentation here).
If you declare a weak reference:
var player_ref: WeakRef = null
and store that reference:
func store_player_node():
var player_ref = weakref(get_parent().get_node("Player"))
Then you can access that reference later:
if player_ref.get_ref():
player_position = player_ref.get_ref().get_position
Weakref has advantage over using get_parent().get_node("Player"). Let's imagine the following scenario:
Player dies and its node is removed from the parent node's children.
New node is created with name Player and added to the scene tree at the same place as the dead Player.
get_parent().get_node("Player") will return a node and the code will not crash. However, it will be a new Player node, not the old one, and I think this is usually undesired.
I hope this helps!

AUDIO_OUTPUT_FLAG_FAST denied by client OR E/MediaPlayer: Error (1,-19)

I am creating a game using Libgdx. I have a lot of small sounds files in the MP3-format and since it is so many I do not preload them. I only load the sound I want to play when it is to be used, like this:
actorSound = Gdx.audio.newSound(Gdx.files.internal(sound));
The code above works great, but the rest of my sounds do not unfortunately. The actor above has its own class and plays a different sound every time it is touched.
When I try to play sounds in my Gamescreen I get the following error:
AUDIO_OUTPUT_FLAG_FAST denied by client
All the audiofiles have the same properties and have been recorded using the same microphone & Audacity. The files are all 44100Hz and only a few kb in size each.
I wonder why the sounds the Actor plays work and the other sounds do not?
I decided to try to change the non-working sounds to music instead and now they play fine - for a little while that is. I can play a full game, return to the menu and start a new game again. The second time I start a game I only get 3 sounds from the Gamescreen and then it is silent except for the sounds from the actor. The error that appears looks like this:
E/MediaPlayer: Error (1,-19)
I load the Music just the same way as the Sound:
gameSound = Gdx.audio.newMusic(Gdx.files.internal(soundeffect));
I have looked into the two errors by reading posts like these:
AUDIO_OUTPUT_FLAG_FAST denied by client
Mediaplayer error (-19,0) after repeated plays
But I'm not sure what to do or change to solve my problem. I would prefer Sound if that is possible, but Music is an acceptable workaround...
When it comes to Music it is probably as suggested in the URL, that I do not release the media players. I am not sure how to do that?
When I leave the GameScreen for another screen, like the MenuScreen or RewardScreen, I dispose Music first. The other screens use Music as well and the sounds are loaded when needed. When I change back to the GameScreen I dispose again and then start a new game...
Any ideas or suggestions? Any help is greatly appreciated.
I added AssetManager as suggested, and I now have a loding screen that loads all the sounds. I load them as sounds and not music, which is how I prefer it.
The sounds work well in the actual game but once I get to the reward screen, only the first sound plays and after that the app crashes with the following error:
06-02 07:47:09.774 6208-6282E/AndroidRuntime: FATAL EXCEPTION: GLThread 2935
Process: PID: 6208
java.lang.NullPointerException: Attempt to read from field 'com.badlogic.gdx.assets.AssetManager
Assets.Assets.manager' on a null object reference
at DelayedSounds(RewardsScreen.java:538)
at RewardsScreen.Update(RewardsScreen.java:567)
at Screens.RewardsScreen.render(RewardsScreen.java:577)
at Game.render(Game.java:46)
at com.badlogic.gdx.backends.android.AndroidGraphics.onDrawFrame(AndroidGraphics.java:459)
at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1562)
at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1262)
06-02 07:47:13.823 6208-6208 E/AndroidGraphics: waiting for pause
synchronization took too long; assuming deadlock and killing
The DelayedSounds method looks like this:
public void DelayedSounds(){
timer = timer + Gdx.graphics.getDeltaTime();
if(playitem == true && timer > 2){
itemsound = "vinster/" + item + ".mp3";
assets.manager.get(itemsound, Sound.class).play(volume);
//sound = Gdx.audio.newMusic(Gdx.files.internal(itemsound));
//sound.setVolume(volume);
//sound.play();
playitem = false;
}
if(playkeep == true && time > 3){
assets.manager.get("dialog/VINSTEN.mp3", Sound.class).play(volume);
//sound = Gdx.audio.newMusic(Gdx.files.internal("prizes/prize.mp3"));
//sound.setVolume(volume);
//sound.play();
playkeep = false;
}
}
As can be seen I use AssetManager now, and have commented out my old code for testing purposes. I define AssetManager in my main class and then pass it around to all other classes that uses sounds.
The RewardsScreen will only play the first sound and then it crashes on a NULL object reference as it seems.
If I change my code back to using Music in the RewardsScreen it works fine (see the code that is commmented out)
The sound I try to play is exactly the same in both cases. Assets class that handles the loading of all my assets has the sounds included and since I still get a NULL object I assume one or more items fails to load?
I search the logs and find this where it loads the sounds:
06-02 08:05:09.360 9844-9888/E/WVMExtractor: Failed to open libwvm.so: dlopen failed: library "libwvm.so" not found
06-02 08:05:09.395 9844-9888/ E/NdkMediaExtractor: sf error code: -1010
06-02 08:05:09.395 9844-9888/ E/SoundPool: Unable to load sample
Maybe this is related to my problem?
I load all the sounds in the same manner and most definitely seem to work, the loading is the regular:
manager.load("prizes/cash.mp3", Sound.class);
I still find the AUDIO_OUTPUT_FLAG_FAST denied by client in my logs but now the sounds are playing instead of being rejected.
Any more ideas about how to solve this?
Your link having enough information for your bug.
It's not good way to create Resource instance each time in Game, Create once and user All over your game, if possible use AssetManager.
Like create Music instance in onCreate() method of your game.
gameSound = Gdx.audio.newMusic(Gdx.files.internal(soundeffect));
Music having play(), resume() and many other helpful methods.
You can also take a look of this, it may be helpful.

Adobe AIR for iPhone app: can't play audio properly

I just developed an App by using adobe air. It contains some animations with background music in mp3 format. The problem is that the music is very jerky when the animation is playing...
FYI, this is the way how I play audio in flash:new Sound(new URLRequest("m3.mp3")).play()
Have I done anything wrong?
BTW, the funny thing is that if you hit the HOME button, and then come back to the app again, everything plays beautifully...
Without knowing more about the code, it seems like the sound is not fully loaded. The file plays as far as it can, then waits for more data to show up, then continues . . . very jerky. You may have to wait for the sound to load completely before playing it:
var s = new air.Sound();
s.addEventListener(air.Event.COMPLETE, onSoundLoaded);
var req = new air.URLRequest("bigSound.mp3");
s.load(req);
function onSoundLoaded(event)
{
var localSound = event.target;
localSound.play();
}
This code is from Adobe's Sound docs.

AudioQueueStart fail -12985

I made a streaming music player and it works fine in the foreground.
But in the background iOS4, it doesn't play the next song automatically. ( remote control works )
The reason is AudioQueueStart return -12985.
I already check the audio session. it just fine. I use AudioQueueStart when it start to play the music.
How can you remove AudioQueueStart?
- (void)play
{
[self setupAudioQueueBuffers]; // calcluate the size to use for each audio queue buffer, and calculate the // number of packets to read into each buffer
OSStatus status = AudioQueueStart(self.queueObject, NULL);
}
I read the answer in the web about the AudioQueueStart fail subject.
One thing to check is that the AudioSession is active first.
In my case, I had previously set the session to inactive between song changes before starting a new song:AudioSessionSetActive(false);
Once I removed this AudioQueueStart works just fine from the background.
In my experience, the -12985 message occurs because another app already has an audio session active when you try to start playback in your app. Options are to 1) instruct the user to close the other app, or 2) set mix mode (see kAudioSessionProperty_OverrideCategoryMixWithOthers).
The disadvantage of mix mode is if you depend on lock screen art or remote controls, they won't work with mix mode set.
I also faced with such problem week ago. I've spent two days to find solution and I found it. May be this link will help (it is official answer): http://developer.apple.com/library/ios/#qa/qa1668/_index.html
Make sure that you activate session from applicationDidEnterBackground task handler. Now my application can play sound in background.
See this.
You probably need to include the following:
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
Towards the bottom there is a reiteration of the how important that line is. As it is not mentioned in any of the three main audio audio guides (AVFoundation, AudioSession, or AudioQueue) it can easily be missed.
I have the same problem.
I registry the AudioSessionInterruptionListener, pause the audio when phone call, resume it after the call end. but get -12985 error code when call AudioQueueStart to resume.
My solution is that I try to call AudioQueueStart after 0.02s.
I don't know the reason.
On iOS7, AudioQueueStart was returning '!int' ('tni!'), though i'm sure no one would be surprised to find that it's not documented in the docs or headers. It was the same issue, though, and the same fix (setting the audio session to active in the background task handler) worked for me.

Playing a sound in a Firefox add-on

I would like to create a simple add-on that would play a different MP3 recording every time the user double clicks a word in a webpage he is visiting and selects a special option from the context menu.
The MP3 files are located on a remote server. Normally I would use JavaScript+Flash to play the MP3 file. In a Firefox add-on, however, I'm unable to load external scripts for some reason (playing the sound works fine if it's the webpage itself that loads the scripts, but of course I need it to work with every website and not just the ones that include the script).
So what's the easiest way to play a remote MP3 file in a Firefox add-on using JavaScript?
This may not entirely solve your question, as I don't BELIEVE it plays MP3s, but I'm not certain.
Firefox has nsISound, which I KNOW can play remote WAV files, as I've tested and proved it.
You may want to test it for yourself and see if it leads you a little closer!
var ios = Components.classes['#mozilla.org/network/io-service;1'].getService(Components.interfaces.nsIIOService);
var sound = ios.newURI("http://www.yoursite.com/snds/haha.wav", null, null);
var player = Components.classes["#mozilla.org/sound;1"].createInstance(Components.interfaces.nsISound);
player.play(sound);
Good luck, I hope this at least gets you close!
I know this is an old question, but if someone needs a way to do it:
let player = document.createElement("audio");
player.src = browser.runtime.getURL(SOUND_URL);
player.play();
There is one caveat: the user must have allowed autoplay on the website.
Here is a working code....
var sound = Components.classes["#mozilla.org/sound;1"].createInstance(Components.interfaces.nsISound);
var soundUri = Components.classes['#mozilla.org/network/standard-url;1'].createInstance(Components.interfaces.nsIURI);
soundUri.spec = "chrome://secchat/content/RING.WAV";
sound.play(soundUri);
var window = require('sdk/window/utils').getMostRecentBrowserWindow();
var audio = ('http://example.com/audio.mp3');
audio.play();

Resources