在.apk中包含.mp3文件

时间:2016-01-19 11:03:19

标签: android media-player

我目前正在开发Media Player。除了我在android模拟器外部存储器中有.mp3文件外,所有操作都已完成。我想知道的是,如何将所有这些.mp3文件包含在.apk中,这样当我在手机上安装应用程序时,文件会自动在设备的内部或外部存储上传输。 我已经解决了这个问题,但无法在任何地方找到最佳答案。

请帮帮我!

这是我的代码

VoiceService.java

package com.example.soundplayer;

import android.app.Service;
import java.util.ArrayList;
import android.content.ContentUris;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.PowerManager;
import android.util.Log;
import android.content.Intent;
import android.os.IBinder;
import java.util.Random;
import android.app.Notification;
import android.app.PendingIntent;
import com.example.soundplayer.Voice;

public class VoiceService extends Service implements
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
MediaPlayer.OnCompletionListener{

    //media player
    private MediaPlayer player;
    //song list
    private ArrayList<Voice> songs;
    //current position
    private int songPosn;

    private boolean shuffle=false;

    private Random rand;

    private String songTitle;

    private static final int NOTIFY_ID=1;

    private final IBinder musicBind = new MusicBinder();

    public void onCreate()
    {
        //create the service
        super.onCreate();
        //initialize position
        songPosn=0;
        //create player
        player = new MediaPlayer();

        initMusicPlayer();

        rand=new Random();


    }
    public void setShuffle(){
          if(shuffle) shuffle=false;
          else shuffle=true;
        }

    public void initMusicPlayer()
    {
        player.setWakeMode(getApplicationContext(),
                  PowerManager.PARTIAL_WAKE_LOCK);
                player.setAudioStreamType(AudioManager.STREAM_MUSIC);

                player.setOnPreparedListener(this);
                player.setOnCompletionListener(this);
                player.setOnErrorListener(this);

    }

    public void setList(ArrayList<Voice> theSongs){
          songs=theSongs;
        }

    public class MusicBinder extends Binder 
    {
          VoiceService getService() {
            return VoiceService.this;
    }
        }


    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
         return musicBind;
    }
    public boolean onUnbind(Intent intent){
          player.stop();
          player.release();
          return false;
        }

    public void playSong(){
          //play a song

        player.reset();
        //get song
        Voice playSong = songs.get(songPosn);
        songTitle=playSong.getTitle();
        //get id
        long currSong = playSong.getID();
        //set uri
        Uri trackUri = ContentUris.withAppendedId(
          android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
          currSong);
        try
        {
              player.setDataSource(getApplicationContext(), trackUri);
        }
            catch(Exception e)
            {
              Log.e("MUSIC SERVICE", "Error setting data source", e);
            }
            player.prepareAsync();
        }

    public void setSong(int songIndex){
          songPosn=songIndex;
        }

    @Override
    public void onCompletion(MediaPlayer mp) {
        // TODO Auto-generated method stub
        if(player.getCurrentPosition()>=0){
            mp.reset();
            playNext();
          }

    }
    @Override
    public void onDestroy() {
      stopForeground(true);
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        // TODO Auto-generated method stub
        mp.reset();
          return false;
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mp.start();

        Intent notIntent = new Intent(this, MainActivity.class);
        notIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendInt = PendingIntent.getActivity(this, 0,
          notIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Notification.Builder builder = new Notification.Builder(this);

        builder.setContentIntent(pendInt)
          .setSmallIcon(R.drawable.play)
          .setTicker(songTitle)
          .setOngoing(true)
          .setContentTitle("Playing")
          .setContentText(songTitle);
        Notification not = builder.build();

        startForeground(NOTIFY_ID, not);

    }

    public int getPosn(){
          return player.getCurrentPosition();
        }

        public int getDur(){
          return player.getDuration();
        }

        public boolean isPng(){
          return player.isPlaying();
        }

        public void pausePlayer(){
          player.pause();
        }

        public void seek(int posn){
          player.seekTo(posn);
        }

        public void go(){
          player.start();
        }

        public void playPrev(){
              songPosn--;
              if(songPosn>=0) songPosn=songs.size()-1;
              playSong();
            }

        public void playNext(){
            if(shuffle){
                int newSong = songPosn;
                while(newSong>=songPosn){
                  newSong=rand.nextInt(songs.size());
                }
                songPosn=newSong;
              }
              else{
                songPosn++;
                if(songPosn==songs.size()) songPosn=0;
              }
              playSong();
            }
}

MainActivity.java

package com.example.soundplayer;

import android.app.Activity;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import android.widget.MediaController.MediaPlayerControl;

import com.example.soundplayer.VoiceService.MusicBinder;

import android.net.Uri;
import android.content.ContentResolver;
import android.database.Cursor;
import android.widget.ListView;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.os.IBinder;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.view.MenuItem;
import android.view.View;

public class MainActivity extends Activity implements MediaPlayerControl{

    private ArrayList<Voice> songList;
    private ListView songView;
    private VoiceService musicSrv;
    private Intent playIntent;
    private boolean musicBound=false;
    private VoiceController controller;
    private boolean paused=false, playbackPaused=false;



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

        songView = (ListView)findViewById(R.id.song_list);

        songList = new ArrayList<Voice>();

        getSongList();

        Collections.sort(songList, new Comparator<Voice>(){
              public int compare(Voice a, Voice b){
                return a.getTitle().compareTo(b.getTitle());
              }
              });

        SongAdapter songAdt = new SongAdapter(this, songList);
        songView.setAdapter(songAdt);

        setController();


        }

    private void setController(){
          //set the controller up
        controller = new VoiceController(this);
        controller.setPrevNextListeners(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                playNext();
              }
            }, new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                playPrev();
              }
            });
        controller.setMediaPlayer(this);
        controller.setAnchorView(findViewById(R.id.song_list));
        controller.setEnabled(true);

        }

    private void playNext(){
        musicSrv.playNext();
          if(playbackPaused){
            setController();
            playbackPaused=false;
          }
          controller.show(0);
        }

        //play previous
        private void playPrev(){
            musicSrv.playPrev();
              if(playbackPaused){
                setController();
                playbackPaused=false;
              }
              controller.show(0);
        }
        @Override
        protected void onPause(){
          super.onPause();
          paused=true;
        }

        @Override
        protected void onResume(){
          super.onResume();
          if(paused){
            setController();
            paused=false;
          }
        }
        @Override
        protected void onStop() {
          controller.hide();
          super.onStop();
        }


    //connect to the service
    private ServiceConnection musicConnection = new ServiceConnection(){

      @Override
      public void onServiceConnected(ComponentName name, IBinder service) {
        MusicBinder binder = (MusicBinder)service;
        //get service
        musicSrv = binder.getService();
        //pass list
        musicSrv.setList(songList);
        musicBound = true;
      }



      @Override
      public void onServiceDisconnected(ComponentName name) {
        musicBound = false;
      }



    };

    @Override
    public void onBackPressed() {
    moveTaskToBack(true);
    }

    public void songPicked(View view){
         musicSrv.setSong(Integer.parseInt(view.getTag().toString()));
          musicSrv.playSong();
          if(playbackPaused){
            setController();
            playbackPaused=false;
          }
          controller.show(0);
        }

    @Override
    protected void onStart() {
      super.onStart();
      if(playIntent==null){
        playIntent = new Intent(this, VoiceService.class);
        bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
        startService(playIntent);
      }
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.action_shuffle:
              musicSrv.setShuffle();
              break;
        case R.id.action_end:
          stopService(playIntent);
          musicSrv=null;
          System.exit(0);
          break;

        }
        return super.onOptionsItemSelected(item);
        }

    @Override
    protected void onDestroy() {
      stopService(playIntent);
      musicSrv=null;
      super.onDestroy();
    }

    public void getSongList() {

        ContentResolver musicResolver = getContentResolver();
        Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);


        if(musicCursor!=null && musicCursor.moveToFirst()){
              //get columns
              int titleColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media.TITLE);
              int idColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media._ID);
              int artistColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media.ARTIST);
              //add songs to list
              do {
                long thisId = musicCursor.getLong(idColumn);
                String thisTitle = musicCursor.getString(titleColumn);
                String thisArtist = musicCursor.getString(artistColumn);
                songList.add(new Voice(thisId, thisTitle, thisArtist));
              }
              while (musicCursor.moveToNext());
            }

        }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void start() {
        // TODO Auto-generated method stub
        musicSrv.go();
    }

    @Override
    public void pause() {
        // TODO Auto-generated method stub
         playbackPaused=true;
          musicSrv.pausePlayer();
    }

    @Override
    public int getDuration() {
        if(musicSrv!=null && musicBound && musicSrv.isPng())
            return musicSrv.getDur();
          else return 0;
    }

    @Override
    public int getCurrentPosition() {
        if(musicSrv!=null && musicBound && musicSrv.isPng())

            return musicSrv.getPosn();
          else return 0;
    }

    @Override
    public void seekTo(int pos) {
        // TODO Auto-generated method stub
        musicSrv.seek(pos);
    }

    @Override
    public boolean isPlaying() {
        if(musicSrv!=null && musicBound)
            return musicSrv.isPng();
          return false;
    }

    @Override
    public int getBufferPercentage() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public boolean canPause() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public boolean canSeekBackward() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public boolean canSeekForward() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public int getAudioSessionId() {
        // TODO Auto-generated method stub
        return 0;
    }



}

1 个答案:

答案 0 :(得分:0)

只需将.mp3文件复制到res / raw文件夹中即可读取

 mp = MediaPlayer.create(context, R.raw.fileName);