How to play a sound for watch kit app - ios

From what I understand it is currently not possible to play a sound from your watch kit app on the watch. If this is the case what is the best way to play a sound? Currently I am using openParentApplication:reply: to run code on the phone that plays the sound. Is this the best way?
Update: I also found that I can play audio directly from the watch extension using the same methods as in the parent app. No Idea if this will actually play when not on the simulator.

There currently isn't any way to play audio on the Watch. Your assumptions are 100% correct. Apple doesn't want to have to transfer the audio clips from the Watch Extension to the Watch at runtime. Currently, the only supported transfer caching system is for images. For now, you will have to play the audio on the iOS device. You can use one of the following approaches to trigger playing the sound:
openParentApplication:reply: - opens app in the background if not currently running
Darwin notifications through something like MMWormhole
Playing the sound from the Watch extension is certainly a gray area. My guess is that it will play on the iOS Device or not play at all when testing with devices. I would certainly advise against that approach though. Your Watch Extension will typically only be open for a VERY short period of time. It would be a much better idea to play the audio from the iOS app since that is guaranteed to continue running.

As of watchOS 2, you can play audio files using WKAudioFilePlayer on the watch. It appears that mp3 files are not supported, but caf and wav are. Copy the sound file to the extension target.
Setup:
NSURL *assetURL = [[NSBundle mainBundle] URLForResource:#"file" withExtension:#"wav"];
WKAudioFileAsset *asset = [WKAudioFileAsset assetWithURL:assetURL];
WKAudioFilePlayerItem *playerItem = [WKAudioFilePlayerItem playerItemWithAsset:asset];
WKAudioFilePlayer *audioFilePlayer = [WKAudioFilePlayer playerWithPlayerItem:playerItem];
Play:
if (audioFilePlayer.status == WKAudioFilePlayerStatusReadyToPlay) {
[self.audioFilePlayer play];
}
Alternatively, you can use the WKInterfaceMovie class:
[self presentMediaPlayerControllerWithURL:assetURL options:nil completion:nil];

Related

AVPlayer removes background music

I've been using giffycat to decode, store, and play gifs in my app. I am making it so that it can easily load a gif in a UICollectionView's cell, so I have decided for each gif model to have its own AVPlayer. I have noticed that simply by creating an AVPlayer, shown bellow, audio from other apps is killed! Annoying for both the user and the creater!
// Create an AVURLAsset with an NSURL containing the path to the video
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:[NSURL URLWithString:_mp4] options:nil];
// Create an AVPlayerItem using the asset
AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset];
_player = [AVPlayer playerWithPlayerItem:item]; //if this line is commented out, I hear audio, else audio from Spotify is quickly killed...
Since these videos are just gifs, I am wondering if there is some way to unassign the audio session. I do not know much about this. ples help!
Turns out the answer is pretty easy, after a little googling and documentation reading...
The solution is
// audio session
let audioSession = AVAudioSession.sharedInstance()
try! audioSession.setCategory(AVAudioSessionCategoryAmbient,
withOptions: AVAudioSessionCategoryOptions.MixWithOthers)
oops, just realized I am posting my question in objC and answer in Swift. Well tough, because that's life sometimes.
AudioSession is a singleton for your entire app to rule how your application mingles with the other sounds of the system and other apps! The default audio session is
playback is enabled, recording is disabled
when user moves silent switch to "silent" your audio is silenced
when user presses sleep/wake button to lock screen or auto-lock period expires, your audio is silenced
when your audio starts, other audio on device (music) is silenced.
CategoryAmbient tells it not to do 4
Nice documentation!
https://developer.apple.com/library/ios/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/ConfiguringanAudioSession/ConfiguringanAudioSession.html#//apple_ref/doc/uid/TP40007875-CH2-SW1
Set the audioMix property of the AVPlayerItem to nil before creating an AVPlayer from it to remove the audio track from the asset.

Full-featured music player using AVPlayer

I'm writing a music player for iOS that needs to have all the features of the built-in Music app. My app needs to continue running in the background so I have to use the AVPlayer class.
Are there any open source implementations out there that I can use instead of writing the whole thing myself?
Just found this. It works great:
https://github.com/gangverk/GVMusicPlayerController
If you want to play tracks from your iTunes music library, and don't want to use the MPMusicPlayerController class, your best bet is to use AVPlayer or AVQueuePlayer (subclass of AVPlayer). You must establish the appropriate audio session and register to receive remote control events for the app to continue playing music in the background.
There are downsides to this method; you won't be able to play DRM-protected tracks and audiobooks purchased from the iTunes store. There's no way to instantiate an iTunes Match download with the AVPlayer class. Furthermore, you'll have a bit of work on your hands if you want to add gapless playback and equaliser settings (The closest you'll get to gapless playback is with the AVQueuePlayer subclass, though in theory, you could overlap AVPlayers with an NSTimer).
You'll also need to change 'Required Background Modes' in your Info.plist to 'App plays audio'
As for the rest of your app, I suggest you read up on UITabBarControllers and UITableViewControllers along with MPMediaQuerys.
See this solution for the audio part.

IOS 5 No audio when playing a video with Silent mode on with a buzztouch app

I have done several apps with buzztouch for Iphone and Ipads, here is a free one as an example :
http://itunes.apple.com/us/app/lr-basics-free-edition/id497563707?mt=8
I do not know code very much, I have very little basics that is why I designed my app using Buzztouch, which by the way is amazing !
The only one problem that I have is that the default behavior when you play a video (which was most of my apps are doing, playing tutorials) and if the silent mode is on either on Ipad or Iphone, there is no audio, even thought the volume slider is active, given the impressions to users that there is a bug, and I got some bad reviews due to that, I have also people writing me about it. I Then tell them all they have to do is to turn off the silent mode and they the audio is back, works everytime, but in the meantime I get complaits !
So here is my questions, is there a simple way I can located in the Buzztouch generated code a property that can easely be changed so that when a video is played, audio stays, despiste the silent mode being active.
I actually checked 4 or 5 other Iphones similar applications including the default youtube apple app, the default is that the audio plays even if the silent mode is turn on, giving my customer the impression that my app is bugged.
I'm not a programmer so please but as simple as possible in your answer.
Tku so much for the help.
Serge
What you are describing is the default behavior in iOS - when the ring/silent switch is in silent mode all audio from your app will be suppressed.
I don't know about implementing this from BuzzTouch, but here is a native solution I used to get around this for one of my apps that plays video:
MPMoviePlayerViewController *mpvc = [[MPMoviePlayerViewController alloc] initWithContentURL:myVidURL];
... set up player ...
// prevent mute switch from switching off audio from movie player
NSError *_error = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &_error];
[self presentMoviePlayerViewControllerAnimated:mpvc];
You will also need to include the AVFoundation framework for this to work.
Here's the link where I first found this tip:
http://www.24100.net/2011/05/ignore-ringtone-mute-switch-during-mpmovieplayer-video-playback-ios/
Right from documentation - iOS has 6 audio session categories out of that 3 affects the behavior of Slient switch:
AVAudioSessionCategoryAmbient or the equivalent kAudioSessionCategory_AmbientSound— Using this category, your audio is silenced by the Ring/Silent switch and when the screen locks. Used when we want our app audio with built-in app audio
AVAudioSessionCategorySoloAmbient or the equivalent kAudioSessionCategory_SoloAmbientSound—Use this category for an application whose audio you want silenced when the user switches the Ring/Silent switch to the “silent” position and when the screen locks. This is the default category
AVAudioSessionCategoryPlayback or the equivalent kAudioSessionCategory_MediaPlayback—Use this category for an application whose audio playback is of primary importance. Your audio plays even with the screen locked and with the Ring/Silent switch set to silent.
Hint: Upload the audio file to your buzztouch account files. This is the only way Buzztouch will recognize the audio. next, add the audio file to your xcode bttouch sound folder and add all references. You should be fine!

AVAudioPlayer, using AmbientSound session, is not playing when app is in background

If this is in the apple doc then I've not been able to find it - hoping someone can help:
My app plays occasional short audio clips - I want the audio to mix in with audio playing from other apps in the background like the iPod app - but I also want it to carry on playing these audio clips when the app is running in background.
I have set "App plays audio" in the Required Background Modes settings in info.plist (the app is also using location services too so that is also set in there)
My app sets up an audio session on applicationDidFinishLaunching:
AudioSessionInitialize (NULL,NULL,NULL,NULL);
UInt32 sessionCategory = kAudioSessionCategory_AmbientSound;
AudioSessionSetProperty (kAudioSessionProperty_AudioCategory,sizeof (sessionCategory),&sessionCategory);
AudioSessionSetActive(true);
In my viewWillAppear: method in the view that is active I have:
[super viewWillAppear:animated];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
and the corresponding event handler and endReceivingRemoteControlEvents code in viewWillDisappear: as discussed in iOS 4: Remote controls for background audio
Finally I have an AVAudioPlayer, set up in the normal way, that plays a sound on certain events
bool successful = [avAudioPlayer play];
if(!successful)
NSLog(#"did not play");
When the app is in foreground the app works fine and plays the audio - but when the app goes into background and the app attempts to play a sound the return value from the [avAudioPlayer play] is NO and the sound does not play - when switched back to foreground the audio starts working again.
If when I set up the session I instead use
UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
Then the audio plays in foreground and background perfectly. But MediaPlayback is not the really the right mode for this app since I am only occasionally playing audio clips - AmbientSound is really the mode I should be using.
What am I missing? Is it just not possible to use kAudioSessionCategory_AmbientSound to play Audio in the background? If so I've not found anything in the documentation about that.
Had to submit a tech support request for this in the end.
According to Apple background playback is not supported by the AmbientSound category - you have to use MediaPlayback.
They claim this is in the documentation - I've looked again and I could not find it.
Ok so getting background sounds to mix into MediaPlayback is easy enough using kAudioSessionProperty_OverrideCategoryMixWithOthers - but I am now going to have to jump through some other hoops to replicate the other AmbientSound functionality (obeying the mute switch and not playing when locked). I really don't understand why AmbientSound is not supported playing in background - but there we go.

iOS audio samples play only on earphone output

I'm developing a program that plays a short sample when a button is pressed. The problem is that it only plays through earphone output and not through the device's speaker. I've tried .wav and .aiff and AVAudioPlayer and SystemSoundID. On the simulator I can hear the sound. I'm using iPod Touch 4th gen. running iOS 4.1. Example code:
NSString *soundFile = [[NSBundle mainBundle] pathForResource:#"button" ofType:#"wav"];
NSURL *url = [NSURL fileURLWithPath:soundFile];
AudioServicesCreateSystemSoundID( (CFURLRef)url, &buttonID);
AudioServicesPlaySystemSound( buttonID );
Edit (solution found): I tried with another .wav file and it worked. Odd, because the original .wav's format is supported by iOS.
Sounds like you've solved the issue, but as a heads-up, you should only be using SystemSoundID style playback for user interface related sounds.
If the audio is a key part of your app, you need to set the appropriate AVAudioSession category and use (for example) the AVAudioPlayer playback methods.
Then again, this might not be relevant. :-)

Resources