How to add Ionic2 native button click sound?

Viewed 1492

Many native app's buttons have a native click sound. Can anyone please tell me how to add native click sound for all buttons in Ionic 2.

2 Answers

Although this question asks specifically about Ionic 2, it's currently still the top Google result even when searching about Ionic 3.

The accepted answer doesn't work for Ionic 3; Ionic 3 components are probably assigned different class names to Ionic 2 components.

The solution below works for Ionic 3 (and might also work for Ionic 2). It registers a document-wide event handler to inspect the clicked element and its ancestors, and manually triggers nativeclick if a <button> is found:

// ↓↓↓ BEGIN ADDITION 1 OF 2 ////////////////////////////////////////////////////

declare var nativeclick: { trigger: () => void };

// ↑↑↑ END ADDITION /////////////////////////////////////////////////////////////

// @Component({ templateUrl: 'app.html' })
// class MyApp

constructor(
    platform: Platform,
    statusBar: StatusBar,
    splashScreen: SplashScreen,
) {
    platform.ready().then(() => {

// ↓↓↓ BEGIN ADDITION 2 OF 2 ////////////////////////////////////////////////////

        const nativeClickListener = (event: Event) => {
            // Traverse through the clicked element and all ancestors.
            for (
                let curElement = <Element> event.target;
                curElement != null;
                curElement = curElement.parentElement
            ) {
                // If a BUTTON element is encountered, trigger a click and stop.
                if (curElement.tagName === 'BUTTON') {
                  // ‘nativeclick’ doesn't exist outside Cordova's environment.
                  typeof nativeclick !== 'undefined' && nativeclick.trigger();
                  break;
                }
            }
        };
        // Call the above listener whenever anything is clicked, ensuring that it
        // is called before more specific EventTargets (or else clicks won't be
        // heard on e.g. <ion-datetime> components or <ion-navbar> back buttons).
        document.addEventListener('click', nativeClickListener, true);

// ↑↑↑ END ADDITION /////////////////////////////////////////////////////////////

        statusBar.styleDefault();
        splashScreen.hide();
    });
}

The above code assumes that you've installed the cordova-plugin-nativeclicksound plugin:

$ cordova plugin add cordova-plugin-nativeclicksound

Although looking for only <button> elements has been enough for me, it might be necessary to watch for more tag names. Adjust as necessary.

Related