17

I had created custom keyboard with UIView. However, I didn't hear the click sound of the keyboard. So I tried following code, but I can't hear anything. How can I play that keyboard click sound?

NSURL* musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle] 
                                               pathForResource:@"Tock"
                                               ofType:@"aiff"]];
    AVAudioPlayer *click = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil];
    [click setVolume:0.15f];
    [click play];

And also I tried this:

AudioServicesPlaySystemSound(0x450);

How can I achieve this?

Community
  • 1
  • 1
Fire Fist
  • 7,032
  • 12
  • 63
  • 109

4 Answers4

35

Try this:

[[UIDevice currentDevice] playInputClick];

Note that

Use this method to play the standard system keyboard click in response to a user tapping in a custom input or keyboard accessory view. A click plays only if the user has enabled keyboard clicks in Settings > Sounds, and only if the input view is itself enabled and visible.

To enable a custom input or accessory view for input clicks, perform the following two steps:

Adopt the UIInputViewAudioFeedback protocol in your input view class. Implement the enableInputClicksWhenVisible delegate method to return YES.

Anh
  • 6,523
  • 7
  • 46
  • 59
  • 7
    I followed the instructions, but however, there is no click sound on my keyboard. On system keyboard click sound works. – iOS Dev Aug 19 '14 at 14:29
6

Couldn't get any of this to work, but this worked for me:

#import <AudioToolbox/AudioToolbox.h>

AudioServicesPlaySystemSound(1104);

But still I had to subclass a UIButton and add the UIInputViewAudioFeedback Protocol to it.

Kurt Van den Branden
  • 11,995
  • 10
  • 76
  • 85
Simon Unsworth
  • 321
  • 1
  • 3
  • 8
  • This worked. I did not even have to add UIInputViewAudioFeedback protocol. But it does not honor system setting of keyboard click sound. I'm on iOS 11. – Chuck Boris Jan 11 '18 at 16:28
6

In Swift add an extension to the input view as follows;

extension UIInputView : UIInputViewAudioFeedback {

    public var enableInputClicksWhenVisible: Bool {
        return true
    }

}

In the action method for your buttons call the following function:

    UIDevice.current.playInputClick()

Add the following property to your info.plist:

NSExtension | NSExtensionAttributes | RequestsOpenAccess = YES

Litehouse
  • 864
  • 8
  • 14
  • It plays sound even if we disable the keyboard sound from "phone settings" , any solution.. – Kiran P Nair Aug 04 '17 at 05:31
  • As i recollect, it works, but it's a caching issue. If you restart the device after making the settings change it will take effect. – Litehouse Sep 21 '17 at 17:40
1

For swift there's actually an incredibly easy way to play keyboard sound effect.

first:

import AudioToolbox

then use this whenever you need the sound effect.

AudioServicesPlaySystemSound(0x450)
WaliD
  • 220
  • 3
  • 8