欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

MediaPlayer播放音乐

程序员文章站 2022-05-28 10:26:02
...
MainActivity.java:
package com.sound.test;

import java.io.IOException;

import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
 private Button button_play;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        findViews();
        setListeners();
    }

    private void findViews() {
  // TODO Auto-generated method stub
     button_play=(Button) findViewById(R.id.button1);
 }

 private void setListeners() {
  // TODO Auto-generated method stub
  button_play.setOnClickListener(new OnClickListener() {   
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    //raw下播放音乐1
    //MediaPlayer.create(MainActivity.this, R.raw.a_place_nearby).start();
    try {
     //assets下播放音乐
     AssetFileDescriptor afd=getResources().getAssets().openFd("sound/a_place_nearby.mp3");

     MediaPlayer mediaPlayer=new MediaPlayer();
     mediaPlayer.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
     mediaPlayer.prepare();
     mediaPlayer.start();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  });
 }

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}