Android 播放音頻

例子1:

放置音頻資源文件android

 

 

 

右鍵src,new,Folder,Assets Folderide

而後將音頻文件複製到assets文件夾下函數

 

 

 

 界面上2個按鈕,對應點擊函數爲PlayMusic 和StopMusicui

點擊播放開始循環播放,this

public class LoginActivity extends AppCompatActivity {
    AssetManager am;
    MediaPlayer player;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_login);
        am=getAssets();
    }

    public void PlayMusic(View view) {
        try {
            player=new MediaPlayer();
            AssetFileDescriptor afd = am.openFd("WarningShort.mp3");
            player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    player.start();
                }
            });
            player.prepare();
            player.start();
        } catch (Exception e) {

        }


    }

    public void StopMusic(View view) {
        if (player != null) {
            player.stop();
        }
    }

}

額外:AssetManager可使用open方法返回InputStreamspa

另一種放置資源的方法code

 

 res,New,Android Resource Directorycomponent

類型和名稱都爲rawblog

複製黏貼mp3文件。ip

 

 

例子2 :在Service中播放音樂

 

新建MyService

public class MyService extends Service {
    public AssetFileDescriptor afdWarning;
    public AssetFileDescriptor afdSheduleDone;
    public static final String SERVICE_LOG = "SERVICE_LOG";
    public MediaPlayer player;

    public MyService() {
    }

    @Override
    public void onCreate() {

        try {
            afdSheduleDone = getAssets().openFd("sheduleDoneShort.mp3");
            afdWarning = getAssets().openFd("WarningShort.mp3");
            player = new MediaPlayer();
        } catch (Exception e) {
            Log.d(SERVICE_LOG, "open resource exception");
            e.printStackTrace();
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    //生成Notification,保證後臺音樂的播放
    public void startForeground() {
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, LoginActivity.class),PendingIntent.FLAG_CANCEL_CURRENT);
        Notification notification = new Notification.Builder(this)
                .setContentTitle("hello").setContentText("My Service Music")
                .setSmallIcon(R.mipmap.ic_launcher_round)
                .setContentIntent(pendingIntent)
                .build();
        startForeground(1,notification);
    }

    public class MyBinder extends Binder {
        public MyBinder() {
            startForeground();
        }

        public void PlayMusci(int i)
        {
            Log.d(SERVICE_LOG, "Well,In Service PlayMusic called with arg "+i);
            AssetFileDescriptor afd=null;
            if(player==null)
                return;
            if (i == 1) {
                afd=afdSheduleDone;
            } else if (i == 2) {
                afd = afdWarning;
            } else {
                return;
            }
            if (afd == null) {
                return;
            }
            player.reset();
            try {
                player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        player.start();
                    }
                });
                player.prepareAsync();
                player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mediaPlayer) {
                        player.start();
                    }
                });

            } catch (Exception e) {
                Log.d(SERVICE_LOG, "playmusic exception");
            }

        }
        public void StopMusic() {
            if (player == null) {
                return;
            }
            player.stop();
        }
    }
}

 

界面依然2個按鈕

 

 

Activity內容

public class LoginActivity extends AppCompatActivity {
    private MyService.MyBinder binder;
    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            binder=(MyService.MyBinder)iBinder;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_login);
        Intent intent = new Intent(LoginActivity.this, MyService.class);
        startService(new Intent(getBaseContext(),MyService.class));
        bindService(intent, connection, BIND_AUTO_CREATE);
    }

    public void PlayMusic(View view) {
        binder.PlayMusci(1);

    }

    public void StopMusic(View view) {
        binder.StopMusic();
    }


}

 例子3:Android8.0以後必須使用前臺Service的狀況

MusicService 中的starForeground修改以下

    public void startForeground() {
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class),PendingIntent.FLAG_CANCEL_CURRENT);
        Notification notification = new NotificationCompat.Builder(this,"foreground")
                .setContentTitle("hehe").setContentText("信息提示")
                .setSmallIcon(R.mipmap.ic_launcher_round)
                .setContentIntent(pendingIntent)
                .build();
        NotificationManager notificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel channel=null;
        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.O){
            channel = new NotificationChannel("foreground", "foregroundName", NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(channel);
        }
        startForeground(1,notification);
    }

 

啓動和綁定服務的代碼修改

    private void initMusicService() {
        Intent musicIntent = new Intent(MainActivity.this, MusicService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(new Intent(MainActivity.this,MusicService.class));
        }else {
            startService(new Intent(MainActivity.this,MusicService.class));
        }

        bindService(musicIntent, connection, BIND_AUTO_CREATE);
    }

加上權限

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
相關文章
相關標籤/搜索