Cara mengakses kamera webcam dari web dengan javascript / jquery

Selamat malam kali ini admin akan memposting cara mengakses webcam sendiri di browser dengan javascript. disini saya menggunakan node.js, socket.io dan jquery

Pertama-tama buat file package.json dengan isi seperti berikut:
{
       
"name" : "Wcam-Live",
       
"version" : "0.0.1",
       
"dependencies" : {
       
"socket.io" : "*",
       
"express" : "*",
       
"log" : "*"
       
}
}

kemudian ketikan perintah npm install di command promt

selanjutnya buat file app.js dengan isi seperti dibawah:
var express = require("express");

var app = new express();

var http = require("http").Server(app);

var io = require("socket.io")(http);



    var Log = require('log'),

    log = new Log('debug')



    var port = process.env.PORT || 3000;



    app.use(express.static(__dirname + "/public"));



    app.get('/',function(req,res){

    res.redirect('index.html');

    });



    io.on('connection',function(socket){

    socket.on('stream',function(image){

    socket.broadcast.emit('stream',image);

    });

    });



    http.listen(port,function(){

    log.info('server di jalankan pada port %s',port);

    });

kemudian test di browser dengan dengan perintah node app.js

selanjunya buat folder dengan nama public, didalam folder public buat tiga file index.html, emitir.html dan visualizar.html
untuk isi index.html masukan kode dibawah:
<!DOCTYPE html>

<html>

<head>

<title>Webcam-Live</title>

</head>

<body>

<p><a href="emitir.html">Emitir Video</a></p>



<p><a href="visualizar.html">Visualizar web</a></p>

</body>

</html>

kemudian untuk isi emitir.html masukan kode berikut :
<!DOCTYPE html>

<html>

<head>

<title>Emitir Video</title>

<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.2.min.js"></script>

<script type="text/javascript" src="/socket.io/socket.io.js"></script>

</head>

<body>

<video src="" id="video" style="width: 680px;height:320px;" autoplay="true"></video>

<iframe src="visualizar.html" height="400px" width="40%" style="overflow-x: hidden;overflow-y: hidden;"></iframe>



<canvas style="display: none" id="preview"></canvas>

<div id="logger"></div>



<script type="text/javascript">

        var canvas = document.getElementById('preview');

        var context = canvas.getContext("2d");



        canvas.width = 800;

        canvas.height = 600;



        context.width = canvas.width;

        context.height = canvas.height;



        var video = document.getElementById("video");



        var socket = io();



        function logger(msg)

        {

        $("#logger").text(msg);

        }



        function loadCam(stream)

        {

        video.src = window.URL.createObjectURL(stream);

        logger('Camera connected [OK]');

        }



        function loadFail()

        {

        logger('Error! Camera not connected');

        }



        function viewVideo()

        {

        context.drawImage(video,0,0,context.width,context.height);

        socket.emit('stream',canvas.toDataURL('image/webp'));

        }



        $(function(){

        navigator.getUserMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msgGetUserMedia);

        if(navigator.getUserMedia){

        navigator.getUserMedia({video: true},loadCam,loadFail);

        }else if(navigator.webkitGetUserMedia){

        navigator.webkitGetUserMedia({video: true},loadCam,loadFail);

        }else if(navigator.mozGetUserMedia){

        navigator.mozGetUserMedia({video: true},loadCam,loadFail);

        }else if(navigator.msgGetUserMedia){

        navigator.msgGetUserMedia({video: true},loadCam,loadFail);

        }



        setInterval(function(){

        viewVideo(video,context);

        }, 70);

        });

</script>

</body>

</html>

dan untuk isi visualizar.html masukan kode berikut:
<!DOCTYPE html>

<html>

<head>

<title>Visualizar Video</title>

<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.2.min.js"></script>

<script type="text/javascript" src="/socket.io/socket.io.js"></script>

</head>

<body>

<img id="play" width="100%">

<div id="logger"></div>



<script type="text/javascript">

        var socket = io();

        socket.on('stream', function(image){

        var img = document.getElementById("play");

        img.src = image;

        $("#logger").text(image);

        });

</script>

</body>

</html>


selanjutnya jalankan aplikasi anda dengan perintah node app.js, akan ada tulisan server dijalankan pada port 3000. selanjunya buka localhost:3000 jika webcam nya tampil di browser seperti pada gambar di bawah berarti anda telah berhasil,


 selanjunya kode ini bisa anda kembangkan untuk membuat aplikasi video call / confrence call. sekian tutorial kali ini semoga bermanfaat, jika artikel ini berguna silakan share ke teman anda, jika ada yang error bisa di tanyakan pada komentar dibawah

Membuat Desain ListView to GridView di Android Studio

Selamat datang di Juanas Smith Shared kali ini admin akan membagikan cara membuat desain listview menjadi gridview, dari gridview ke listview di android studio, artikel ini ditujukan bagi anda yang sedang belajar pemrograman android pemula hingga mengengah



Langkah Pertama buatlah dua viewstub di activity main
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
   
xmlns:app="http://schemas.android.com/apk/res-auto"
   
xmlns:tools="http://schemas.android.com/tools"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
android:orientation="vertical">

    <ViewStub
       
android:id="@+id/stub_list"
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:layout_marginTop="10dp"
       
android:inflatedId="@+id/showLayout"
       
android:layout="@layout/my_listview" />

    <ViewStub
       
android:id="@+id/stub_grid"
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
        
android:layout_marginTop="10dp"
       
android:inflatedId="@+id/showLayout"
       
android:layout="@layout/my_gridview" />

Selanjutnya buat grid_item untuk layout gridviewnya
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    android:orientation="vertical"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:paddingTop="10dp"

    android:paddingBottom="10dp"

    android:paddingLeft="10dp"

    android:paddingRight="10dp"

    android:background="#fff">



    <ImageView

        android:id="@+id/ImageView"

        android:layout_width="80dp"

        android:layout_height="80dp"

        app:srcCompat="@mipmap/ic_launcher_round"

        android:layout_gravity="center"/>



    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/txtTitle"

        android:textStyle="bold"

        android:layout_below="@+id/ImageView"

        android:text="Title"

        android:textAppearance="?android:attr/textAppearanceMedium"

        android:layout_gravity="center"/>



    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/txtDescription"

        android:textStyle="bold"

        android:text="Description"

        android:textAppearance="?android:attr/textAppearanceSmall"

        android:layout_below="@+id/txtTitle"

        android:layout_toRightOf="@+id/ImageView"

        android:layout_gravity="center"/>



</LinearLayout>

jika tadi membuat grid_item sekarang buatlah list_item untuk layout list nya
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    xmlns:id="http://schemas.android.com/tools">



    <ImageView

        android:id="@+id/ImageView"

        android:layout_width="80dp"

        android:layout_height="80dp"

        app:srcCompat="@mipmap/ic_launcher_round" />



    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/txtTitle"

        android:textStyle="bold"

        android:text="Title"

        android:textAppearance="?android:attr/textAppearanceMedium"

        android:layout_toRightOf="@+id/ImageView"

        android:layout_marginTop="15dp"

        android:layout_marginLeft="20dp"/>



    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/txtDescription"

        android:textStyle="bold"

        android:text="Description"

        android:textAppearance="?android:attr/textAppearanceSmall"

        android:layout_below="@+id/txtTitle"

        android:layout_toRightOf="@+id/ImageView"

        android:layout_marginTop="10dp"

        android:layout_marginLeft="20dp"/>

</RelativeLayout>

Langkah berikutnya buat layout lagi dengan nama my_gridview.xml untuk menampung gridviewnya
<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:background="#d1d1d1">



    

    <GridView

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:id="@+id/mygridView"

        android:paddingTop="0dp"

        android:paddingBottom="15dp"

        android:columnWidth="100dp"

        android:gravity="center|bottom"

        android:horizontalSpacing="10dp"

        android:layout_marginLeft="0dp"

        android:layout_marginRight="0dp"

        android:numColumns="3"

        android:stretchMode="spacingWidth"

        android:verticalSpacing="20dp"

        android:dividerHeight="10dp" />

</FrameLayout>

Sekarang buat my_listview.xml untuk menampung listview nya
<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent" android:layout_height="match_parent"

    android:background="#d1d1d1">



    <ListView

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:id="@+id/myListView"

        android:cacheColorHint="#000"

        android:paddingTop="10dp"

        android:dividerHeight="10dp"

        android:divider="#ffffff"

        android:layout_marginLeft="0dp"

        android:layout_marginRight="0dp" />



</FrameLayout>

Kemudian buat class product di java
package giviews.id.listview2gridview;



/**

 * Created by asus on 09/05/2017.

 */



public class Product {

    private int imageId;

    private String title, description;



    public Product(int imageId, String title, String description) {

        this.imageId = imageId;

        this.title = title;

        this.description = description;

    }



    public int getImageId() {

        return imageId;

    }



    public void setImageId(int imageId) {

        this.imageId = imageId;

    }



    public String getTitle() {

        return title;

    }



    public void setTitle(String title) {

        this.title = title;

    }



    public String getDescription() {

        return description;

    }



    public void setDescription(String description) {

        this.description = description;

    }

}

Kemudian buat GridViewAdapter di java
package giviews.id.listview2gridview;



import android.content.Context;

import android.support.annotation.LayoutRes;

import android.support.annotation.NonNull;

import android.support.annotation.Nullable;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.ArrayAdapter;

import android.widget.ImageView;

import android.widget.TextView;



import java.util.List;



/**

 * Created by asus on 09/05/2017.

 */



public class GridViewAdapter extends ArrayAdapter<Product> {



    public GridViewAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull List<Product> objects) {

        super(context, resource, objects);

    }



    @NonNull

    @Override

    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        View v = convertView;



        if (null == v) {

            LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            v = inflater.inflate(R.layout.grid_item, null);

        }

        Product product = getItem(position);

        ImageView img = (ImageView) v.findViewById(R.id.ImageView);

        TextView txtTitle = (TextView) v.findViewById(R.id.txtTitle);

        TextView txtDescription = (TextView) v.findViewById(R.id.txtDescription);



        img.setImageResource(product.getImageId());

        txtTitle.setText(product.getTitle());

        txtDescription.setText(product.getDescription());



        return v;

    }

}

dan sekarang ListViewAdapter
package giviews.id.listview2gridview;



import android.content.Context;

import android.support.annotation.LayoutRes;

import android.support.annotation.NonNull;

import android.support.annotation.Nullable;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.ArrayAdapter;

import android.widget.ImageView;

import android.widget.TextView;



import java.util.List;



/**

 * Created by asus on 09/05/2017.

 */



public class ListViewAdapter extends ArrayAdapter<Product> {



    public ListViewAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull List<Product> objects) {

        super(context, resource, objects);

    }



    @NonNull

    @Override

    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        View v = convertView;



        if (null == v) {

            LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            v = inflater.inflate(R.layout.list_item, null);

        }

        Product product = getItem(position);

        ImageView img = (ImageView) v.findViewById(R.id.ImageView);

        TextView txtTitle = (TextView) v.findViewById(R.id.txtTitle);

        TextView txtDescription = (TextView) v.findViewById(R.id.txtDescription);



        img.setImageResource(product.getImageId());

        txtTitle.setText(product.getTitle());

        txtDescription.setText(product.getDescription());



        return v;

    }

}

Kemudian buat menu dengan nama main.xml untuk menempatkan tombol switch view dari gridview ke list view
<?xml version="1.0" encoding="utf-8"?>

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/item_menu_1" android:title="Swith View"></item>

</menu>

Terakhir sesuaikan isi file MainActivity.java seperti dibawah
package giviews.id.listview2gridview;



import android.content.SharedPreferences;

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.view.ViewStub;

import android.widget.AdapterView;

import android.widget.GridView;

import android.widget.ListView;

import android.widget.Toast;



import java.util.ArrayList;

import java.util.List;



public class MainActivity extends AppCompatActivity {



    private ViewStub stubGrid, stubList;

    private ListView listView;

    private GridView gridView;

    private ListViewAdapter listViewAdapter;

    private GridViewAdapter gridViewAdapter;

    private List<Product> productList;

    private int currentViewMode = 0;



    static final int VIEW_MODE_LISTVIEW = 0;

    static final int VIEW_MODE_GRIDVIEW = 1;







    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);



        stubList = (ViewStub) findViewById(R.id.stub_list);

        stubGrid = (ViewStub) findViewById(R.id.stub_grid);



        //inflate ViewStube before get view



        stubList.inflate();

        stubGrid.inflate();



        listView = (ListView) findViewById(R.id.myListView);

        gridView = (GridView) findViewById(R.id.mygridView);



        //get list of product

        getProductList();



        //get current view in share references

        SharedPreferences sharedPreferences = getSharedPreferences("View Mode", MODE_PRIVATE);

        currentViewMode = sharedPreferences.getInt("currentViewMode", VIEW_MODE_LISTVIEW); //default view is listview

        //register item click

        listView.setOnItemClickListener(onItemClick);

        gridView.setOnItemClickListener(onItemClick);



        switchView();



    }



    private void switchView() {

        if(VIEW_MODE_LISTVIEW == currentViewMode) {

            // display listview

            stubList.setVisibility(View.VISIBLE);

            // hide gridview

            stubGrid.setVisibility(View.GONE);

        }else{

            // hide listview

            stubList.setVisibility(View.GONE);

            // display gridview

            stubGrid.setVisibility(View.VISIBLE);

        }

        setAdapters();

    }



    private void setAdapters() {

        if (VIEW_MODE_LISTVIEW == currentViewMode) {

            listViewAdapter = new ListViewAdapter(this, R.layout.list_item, productList);

            listView.setAdapter(listViewAdapter);

        }else{

            gridViewAdapter = new GridViewAdapter(this, R.layout.grid_item, productList);

            gridView.setAdapter(gridViewAdapter);

        }

    }



    public List<Product> getProductList() {

        // pseudo code to get product, replace your code to get real product here

        productList = new ArrayList<>();

        productList.add(new Product(R.mipmap.ic_launcher_round, "Title 1", "This is description 1"));

        productList.add(new Product(R.mipmap.ic_launcher_round, "Title 2", "This is description 2"));

        productList.add(new Product(R.mipmap.ic_launcher_round, "Title 3", "This is description 3"));

        productList.add(new Product(R.mipmap.ic_launcher_round, "Title 4", "This is description 4"));

        productList.add(new Product(R.mipmap.ic_launcher_round, "Title 5", "This is description 5"));

        productList.add(new Product(R.mipmap.ic_launcher_round, "Title 6", "This is description 6"));

        productList.add(new Product(R.mipmap.ic_launcher_round, "Title 7", "This is description 7"));

        productList.add(new Product(R.mipmap.ic_launcher_round, "Title 8", "This is description 8"));

        productList.add(new Product(R.mipmap.ic_launcher_round, "Title 9", "This is description 9"));

        productList.add(new Product(R.mipmap.ic_launcher_round, "Title 10", "This is description 10"));

        return productList;

    }



    AdapterView.OnItemClickListener onItemClick = new AdapterView.OnItemClickListener() {

        @Override

        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            // Do anything when user click to item

            Toast.makeText(getApplicationContext(),productList.get(position).getTitle() +" - " + productList.get(position).getDescription(), Toast.LENGTH_SHORT).show();

        }

    };



    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.main, menu);

        return super.onCreateOptionsMenu(menu);

    }



    @Override

    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {

            case R.id.item_menu_1:

                if (VIEW_MODE_LISTVIEW == currentViewMode) {

                    currentViewMode = VIEW_MODE_GRIDVIEW;

                }else{

                    currentViewMode = VIEW_MODE_LISTVIEW;

                }

                //Swith view

                switchView();

                //save view mode is share reference

                SharedPreferences sharedPreferences = getSharedPreferences("ViewMode", MODE_PRIVATE);

                SharedPreferences.Editor editor = sharedPreferences.edit();

                editor.putInt("currentViewMode", currentViewMode);

                editor.commit();



                break;

        }

        return true;

    }

}


Silakan jalankan aplikasi anda, jika da yang error silakan ditanyakan di kolom komentar dibawah. jika artikel ini bermanfaat silakan di share ke teman anda. terimakasih sudah berkunjung ke blog kami.

Membuat ImageSlider dengan Android Studio



Pertama Siapkan tiga buah gambar atau lebih, untuk gambar slidernya.

kedua buat ViewPager
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
   
xmlns:tools="http://schemas.android.com/tools"
   
android:id="@+id/activity_main"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
tools:context="id.giviews.imageslider.MainActivity">

    <android.support.v4.view.ViewPager
       
android:id="@+id/viewPager"
       
android:layout_width="match_parent"
       
android:layout_height="150dp"/>

</RelativeLayout>

ketiga bikin layout baru dengan nama custom_layout, didalamnya tambahkan imageview untuk menampung gambar slidernya nanti.
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical" android:layout_width="match_parent"

    android:layout_height="match_parent">



    <ImageView

        android:id="@+id/imageView"

        android:layout_width="match_parent"

        android:layout_height="match_parent" />



</LinearLayout>

keempat buat class baru viewPagerAdapter di java
package id.giviews.imageslider;



import android.content.Context;

import android.support.v4.view.LayoutInflaterCompat;

import android.support.v4.view.PagerAdapter;

import android.support.v4.view.ViewPager;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.ImageView;



/**

 * Created by asus on 18/07/2017.

 */



public class ViewPagerAdapter extends PagerAdapter{



    private Context context;

    private LayoutInflater layoutInflater;

    private Integer[] images = {R.drawable.slide1, R.drawable.slide2, R.drawable.slide3};



    public ViewPagerAdapter(Context context) {

        this.context = context;

    }



    @Override

    public int getCount() {

        return images.length;

    }



    @Override

    public boolean isViewFromObject(View view, Object object) {

        return view == object;

    }



    @Override

    public Object instantiateItem(ViewGroup container, int position) {

        layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View view = layoutInflater.inflate(R.layout.custom_layout, null);

        ImageView imageView = (ImageView) view.findViewById(R.id.imageView);

        imageView.setImageResource(images[position]);



        ViewPager vp = (ViewPager) container;

        vp.addView(view, 0);

        return view;

    }



    @Override

    public void destroyItem(ViewGroup container, int position, Object object) {



        ViewPager vp = (ViewPager) container;

        View view = (View) object;

        vp.removeView(view);

    }

}

kelima ubah script MainActivity seperti berikut
package id.giviews.imageslider;



import android.support.v4.view.ViewPager;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;



import java.util.Timer;

import java.util.TimerTask;



public class MainActivity extends AppCompatActivity {



    ViewPager viewPager;



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);



        viewPager = (ViewPager) findViewById(R.id.viewPager);

        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(this);

        viewPager.setAdapter(viewPagerAdapter);



        Timer timer = new Timer();

        timer.scheduleAtFixedRate(new MyTimerTask(), 2000, 4000);

    }



    public class MyTimerTask extends TimerTask{

        @Override

        public void run() {

            MainActivity.this.runOnUiThread(new Runnable() {

                @Override

                public void run() {

                    if (viewPager.getCurrentItem() == 0) {

                        viewPager.setCurrentItem(1);

                    }else if (viewPager.getCurrentItem() == 1) {

                        viewPager.setCurrentItem(2);

                    }else {

                        viewPager.setCurrentItem(0);

                    }

                }

            });

        }

    }

}


Selanjutnya jalankan aplikasinya jika slidernya nampil berarti aplikasi anda telah berhasil, jika ada yang error silakan ditanyakan pada kolom komentar dibawah. jika artikel ini bermanfaat silakan share ke teman anda. terimakasih sudah berkunjung ke blog kami.