简体   繁体   中英

Detect press of “next track” button on keyboard?

I would like to be able to detect when the "next track," "previous track," and (where applicable) "shuffle" buttons on the user's keyboard. Is this even possible? Thanks!

Actually this is possible now using the Media session feature provided by browser. normal keyboard events normally won't support the player control buttons in keyboard. here's an example from mozilla docs :

 if ('mediaSession' in navigator) { navigator.mediaSession.metadata = new MediaMetadata({ title: 'Unforgettable', artist: 'Nat King Cole', album: 'The Ultimate Collection (Remastered)', artwork: [ { src: 'https://dummyimage.com/96x96', sizes: '96x96', type: 'image/png' }, { src: 'https://dummyimage.com/128x128', sizes: '128x128', type: 'image/png' }, { src: 'https://dummyimage.com/192x192', sizes: '192x192', type: 'image/png' }, { src: 'https://dummyimage.com/256x256', sizes: '256x256', type: 'image/png' }, { src: 'https://dummyimage.com/384x384', sizes: '384x384', type: 'image/png' }, { src: 'https://dummyimage.com/512x512', sizes: '512x512', type: 'image/png' }, ] }); navigator.mediaSession.setActionHandler('play', function() { /* Code excerpted. */ }); navigator.mediaSession.setActionHandler('pause', function() { /* Code excerpted. */ }); navigator.mediaSession.setActionHandler('seekbackward', function() { /* Code excerpted. */ }); navigator.mediaSession.setActionHandler('seekforward', function() { /* Code excerpted. */ }); navigator.mediaSession.setActionHandler('previoustrack', function() { /* Code excerpted. */ }); navigator.mediaSession.setActionHandler('nexttrack', function() { /* Code excerpted. */ }); }

Please note that this feature is not supported in all browsers.

if you know the key code you can. Although not all keyboards will have it, or perhaps will differ. (guessing)

see the keycode by doing this and hitting a key:

$(window).keydown( function(event){ console.log(event.keyCode); } );

when you have the code you can handle the event when that key is hit.

Fiddle: http://jsfiddle.net/JyKMN/

I can't seem to find the shuffle keyCode , but this captures the fast forward and rewind... There has to be a better way of doing what you are trying to do than this IMO.

$('#capture').on('keydown',function(e){
    switch (e.which) {
        case 176:
            alert('Fast Forward');
            break;
        case 177:
            alert('Rewind');
            break;
        default:
            alert('Neither FF or rewind was pressed');  
            }      
});

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM