So I want to add vibration to my iOS app.
Simple enough:
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
and of course:
#import <AudioToolbox/AudioServices.h>
But there is a catch - it won't work alongside AQRecorder in the same ViewController.
(AQRecorder is a helper class for recording audio files via the AudioQueue made by Apple - Version: 2.5)
In that case, when I'm using the recorder the vibration won't work.
Closest I could get to a solution was to vibrate device before initializing the recorder. After that, even when I stop the recorder and put nil wherever it makes sense, the vibration won't work.
Does anyone have some ideas what else can I try to make it work?
I'm open for hacks and/or "crazy" solutions :)
EDIT:
My real problem is that I want to record and vibrate device in the same time. AQRecorder is not necessarily the only solution (even though it's preferable since I already implemented it).
So any other potential solution is a good solution.
Related
I would like to present an alert if the sound is 0.
I found this library https://github.com/moshegottlieb/SoundSwitch, but it doesn't seem to work. At least not on a simulator
Have you seen this question? They give various answers:
float vol = [[AVAudioSession sharedInstance] outputVolume];
NSLog(#"output volume: %1.2f dB", 20.f*log10f(vol+FLT_MIN));
Nonetheless it doesn't seems to work using the simulator (I'm trying and it always return the same value). This lead me to think maybe it's not something we can check from the simulator. Can you try on a real device? Let me know if it works.
EDIT: Ok so reading about it it seems there's no API avaiable to check silent mode. Anyway what people have found a workaround: Playing a short audio with no volume. If the time when it finishes (minus time when it started) is lower than the actual length of the audio is on mute mode (being in the silent mode the audio will last 0 seconds).
So, here somebody posted a class that do that for you. Let me know if it works
I am currently working on a PhoneGap application that, upon pressing a button, is supposed to play an 8 seconds long sound clip, while at the same time streaming sound from the microphone over RTMP to a Wowza server through a Cordova plugin using the iOS library VideoCore.
My problem is that (on iOS exclusively) when the sound clip stops playing, the microphone - for some reason - also stops recording sound. However, the stream is still active, resulting in a sound clip on the server side consisting of 8 seconds of microphone input, then complete silence.
Commenting out the line that plays the sound results in the microphone recoding sound without a problem, however we need to be able to play the sound.
Defining the media variable:
_alarmSound = new Media("Audio/alarm.mp3")
Playing the sound and starting the stream:
if(_streamAudio){
startAudioStream(_alarmId);
}
if(localStorage.getItem("alarmSound") == "true"){
_alarmSound.play();
}
It seems to me like there is some kind of internal resource usage conflict occuring when PhoneGap stops playing the sound clip, however I have no idea what I can do to fix it.
I've encountered the same problem on iOS, and I solved it by doing two things:
AVAudioSession Category
In iOS, apps should specify their requirements on the sound resource using the singleton AVAudioSession. When using Cordova there is a plugin that enables you to do this: https://github.com/eworx/av-audio-session-adapter
So for example, when you want to just play sounds you set the category to PLAYBACK:
audioSession.setCategoryWithOptions(
AVAudioSessionAdapter.Categories.PLAYBACK,
AVAudioSessionAdapter.CategoryOptions.MIX_WITH_OTHERS,
successCallback,
errorCallback
);
And when you want to record sound using the microphone and still be able to playback sounds you set the category as PLAY_AND_RECORD:
audioSession.setCategoryWithOptions(
AVAudioSessionAdapter.Categories.PLAY_AND_RECORD,
AVAudioSessionAdapter.CategoryOptions.MIX_WITH_OTHERS,
successCallback,
errorCallback
);
cordova-plugin-media kills the AVAudioSession
The Media plugin that you're using for playback handles both recording and playback in a way that makes it impossible to combine with other sound plugins and the Web Audio API. It deactivates the AVAudioSession each time it has finished playback or recording. Since there is only one such session for your app, this effectively deactivates all sound in your app.
There is a bug registered for this: https://issues.apache.org/jira/browse/CB-11026
Since the bug is still not fixed, and you still want to use the Media plugin, the only way to fix this is to download the plugin code and comment out/remove the lines where the AVAudioSession is deactivated:
[self.avSession setActive:NO error:nil];
I found it took some effort to get the existing answers on this topic working with my code so I'm hoping this helps someone who needs a more explicit solution.
As of version 5.0.2 of the Cordova Media plugin this issue still persists. If you want to use this plugin, the most straightforward solution that I have found is to fork the plugin repository and make the following changes to src/ios/CDVSound.m. After quite some hours looking into this, I was unable to find a working solution without modifying the plugin source, nor was I able to find suitable alternative plugins.
Force session category
The author of the plugin mentioned in Edin's answer explains the issue with the AVAudioSession categories on a similar question. Since changes to CDVSound.m are necessary regardless, I found the following change easier than getting the eworx/av-audio-session-adapter plugin working.
Locate the following lines of code:
NSString* sessionCategory = bPlayAudioWhenScreenIsLocked ? AVAudioSessionCategoryPlayback : AVAudioSessionCategorySoloAmbient;
[self.avSession setCategory:sessionCategory error:&err];
Replace them with:
[self.avSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&err];
Prevent session deactivation
Further more, the changes suggested in Edin's answer are necessary to prevent deactivation of additional audio sessions, however, not all instances need to be removed.
Remove the following line and surrounding conditional statements from the functions audioRecorderDidFinishRecording(), audioPlayerDidFinishPlaying and itemDidFinishPlaying():
[self.avSession setActive:NO error:nil];
The other instances of the code are used for error handling and resource release and, in my experience, do not need to be and should not be removed.
Update: Playback Volume
After apply these changes we experienced issues with low audio volume during playback (while recording was active). Adding the following lines after the respective setCategory lines from above allowed for playback at full volume. These changes are explained in the answer from which this fix was sourced.
[self.avSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
and
[weakSelf.avSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
I have an application that can detect accidents, it is really important for us to alert users using vibration and alert sound if an accident is detected.
My questions are:
Is it possible to add long vibration in application by using custom sounds or something that apple might be ok with?
If I use private apis, is it possible to convince apple to approve my app considering that the use case is really critical?
Two questions here, really.
1st one: haptic feedback / control vibration on iOS / custom iOS patterns
No, it can't be done, even in the new Apple Watch without Jailbreaking your phone. You can have a look at this keyboard mod (needs Jailbreak). Here you have some code but it needs Jailbreaking your phone.
If you need to alert your users I recommend just playing the default vibration inside a while. Sleep the current thread for 1 sec, then vibrate again until some boolean flag changes. Objective-C Pseudocode:
while (!endVibrationAlert) {
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
[NSThread sleepForTimeInterval:1];
}
// when user touches some button to dismiss alert
self.endVibrationAlert = true;
2nd one: never ever try to bypass Apple's reviewing system. Abide by the rules. For your 1st version, maybe it passes. Then, in the next update your App can get rejected.
I placed 2 VLCMediaPlayer in the IPad ViewController.
Then I want to mute one of the players.
I executed the following code from VLCAudio class:
[VLCMediaPlayer.audio setMute:YES];
But the voice of the player was still on.
Then I added another piece of code:
[VLCMediaPlayer.audio setVolume:0];
Nothing had been changed.
Is it because both setMute and setVolue functions don’t work under the ISO VLCKit?
If so, how to mute VLCMediaPlayer by coding?
Set the current audio track to -1. Performance-wise, this is more efficient, too, since the audio information isn't even decoded.
Volume control (incl. mute) isn't supported with current versions of MobileVLCKit on iOS, but on the Mac only.
If you want to mute from the beginning, I found a way to do it.
Before you send play msg to the player instance, you should init it with options, such as
self.player = [[VLCMediaPlayer alloc] initWithOptions:#[#"--gain=0"]];
where "--gain=0" which means audio gain set to 0. This is not the documentation method, may not work on every version of mobile vlc framework. But it works for me.
If you want to mute while playing, you can try
self.player.currentAudioTrackIndex = -1;
This also works for me!
I'm setting up an AVAudioSession when the app launches and setting the delegate to the appDelegate. Everything seems to be working (playback, etc) except that beginInterruption on the delegate is not being called when the phone receives a call. When the call ends endInterruption is being called though.
The only thought I have is that the audio player code I'm using used to be based on AVAudioPlayer, but is now using AVPlayer. The callbacks for the AVAudioPlayer delegate for handling interrupts are still in there, but it seems odd that they would conflict in any way.
Looking at the header, in iOS6, it looks like AVAudioSessionDelegate is now deprecated.
Use AVAudioSessionInterruptionNotification instead in iOS6.
Update: That didn't work. I think there's a bug in the framework.
Yes, in my experience, beginInterruption, nor the newly documented AVAudioSessionInterruptionNotification work properly. What I had to do was track the status of the player using a local flag, then handle the endInterruption:withFlags: method in order to track recovery from interruptions.
With iOS 6, the resuming from an interruption will at least keep your AudioPlayer in the right place, so there was no need for me to store the last known play time of my AVAudioPlayer, I simply had to hit play.
Here's the solution that I came up with. It seems like iOS 6 kills your audio with a Media Reset if an AVPlayer stays resident too long. What ends up happening, is the AVPlayer plays, but no sound comes out. The rate on the AVPlayer is 1, but there's absolutely no sound. To add pain to the situation, there's no error on either the AVAudioSession setActive, nor the AVPlayer itself that indicates that there's a problem.
Add to the fact that you can't depend on appWillResignActive, because your app may already be in the background if you're depending on remote control gestures at all.
The final solution I implemented was to add a periodic observer on the AVPlayer, and record the last known time. When I receive the event that I've been given back control, I create a new AVPlayer, load it with the AVPlayerItem, and seekToTime to the proper time.
It's quite an annoying workaround, but at least it works, and avoids the periodic crashes that were happening.
I can confirm that using the C api, the interruption method is also not called when the interruption begins; only when it ends
(AudioSessionInitialize (nil, nil, interruptionListenerCallback, (__bridge void *)(self));
I've also filed a bug report with apple for the issue.
Edit: This is fixed in iOS 6.1 (but not iOS 6.0.1)
Just call:
[[AVAudioSession sharedInstance] setDelegate: self];
I just checked on my iPhone 5 (running iOS 6.0) by setting a breakpoint in the AudioSessionInterruptionListener callback function that was declared in AudioSessionInitialize(), and this interrupt callback does, in fact, get called when the app has an active audio session and audio unit and is interrupted with an incoming phone call (Xcode shows the app stopped at the breakpoint at the beginning of the interruption, which I then continue from).
I have the app then stop its audio unit and de-activate its audio session. Then, on the end interruption callback, the app re-activates the audio session and restarts the audio unit without problems (the app is recording audio properly afterwards).
I built a brand new audio streaming (AVPlayer) application atop iOS 6.0.x and found the same problem.
Delegates are now deprecated and we have to use notifications, that's great, however here's my findings:
During an incoming phone call I get only AVAudioSessionInterruptionTypeEnded in my handler, along with AVAudioSessionInterruptionOptionShouldResume. Audio session gets suspended automatically (audio fades) and I just need to resume playback of AVPlayer.
However when attempting to launch a game, such as CSR Racing, I oddly get the dreaded AVAudioSessionInterruptionTypeBegan but no sign when my application can resume playback, not even killing the game.
Now, this may depend on other factors, such as my audio category (in my case AVAudioSessionCategoryPlayback) and the mixing settings of both applications (kAudioSessionProperty_OverrideCategoryMixWithOthers), I'm not sure, but definitely I see something out of place.
Hopefully others reported that on 6.1beta this is fixed and I yet have to upgrade, so we'll see.