Minggu, 10 Mei 2015

Materi Pertemuan 13 (Multimedia 2)

KAMERA
Layout
 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/camera"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="AMBIL FOTO" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/ic_launcher" />

</LinearLayout>

Java
import java.io.File;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class KameraActivity extends Activity {
    private static int TAKE_PICTURE = 1;
    private Uri tmpgambar;   
    private Button tmbkamera;
    private String strFile;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.kamera);
        tmbkamera = (Button)findViewById(R.id.camera);       
        tmbkamera.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                buatFolder();
                ambilFoto(v);
            }
        });
    }
   
    private void ambilFoto(View v){       
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        strFile = Environment.getExternalStorageDirectory()+ "/ContohDataMultimedia/fileFoto.jpg";
        File foto = new File(strFile);
        tmpgambar = Uri.fromFile(foto);       
        intent.putExtra(MediaStore.EXTRA_OUTPUT, tmpgambar);
        startActivityForResult(intent, TAKE_PICTURE);       
    }
   
    private void buatFolder(){
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
        File file = new File(path+"/ContohDataMultimedia/");
        if(!file.exists()){
            file.mkdir();
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            try { // Kalau2 fotonya gak ke save
                Bitmap bitmap = BitmapFactory.decodeFile(strFile);
                ((ImageView)findViewById(R.id.imageView1)).setImageBitmap(bitmap);   
            } catch (Exception e) {
                e.printStackTrace();
            }               
        }       
    }
}

VIDEO
Create

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/video"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Buat Video" /> 

</LinearLayout>

import java.io.File;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class BuatVideoActivity extends Activity {
    private static int TAKE_PICTURE = 1;
    private Uri tmpvideo;   
    private Button tmbvideo;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buat_video);
        tmbvideo = (Button)findViewById(R.id.video);       
        tmbvideo.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                buatFolder();
                ambilVideo(v);
            }
        });
    }
   
    private void ambilVideo(View v){       
        Intent intent = new Intent("android.media.action.VIDEO_CAPTURE");
        File video = new File(Environment.getExternalStorageDirectory()+ "/ContohDataMultimedia/fileVideo.3gp");       
        tmpvideo = Uri.fromFile(video);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, tmpvideo);
        startActivityForResult(intent, TAKE_PICTURE);       
    }
   
    private void buatFolder(){
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
        File file = new File(path+"/ContohDataMultimedia/");
        if(!file.exists()){
            file.mkdir();
        }
    }
}

List
 <?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="15dp"
    android:textSize="25dp" >
</TextView>

import java.io.File;
import java.io.FilenameFilter;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class DaftarVideoActivity extends ListActivity {
    ArrayAdapter<String>adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);       
        adapter = new ArrayAdapter<String>(this, R.layout.daftarvideo, getVideo());
        setListAdapter(adapter);
        ListView listView = getListView();
        listView.setOnItemClickListener(new OnItemClickListener(){
            public void onItemClick(AdapterView<?> parent, View arg1, int position, long arg3) {
                String tempat = parent.getItemAtPosition(position).toString();
                Intent intent = new Intent();
                intent.setClass(getApplicationContext(), VideoActivity.class);
                intent.putExtra("video", tempat);
                startActivity(intent);
            }
           
        });
    }
   
    static String [] nmFile=null;
    public static String [] getVideo(){       
        File video = new File(Environment.getExternalStorageDirectory()+"/ContohDataMultimedia/");       
        File [] daftarVideo =  video.listFiles(new FilenameFilter(){
            public boolean accept(File dir, String name) {
                return (((name.endsWith(".mp3"))||(name.endsWith(".MP3"))||(name.endsWith(".mp4"))||
                        (name.endsWith(".MP4"))||(name.endsWith(".avi"))||(name.endsWith(".AVI"))||
                        (name.endsWith(".3gp"))||(name.endsWith(".mkv"))||(name.endsWith(".MKV"))||
                        (name.endsWith(".wmv"))||(name.endsWith(".WMV"))||(name.endsWith(".flv"))||
                        (name.endsWith(".FLV"))));
            }
        });
        nmFile = new String[daftarVideo.length];
        for(int i=0; i<daftarVideo.length; i++){
            nmFile[i] = daftarVideo[i].getAbsolutePath();
        }
        return nmFile;
    }   

}

Play
<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="80dp"
    android:paddingRight="80dp"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <VideoView
        android:id="@+id/videoView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;

public class VideoActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.video);
        Bundle bundle = getIntent().getExtras();
        String tempat = bundle.getString("video");
        VideoView videoView = (VideoView)findViewById(R.id.videoView1);
        MediaController mediaController = new MediaController(this);
        mediaController.setAnchorView(videoView);
        Uri uri = Uri.parse(tempat);
        videoView.setVideoURI(uri);
        videoView.setMediaController(mediaController);
        videoView.start();
        videoView.requestFocus();
    }   

}


AUDIO
Layout
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".RecordActivity" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="..."
        android:textAppearance="?android:attr/textAppearanceLarge" />
    <Button
        android:id="@+id/button1"
        android:layout_width="200dp"
        android:layout_height="80dp"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:text="Mulai Rekam"
        android:textSize="30dp" />
    <Button
        android:id="@+id/button2"
        android:layout_width="200dp"
        android:layout_height="80dp"
        android:layout_alignLeft="@+id/button1"
        android:layout_alignRight="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="10dp"
        android:text="Stop Rekam"
        android:textSize="30dp"/>
    <Button
        android:id="@+id/button3"
        android:layout_width="200dp"
        android:layout_height="80dp"
        android:layout_alignLeft="@+id/button2"
        android:layout_alignRight="@+id/button2"
        android:layout_below="@+id/button2"
        android:layout_marginTop="10dp"
        android:text="Putar"
        android:textSize="30dp"/>
    <Button
        android:id="@+id/button4"
        android:layout_width="200dp"
        android:layout_height="80dp"
        android:layout_alignLeft="@+id/button3"
        android:layout_alignRight="@+id/button3"
        android:layout_below="@+id/button3"
        android:layout_marginTop="10dp"
        android:text="Stop"
        android:textSize="30dp"/>
</RelativeLayout>

Java
import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class RekamActivity extends Activity {
    private Button rekam, stopr, putar, stopp;
    private TextView txt;
    private MediaPlayer mp;
    private MediaRecorder mr;
    private String tempat;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rekam);
        tempat = Environment.getExternalStorageDirectory() + "/ContohDataMultimedia/fileRekam.3gpp";
        txt = (TextView)findViewById(R.id.textView1);
        rekam = (Button)findViewById(R.id.button1);
        rekam.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                buatFolder();
                startRekam();
                txt.setText("Sedang Merekam...");
                rekam.setEnabled(false);
                stopr.setEnabled(true);
                putar.setEnabled(false);
                stopp.setEnabled(false);
            }
        });
        stopr = (Button)findViewById(R.id.button2);
        stopr.setEnabled(false);
        stopr.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                stopRekam();
                txt.setText("");
                rekam.setEnabled(true);
                stopr.setEnabled(false);
                putar.setEnabled(true);
                stopp.setEnabled(false);
            }
        });
        putar = (Button)findViewById(R.id.button3);
        putar.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                startHasil();
                txt.setText("Sedang Memutar...");
                rekam.setEnabled(false);
                stopr.setEnabled(false);
                putar.setEnabled(false);
                stopp.setEnabled(true);
            }
        });
        stopp = (Button)findViewById(R.id.button4);
        stopp.setEnabled(false);
        stopp.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                stopHasil();
                txt.setText("");
                rekam.setEnabled(true);
                stopr.setEnabled(false);
                putar.setEnabled(true);
                stopp.setEnabled(false);
            }
        });
    }
   
    private void buatFolder(){
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
        File file = new File(path+"/ContohDataMultimedia/");
        if(!file.exists()){
            file.mkdir();
        }
    }
   
    public void startRekam(){
        if(mr != null){
            mr.release();
        }
        File fout = new File(tempat);
        if(fout != null){
            fout.delete();
        }
        mr = new MediaRecorder();
        mr.setAudioSource(MediaRecorder.AudioSource.MIC);
        mr.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mr.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        mr.setOutputFile(tempat);
        try {
            mr.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mr.start();
    }
    public void stopRekam(){
        if(mr != null){
            mr.stop();
            mr.release();
            mr = null;
        }
    }
    public void startHasil(){
        mp = new MediaPlayer();
        try {
            mp.setDataSource(tempat);
            mp.prepare();
            mp.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void stopHasil(){
        if(mp != null){
            if(mp.isPlaying())
                mp.stop();
            mp.release();
            mp = null;
        }
    }
   
}

FILE
Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="10dp" >

    <EditText
        android:id="@+id/editNama"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="Nama"
        />
    <TextView
            android:id="@+id/txtStatusGambar"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textColor="#fff"
            android:text="Gambar Belum Dipilih" >
    </TextView>
    <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_gravity="center_horizontal" >
    <Button
            android:id="@+id/btnChooseImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="Select Image" >
    </Button>
    <Button
            android:id="@+id/btnAddImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="Upload Image" >
    </Button>  
    </LinearLayout>
</LinearLayout>

Java
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class FileUploadActivity extends Activity implements OnClickListener{
    /** Called when the activity is first created. */
    Button upload,add;
    TextView status;
    EditText nama;
  
    //variable for upload data into http
    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    DataInputStream inputStream = null;
  
    Bitmap bm;

    static String pathToOurFile = "",format;
    String urlServer = "http://kelasandroid.net16.net/imageupload/upload.php";   
    String lineEnd = "\r\n",twoHyphens = "--",boundary =  "*****";
  
    private static final int SELECT_PICTURE = 0;

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1*1024*1024;
  
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_upload);
        upload=(Button)findViewById(R.id.btnChooseImage);
        upload.setOnClickListener(this);
        add=(Button)findViewById(R.id.btnAddImage);
        add.setOnClickListener(this);
        status=(TextView)findViewById(R.id.txtStatusGambar);
        nama=(EditText)findViewById(R.id.editNama);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.btnChooseImage:
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"),SELECT_PICTURE);
            break;
        case R.id.btnAddImage:
            try {
                bm = BitmapFactory.decodeFile(pathToOurFile);
                new UploadFile().execute("");               
                } catch (Exception e) {
                    Log.e(e.getClass().getName(), e.getMessage());
                }
            break;
        default:
            break;
        }
    }
  
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            status.setText(data.getData().toString());
            String[] projection = { MediaStore.Images.Media.DATA };          
            Cursor cursor = managedQuery(data.getData(), projection, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            String filePath = cursor.getString(column_index);
            //cursor.close();
            pathToOurFile=filePath;
            format = filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length());
        }      
    }  
   
    class UploadFile extends AsyncTask<String, String, String>{
        @Override
        protected String doInBackground(String... params) {
            try {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bm.compress(CompressFormat.JPEG, 75, bos);
                byte[] data = bos.toByteArray();
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost postRequest = new HttpPost(urlServer);
                ByteArrayBody bab = new ByteArrayBody(data, nama.getText().toString()+"."+format);
                MultipartEntity reqEntity = new MultipartEntity(
                        HttpMultipartMode.BROWSER_COMPATIBLE);
                reqEntity.addPart("uploaded", bab);
                reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf"));
                postRequest.setEntity(reqEntity);
                HttpResponse response = httpClient.execute(postRequest);
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        response.getEntity().getContent(), "UTF-8"));
                String sResponse;
                StringBuilder s = new StringBuilder();

                while ((sResponse = reader.readLine()) != null) {
                    s = s.append(sResponse);
                }               
                return "Success";               
            } catch (Exception e) {               
                e.printStackTrace();               
            }   
            return null;
        }
        @Override
        protected void onPostExecute(String result) {           
            super.onPostExecute(result);
            if("Success".equals(result)){
                Toast.makeText(FileUploadActivity.this, "Penambahan data berhasil", 1).show();
            }else{
                Toast.makeText(FileUploadActivity.this, "Penambahan data GAGAL", 1).show();
            }           
        }
    }   
  
}

Php
<?php
$target_path  = "./upload/";
$target_path = $target_path . basename( $_FILES['uploaded']['name']);
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target_path)) {
echo "The file ".  basename( $_FILES['uploaded']['name']).
" has been uploaded";
} else{
echo "Gagal Bung!";
}
?>

Download library untuk upload file
httpclient
httpmime

AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CAMERA" />

    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />

Tidak ada komentar:

Posting Komentar