Using HTML5 + Socket.IO to achieve a shake control PC end song switch

I prefer to listen to music, especially on the weekend, the computer is in Baidu listening to FM, randomly play songs, lying in bed. But I have encountered an annoying thing, I want to cut the music that I don’t like, I have to get up to operate the computer to change the song. So thinking that you can use your mobile phone to control your computer to switch songs. After a conditional thinking, you will absolutely use HTML5 + Socket.io to implement this function. First of all, I split this function into the following steps:

1. Mobile front end page + script logic implementation

2. PC end page + Script logic implementation


4. Add Socket.IO to achieve long connection

5. Implement mobile control PC-side logic

1, the implementation of the mobile terminal page script

HTML page Writing


imitated WeChat shake a shake page, realize A similar interface as follows:


When we shake the hand, it will be an animation, the intermediate pattern is divided into two, the upper half Upset and then return, the second half is also synonymous, as shown below:

利用HTML5+Socket.io实现摇一摇控制PC端歌曲切换

Mobile interface


HTML code (Shake .html):

利用HTML5+Socket.io实现摇一摇控制PC端歌曲切换


shakes a swing song

           
SHAKE.CSS):
HTML, Body {Width: 100%; Height: 100%; Background-Color: # 000; Margin: 0; Overflow: hidden;} .wrap {position: absolute; left: 50%; top: 50%; Width: 132px; -Webkit-Transform: Translate (-50%, - 50%); Transform: Translate (-50%, - 50%);} .hand {Position: absolute; left: 0; Width: 100%; Height: 50%; Background: URL (Shake.png) No-repeat # 000; Background-Size: 132px 132px;} .above-hand {TOP: 0; Background-Position: 0 0; } .below-hand {bottom: 0; Background-position: 0 -66px;} .inner {position: absolute; top: 50%; Left: 50%; Width: 50px; Height: 90px; Background: URL (Inner). PNG) NO-REPEAT 0 0; Background-Size: 50px 90px; -Webkit-Transform: Translate (-50%, - 50%); Transform: Translate (-50%, - 50%);} .above-hand: after, .below -Hand: Before {Display: None; Content: '; Position: Absolute; Left: -100vw; width: 200vw; Height: 2px; Background-Color: # Babdc1;} .above-hand: after {bottom: 0; } .below-hand: before {top: 0;} .wrap.active .above-hand {-webkit-animation: UP 1.5s ease; animation: Up 1s ease;}. wrap.active .blow-hand {-webkit -animation: Down 1.5s ease;} .wrap.active .above-hand: after, .wrap.active .blow-hand: before {display: block;} .tip {position: absolute; bottom : 30px; Left: 10px; Color: #fff; font-family: '体';TEXT-Align: Center; Right: 10px; Height: 32px; Line-Height: 32px; Background-Color: RGBA (255, 255, 255 ,.4); border-radius: 3px;} .tip.active {-webkit-animation: jump 1.5s linear; animation: jump 1s linear;}
Next is the implementation of the mobile JS script logic, shake one The realization of the shake needs to use the HTML5 new DeviceMotion event, obtain information about the change speed of the device in the location and direction, the basic use of the event is as follows:
IF Window.DeviceMotionEvent) {WINDOW.ADDEVENTLISTENER ('DeviceMotion', Handler,! 1);} else {Alert ('Your browser does not support shaking, ");}
DeviceMotion event object has an AccelerationIncludingGraVity property that includes an object containing x, y, and z attributes, tells you acceleration in each direction in consideration of the natural gravity acceleration of the z-axis. The specific use of the API can refer to the online information, there are very many, this is not repeated here.

The specific logic of shake is as follows:

 Function Handler (e) {var current = E.AccelerationinCludinGgravity; var currenttime; var timedife; var deltax = 0; var delta = 0; VAR deltaz = 0; // Record the acceleration IF in the X, Y, Z direction ((Lastx === Null) in the X, Y, Z direction Lasty === NULL) && (Lastz === NULL)) {Lastx = Current.x; Lasty = current.y; lastz = current.z; return;} // Get acceleration absolute gap in each direction in each direction in each direction Deltax = math.abs (Lastx - current.x); deltay = math.abs (Lasty - current.y); deltaz = math.abs (Lastz - current.z); // When the gap is greater than the set thix, When the time interval is greater than the specified threshold, trigger a shake logic IF ((Deltax> Threshold) || (DELTAX> Threshold) || ((Deltay> Threshold) || ((Deltay> Threshold) ) && (deltaZ> threshold))) {currentTime = new Date (); timeDifference = currentTime.getTime () - lastTime.getTime (); if (timeDifference> timeout) {dealShake (); lastTime = new Date ();}}}} Lastx = Current.x; Lasty = current.y; Lastz = current.z;}   Since the shake needs to play a shake sound and switch songs Successful sound, but because most mobile phones are automatic playback of the audio, the user must be truly click to play audio. There is no thorough solution here, just changed a thinking, using the user to touch the habit of the screen, listen to the Document TouchStart event. When the user touches the screen, play a 1S no sound frequency, then remove the TouchStart event, then switch the sound source, play a shake sound, so that similar purpose can be achieved. The code is as follows: 
Document.addeventListener (‘TouchStart’, AutoPlay,! 1); function autoplay () {Shaking.Play () ;fact () ;fact (); FOUND.PLAY ()


2, PC end page script logic implementation
   
The PC side interface is also an interface of an HTML5 music player on the web. The effect is as follows:


HTML (shake_pc.html) layout code is as follows:
   
listening to

[1
   
BY


利用HTML5+Socket.io实现摇一摇控制PC端歌曲切换

              
CSS style
The style layout is very simple, there is nothing to say. The CSS style code (shake_pc.css) is as follows:
body {font-family: 'Open Sans', Sans-Serif; Overflow: hidden; } .BG {Position: Absolute; Left: 0; Right: 0; Top: 0; Bottom: 0; Margin: -30px; Filter: BLUR (30px); -Webkit-Filter: BLUR (30px); BackgrouNd: URL (./ IMGAES / BG.JPG) No-repeat; Background-Size: Cover;} .music-player {Position: Relative; Width: 350px; Height: 290px; Margin: 150px auto; box-shadow: 0 0 60px RGBA (0, 0, 0, 0.8); Border-Radius: 7px; Background: # 222; overflow: hidden; z-index: 0;} .info {position: relative; width: 100%; Height: 80px Padding-top: 20px; color: # 585858; text-align: center;} .info .song-name {height: 30px; font-size: 30px; font-weight: 300;} .info .author {margin- Top: 14px; font-size: 14px;} .progress {position: absolute; left: 0; bottom: 0; width: 0; Height: 3px; Background-Color: # ed553b;} .controls {height: 190px; background -COLOR: RGBA (152, 46, 75, 0.6; Text-align: center;} .controls .time {font-size: 48px; height: 84px; line-height: 84px; Color: RGBA (225, 225, 225, 0.4); } .play-controls .btn {Display: inline-block; width: 95px; height: 40px; vertical-align: top;} .play-controls .btn.prev {background: URL (./ Imgaes / Prev.png) No-repeat center center;} .play-controls .btn.play {background: URL (./ Imgaes / Play.png) No-repeat center center;} .play-controls .btn.next {background: URL (./ Imgaes / next.png) No-repeat center center;} .volume-bar {POSITION: Relative; Width: 250px; height: 2px; margin: 30px auto 0;} .volume-bar .vol-muted {position: absolute; LEFT: 0; top: -6px; width: 10px; Height: 13px; Background: URL} .volume-bar;} .volume-bar .vol-slider {position: absolute; left: 14px; Right: 28px; top: 0; Height: 100%; Background-Color: RGBA (255, 255, 255, .3);} .volume-bar .vol-slider-inner {Display: block; width: 50%; Height: 100%; Background-Color: # ed553b;} .volume-bar .vol-max { Position: Absolute; Right: 0; Top: -8.5px; Width: 22px; Height: 18px; Background: URL (./ Imgaes / Max.png) No-repeat center center;}
Script logic
After the document is loaded, it is randomly acquired a music and then play. Clicking on the previous or next song is randomly switching song, and can control the volume, interested friends can also achieve the synchronous play of the lyrics. About HTML5 Media Native API, you can refer to the attributes, methods and event summary of the HTML5 VIDEO tag
Some code is as follows:
const http = require ('http'); var express = required ('expression "); var app = expression (); var server = required (' http '). Server (app); var = required (' socket .io ') (Server); app.use (express.static (' ./ ')); app.get (' / ', (req, res) => {var userAgent = Req.heAdrs ['User-Agent']. TOLOWERCASE (); if (/ (/ (/ (/ (use)) {res.sendfile (__ DIRNAME + '/ shake_m.html');} else {res. extendedfile (__Dirname + '/ shake_pc.html');}});}}); IO.ON ('connection', function (socket) {var usrname = ', senddata = {}; console.log (' aclient connection ... ' + socket.id); socket.on ('disconnect', function () {console.log (`device $ {socket.id} Disconnected.`);}; socket.on ('Message', Function) DATA) {var cmd = data.cmd; // next command is sent by the mobile terminal, the OK command is sent by the PC Song successfully sent the command IF (cmd == 'next') {socket.broadcast.emit ('Next ');} else if (cmd ==' ok ') {socket.broadcast.emit (' ok ', data.data);}});}); Server.Listen (3000, function () {Console.log ('Start Listening On 3000 Port ...');});
First introduced socket.js in the page, then connect the Socket server, then listen to the event, as shown below: // Mobile Socket Logic Socket .on ('connect', Function () {Console.log ('WebSocket Connection has been established ...);}); socket.on (' ok ', function (data) {if (bound.src! = Host + 'found.mp3') {Found.SRC = 'found.mp3';} found.play (); tip.innerText = 'is appreciating:' + Data.Artist + '-' + data.title; tip.classlist. Remove ('Active'); Tip.OffSetWidth = Tip.OffSetWidth; Tip.ClassList.Add ('Active');}); Function Dealshake () {if (Isshaking) Return; Isshaking =! 0; IF (Shaking.SRC ! = Host + 'Shaking.mp3') {Shaking.SRC = 'Shaking.mp3';} Shaking.Play (); wrap.classlist.add ('Active'); settimeout (Function () {socket.emit ('Message ', {cmd:' next ', data: null});}, 1000);} // PC side SOCKET logic function initioevts () {socket.on (' connection ", function () {Console.log ('WebSocket connection has been established ...);}); socket.on (' next ', function (data) {getsong (). Then (Function (VAL) {var Song = DEALSONG (VAL); Socket.emit ('Message', {CMD: 'OK', DATA: SONG});}, function (err) {console.log (err);});};}

When the user rocking the device trigger a shake, send a new command message to the server, then forward the message to the PC side, the PC side receives the message, execute the song switching operation And feedback a OK command message and carry a song message to the server, the server forwards the message back to the mobile terminal, the mobile side plays the successful sound and displays the songs of the current PC play.

This feature is mainly used by my own, and some details may not be processed. You can make some multi-screen interactions on this basis.

DEMO Download: http://xiazai.jb51.net/201701/yuanma/shake-music_jb51.rar

The above is all of this article, I hope to everyone I have helpful, I hope everyone will support Tumi Clouds.
                    
© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment