Showing posts with label get Assets. Show all posts
Showing posts with label get Assets. Show all posts

Wednesday, November 18, 2015

Play Audio From Asset Directory in Android



Description:

Many applications need small audio file integrated in app only. For Example, Simple 2D bomb blast game, it requires bomb blast sound effect. It is necessary for developer to add sound effect in this type of app.Another reason is make application more attractive. Sound effect shapes your app more attractive and look different than other apps. Here is the code which help you to play audio file from asset file.

We have created this app with very easy way, you can use the same file for different application with copy/paste file.

First, Create AudioPlayer.java file:

AudioPlayer.java


import java.io.IOException;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;

public class AudioPlayer {

String fileName;
   Context contex;
   MediaPlayer mp;

   //Constructor
   public AudioPlayer(String name, Context context) {
       fileName = name;
       contex = context;
      // playAudio();
   }

   //Play Audio
   public void playAudio() {
       mp = new MediaPlayer();
       try {
           AssetFileDescriptor descriptor = contex.getAssets()
                   .openFd(fileName);
           mp.setDataSource(descriptor.getFileDescriptor(),
                   descriptor.getStartOffset(), descriptor.getLength());
           descriptor.close();
           mp.prepare();
           mp.setLooping(true);
           mp.start();
           mp.setVolume(3, 3);

       } catch (IllegalArgumentException e) {
           e.printStackTrace();
       } catch (IllegalStateException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       }
   }
   //Stop Audio
   public void stop() {
    if(mp != null){
       mp.stop();
    }
   }
   
   //Pause Audio
   public void pause(){
    if(mp != null){
    mp.pause();
    }
   }
   
}

Now, Add 3 Buttons Play,Pause and Stop in activity_main.xml file.

activity_main.xml


<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"
    tools:context="${relativePackage}.${activityClass}" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:orientation="vertical" >

        <Button
            android:id="@+id/buttonPlay"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Play"
            android:drawableLeft="@android:drawable/ic_media_play" />

        <Button
            android:id="@+id/buttonPause"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Pause"
            android:drawableLeft="@android:drawable/ic_media_pause" />

        <Button
            android:id="@+id/buttonStop"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Stop"
            android:drawableLeft="@drawable/stop" />

    </LinearLayout>

</RelativeLayout>


Copy below code in MainActivity.java file

MainActivity.java


import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

Button btnPlay, btnPause, btnStop;
AudioPlayer audioPlayer;
Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btnPlay = (Button) findViewById(R.id.buttonPlay);
btnPause = (Button) findViewById(R.id.buttonPause);
btnStop = (Button) findViewById(R.id.buttonStop);

context = getApplicationContext();
audioPlayer = new AudioPlayer("audio_sample.mp3", context);

btnPlay.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
audioPlayer.playAudio();
btnPlay.setEnabled(false);
}
});

btnPause.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
btnPlay.setEnabled(true);
if (audioPlayer != null) {
audioPlayer.pause();
}
}
});

btnStop.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
btnPlay.setEnabled(true);
if (audioPlayer != null) {
audioPlayer.stop();
}
}
});
}
}


Download Full Source Code: GitHub



Thursday, August 15, 2013

Install APK from assets in android application

Yes, We can install another application from installed application !!!
Sometimes our application is dependent in other application,at that time you need to store application APK file into assets folder and just write code for it. Thats it.

The main benefit is there is no requirement of internet to download application which you need to use in your application.The question arrives in your mind is, how it is possible?
Here is full description for that.



  • Create one folder called rar in assets folder.
  • Copy another application APK and paste it into this rar folder.   
  • Create one button or other component which is used to install APK file.
  • For Example, I choose button for install APK file.
  • Now add below code carefully in MainActivity.java


MainActivity.java




public class MainActivity extends Activity {


Button b;
String rarPath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

b = (Button) findViewById(R.id.button1);

b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {

rarPath = "rar/sms.apk";
AssetManager assetManager = getAssets();

InputStream in = null;
OutputStream out = null;
try {
   in = assetManager.open(rarPath);
   out = new FileOutputStream("/sdcard/myapk.apk");

   byte[] buffer = new byte[1024];

   int read;
   while((read = in.read(buffer)) != -1) {

       out.write(buffer, 0, read);

   }

   in.close();
   in = null;

   out.flush();
   out.close();
   out = null;

   Intent intent = new Intent(Intent.ACTION_VIEW);

   intent.setDataAndType(Uri.fromFile(new File("/sdcard/myapk.apk")),
       "application/vnd.android.package-archive");

   startActivity(intent);

} catch(Exception e) { e.printStackTrace();
Toast.makeText(getApplicationContext(),"Error !",Toast.LENGTH_LONG).show();}
}
});
}
}

Done. Now run the project.

NOTE: If APK file size is more than 2Mb, it will take some time to copy and install it.
Use Thread or AsyncTask for heavy APK file.