How to play keyboard click sound in custom keyboard?

可紊 提交于 2019-11-30 07:56:37

问题


I had created custom keyboard with UIView. However I didn't hear click sound of keyboard. So I tried following codes.But I can't hear anythings. 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 next one.

AudioServicesPlaySystemSound(0x450);

How can I?


回答1:


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.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/10299021/how-to-play-keyboard-click-sound-in-custom-keyboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!