How to end a sound right away? - ios

I'm working on an IOS game, and the background music clip is 7 seconds long, so when the scene changes from one scene to the next, I want it to stop instantly, but it continues and finishes the 7 second loop then stops.
This is the code:
[self runAction:[SKAction repeatActionForever:[SKAction playSoundFileNamed:#"sound 1.m4a" waitForCompletion:YES]]];
if (_dead == YES) {
[self removeAllActions];
}
where _dead is when the player dies, and the new scene is triggered.
How can I get the music to stop that instant, as opposed to finishing its loop?

Instead of using SKAction to play your background sound file, I would suggest using AVFoundation which allows you to simply issue a stop command.
Update
I can't think of any food tutorials that focus primarily on the sound side. Most deal with video and sound. Try google with something like 'AVFoundation tutorial'.
To use AVFoundation you can do this for your purposes...
Add the AVFoundation.framework to your project.
In your .h file add the delegate <AVAudioPlayerDelegate>
In your .m file #import <AVFoundation/AVFoundation.h>
Create a property AVAudioPlayer *_backgroundMusicPlayer;
Create this method:
- (void)playBackgroundMusic:(NSString *)filename {
NSError *error;
NSURL *backgroundMusicURL = [[NSBundle mainBundle] URLForResource:filename withExtension:nil];
_backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:backgroundMusicURL error:&error];
_backgroundMusicPlayer.numberOfLoops = -1;
_backgroundMusicPlayer.volume = 0.2;
_backgroundMusicPlayer.delegate = self;
[_backgroundMusicPlayer prepareToPlay];
[_backgroundMusicPlayer play];
}
To start playing [self playBackgroundMusic:[NSString stringWithFormat:#"bgMusic.mp3"]];
To stop playing [_backgroundMusicPlayer stop];
That should do the trick. I suggest you read up on the AVAudioPlayer Class Reference so you understand its properties. For example, numberOfLoops set to -1 will loop the sound indefinitely until you call the stop method. Another issue to keep in mind is the audio file sound format. AVFoundation is somewhat picky about what sound files it will play. I always stick to mp3.
Fuzzygoat also makes an excellent point. I have not tried his approach in regards to sound so I do not know if it will solve your issue. It is similar to what you already have but with a slight change.
To start the sound:
SKAction *mySound = [SKAction repeatActionForever:[SKAction playSoundFileNamed:#"astroKitty 1.m4a" waitForCompletion:YES]];
[self runAction:mySound withKey:#"boogieDown"];
To stop the sound:
[self removeActionForKey:#"boogieDown"];

Related

How do I control playback of a video in an iOS Sprite Kit SKVideoNode?

I load a video into my Sprite Kit SKVideoNode, but how do I stop and restart the playback or go to a specific time in the video? All I see are play and pause methods.
// AVPlayer
NSURL *fileURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"HowToPlay" ofType:#"mp4"]];
_avPlayer = [AVPlayer playerWithURL:fileURL];
// SKVideoNode
_videoNode = [SKVideoNode videoNodeWithAVPlayer:_avPlayer];
[_videoNode play];
This turned out to work for me.
Restart:
[_videoNode removeFromParent];
_videoNode = [SKVideoNode videoNodeWithVideoFileNamed:#"video.mp4"];
_videoNode.position = ...
_videoNode.size = ...
[self addChild:_videoNode];
[_videoNode play];
Pause:
[_videoNode pause];
_videoNode.paused = YES;
Play:
[_videoNode play];
_videoNode.paused = NO;
All you can do with a SKVideoNode is documented here. play and pause are the only supported playback methods.
There is no stop because its equivalent to pause in this context - what should "stop" do, render a black texture? If the SKVideoNode should be removed on "stop" then just send it the removeFromParent message, that'll "stop" it.
Rewind is unnecessary because you can simply run the play method again or create a new SKVideoNode.
I assume jumping to a specific timeframe isn't supported because this can't be instant, so again there's the problem of what the node should display in the time until the video playback position was moved to the specified timestamp?
If you keep a reference to the AVPlayer object used to initialize the video node then you can control playback with its methods

Find out whether AVPlayer is loading or playing mp3 from internet

I would like to use AVPlayer to stream a .mp3 from internet
[[AVPlayer alloc] initWithURL:url];
It all works apart from the fact that I am unable to tell whether player is Loading (buffering) or playing ?
I have tried to use KVO on many properties, but none seem to provide me with a simple way of determining whether the AVPlayer is currently actually playing audio or whether it is loading data. It is driving me nuts.
Thank you for your suggestions in advance
You can detect when buffering is done and playback has started by creating a periodic time observation (using addPeriodicTimeObserverForInterval:queue:usingBlock:) to detect when the play time has started to move. For example:
AVPlayer *player;
// allocate AVPlayer and start playing
__weak PlayerController *blockSelf = self;
id observerToken = [player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(1.0, NSEC_PER_SEC)
queue:nil
usingBlock:^ (CMTime time)
{
if (CMTimeGetSeconds(time) > 0.0)
{
// done buffering, should be playing now
[player removeTimeObserver:[blockSelf playerTimeObserverToken]];
[blockSelf setPlayerTimeObserverToken:observerToken:nil];
}
}];
[self setPlayerTimeObserverToken:observerToken]; // Keep a reference to the token for later use in block.

How to mute/unmute audio when playing video using MPMoviePlayerController?

I've created my own custom controls for use with the MPMoviePlayerController. So far everything works except the mute button control.
I've configured the AVAudioSession using the following code before I create my instance of the MPMoviePlayerController.
NSError *modeError = nil;
[self.audioSession setMode:AVAudioSessionModeMoviePlayback error:&modeError];
if (modeError != nil) {
NSLog(#"Error setting mode for AVAudioSession: %#", modeError);
}
NSError *categoryError = nil;
[self.audioSession setCategory:AVAudioSessionCategoryPlayback error:&categoryError];
if (categoryError != nil) {
NSLog(#"Error setting category for AVAudioSession: %#", categoryError);
}
Then in my mute button callback method I have the following code:
NSError *activeError = nil;
[self.audioSession setActive:NO error:&activeError];
if (activeError != nil) {
NSLog(#"Error setting inactive state for AVAudioSession: %#", activeError);
}
When clicking the Mute button I get the following unuseful error:
Error Domain=NSOSStatusErrorDomain Code=560030580 "The operation couldn’t be completed. (OSStatus error 560030580.)"
I am linking to the AVFoundation framework.
This is really starting to bug me as I can't for the life of me work out a way to reduce or mute the playback audio of my application.
I don't want to change the system global volume just the application level volume as defined by the AVAudioSession AVAudioSessionCategoryPlayback category.
It seems that you can set the volume of the AVAudioPlayer but not the MPMoviePlayerController. I've seen other posts here on SO that say just create an instance of AVAudioPlayer and set the volume but this just causes my app to crash and I expect it has something to do with the fact I'm not using the initWithContentsOfURL:error: or initWithData:error: and instead using `init'.
Any help would be appreciated.
After speaking to an Apple technician it turns out that it's not possible to control or mute the audio using MPMoviePlayerController.
Instead you have to create your own controller using AVFoundations AVPlayer class.
Once you're using that it's a matter of creating a custom audio mix and setting the volume level. It actually works very well.
Sample code:
AVURLAsset * asset = [AVURLAsset URLAssetWithURL:[self localMovieURL] options:nil];
NSArray *audioTracks = [asset tracksWithMediaType:AVMediaTypeAudio];
// Mute all the audio tracks
NSMutableArray * allAudioParams = [NSMutableArray array];
for (AVAssetTrack *track in audioTracks) {
AVMutableAudioMixInputParameters *audioInputParams =[AVMutableAudioMixInputParameters audioMixInputParameters];
[audioInputParams setVolume:0.0 atTime:kCMTimeZero ];
[audioInputParams setTrackID:[track trackID]];
[allAudioParams addObject:audioInputParams];
}
AVMutableAudioMix * audioZeroMix = [AVMutableAudioMix audioMix];
[audioZeroMix setInputParameters:allAudioParams];
// Create a player item
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:asset];
[playerItem setAudioMix:audioZeroMix]; // Mute the player item
// Create a new Player, and set the player to use the player item
// with the muted audio mix
AVPlayer *player = [AVPlayer playerWithPlayerItem:playerItem];
self.mPlayer = player;
[mPlayer play];
I've written an MPMoviePlayerController replacement class that adds support for volume level. I will upload the to github shortly and add the link in this post.
I know this is an old post, but I managed to find a way to successfully control the volume of the MPMoviePlayerController control in iOS6 & iOS7, using an MPVolumeView. One gotcha is that it does NOT work in the simulator, only on the physical device. For just controlling the volume, adding a hidden MPVolumeView will work fine. However if you use a hidden one, the native OS volume display that appears when you change the volume using the physical device volume buttons will still appear centre screen. If you want to prevent this, make sure your MPVolumeView is not hidden. Instead, you can give it a very low alpha transparency and place it behind other views, so the user can't see it.
Here's the code i've used:
MPVolumeView *volumeView = [[MPVolumeView alloc]initWithFrame:CGRectZero];
[volumeView setShowsVolumeSlider:YES];
[volumeView setShowsRouteButton:NO];
// control must be VISIBLE if you want to prevent default OS volume display
// from appearing when you change the volume level
[volumeView setHidden:NO];
volumeView.alpha = 0.1f;
volumeView.userInteractionEnabled = NO;
// to hide from view just insert behind all other views
[self.view insertSubview:volumeView atIndex:0];
This allows you to control the volume by calling:
[[MPMusicPlayerController applicationMusicPlayer] setVolume:0.0];
But I was still getting the native OS volume display appearing the first time I would try to change the volume - on subsequent loads it did not show this display, so figuring it was something to do with the stage in the viewcontroller life cycle, I moved it from my viewDidLoad method to the viewDidAppear method - it worked - the volume muted and the native volume display did not appear, but I now was able to hear a split second of audio before the video started playing. So I hooked into the playback state did change delegate of the MPMoviePlayerController. In viewDidload I added:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(videoPlaybackStateDidChange:)
name:MPMoviePlayerPlaybackStateDidChangeNotification object:nil];
And the delegate callback method:
-(void)videoPlaybackStateDidChange:(NSNotification *)aNotification
{
// Note, this doesn't work in simulator (even in iOS7), only on actual device!
if ([moviePlayerController playbackState] == MPMoviePlaybackStatePlaying)
{
[[MPMusicPlayerController applicationMusicPlayer] setVolume:0.0];
}
}
This muted the audio of the video before it started playing, but after the viewDidLoad in the life cycle, so no native OS volume muted display.
In my app, I retrieved and stored the current volume level before muting (using [MPMusicPlayerController applicationMusicPlayer].volume property), and then restored the volume to this level when the view controller was closed, meaning the user would be unaware that their device volume level was modified and reverted.
Also, if your MPMoviePlayerController is using a non-standard audio route in iOS7, calling [[MPMusicPlayerController applicationMusicPlayer] setVolume:0.0] may not work for you - in this case you can loop through the subviews of your MPVolumeView control until you find a view which subclasses UISlider. You can then call [sliderView setValue:0 animated:NO] which should work for you. This method isn't using any private Apple APIs so shouldn't get your app rejected - after all there are so many legitimate reasons why you would offer this functionality, and it was possible in iOS6 without having to go to these lengths! In fact, I was bamboozled to discover that Apple had removed the functionality to set the volume on MPMoviePlayerController in iOS7 in the first place.. enforced migration to AVPlayer?
Update: My iPad app has now been approved using this method and is live on the app store.

iOS AVAudioPlayer does not play while finger panning MKMapView

I have a basic beep sound that I loaded with AVAudioPlayer in my app.
It can play the beep fine if my finger isn't panning my MKMapView.
My beep is set to play every 2 seconds.
When I start panning the map view, and don't take my finger off the screen, the beep stops playing.
I recall NSUrlConnection also doesn't fire while scrolling a table view, I thought this might be the same problem but I couldn't figure out how I can add my audio player to the proper run loop.
I setup my player like this:
-(void)setupBeep
{
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/beep.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;
if(error)
{
NSLog(#"Error opening sound file: %#", [error localizedDescription]);
}
}
and I am playing my sound like this:
// plays a beeping sound
-(void)beep
{
[audioPlayer play];
}
Anyone came across this problem before?
How have you scheduled your -beep method to be called?
I suspect you’ve added an NSTimer to the main run loop in the default input mode. The reason you’re not hearing anything is that while MKMapView is tracking your finger, the run loop is in not in NSDefaultRunLoopMode—it’s in UITrackingRunLoopMode.
Try scheduling in NSRunLoopCommonModes, which includes both default and tracking modes:
NSTimer *timer = [NSTimer timerWithTimeInterval:interval target:self selector:#selector(beep) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
Also, be aware that NSTimer retains its target. A repeating timer will reschedule itself automatically, so you’ll need to call its -invalidate method to remove it from the loop and allow the target to be released.
EDIT: Check out Apple’s Threading Programming Guide: Run Loops for a much more detailed explanation.

AVAudioPlayer only plays a custom audio file for one second

In my application I am using an AVAudioRecorder object to allow the user to record a sound file, and when the user is done recording they can play the sound via the AVAudioPlayer. The issue I'm having is when the user tries to play the audio file it only plays for one second. What is even more odd is that this code worked perfect on iOS 5, but since upgrading to iOS 6 this issue has started to happen.
I have checked the file that is being created via iTunes file sharing, and I'm able to play the entire sound file on my desktop.
Below I have pasted the code from my manipulation file that loads the audio player. From what I can tell the
- (void)playRecordingBtnClk:(id)sender
{
NSLog(#"Play btn clk");
if (!isRecording) {
// disable all buttons
[_recordButton disableButton];
[_stopButton disableButton];
[_playButton disableButton];
[_saveButton disableButton];
// create the player and play the file from the beginning
if (audioPlayer) {
[audioPlayer release];
audioPlayer = nil;
}
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioRecorder.url error:&error];
audioPlayer.delegate = self;
audioPlayer.currentTime = 0.0;
[audioPlayer prepareToPlay];
if (error) {
NSLog(#"Error Playing Audio File: %#", [error debugDescription]);
return;
}
[audioPlayer play];
[self startTicker];
}
}
It appears that the
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
method is being called after one second which is why the audio player stops. Anyone have any ideas what is going on here?
For iOS 6.0, add two more lines:
soundPlayer.currentTime = soundPlayer.duration + soundPlayer.duration;
soundPlayer.numberOfLoops = 1;
Not a perfect solution. We may need to wait for iOS 6.0.1/6.1 update.
For more, please visit this, someone commented there, saying it might be a problem of CDAudioManager.

Resources