Android开发音乐播放和调节大小声音代码

package com.ww.rr;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;

/**
 *
 * 2、Open Core 的具体功能

 1、多媒体文件的播放、下载,包括:3GPP,MPEG-4,AAC 和 MP3 containers。
 2、流媒体文件的下载、实时播放,包括:3GPP,HTTP 和 RTSP/RTP。
 3、动态视频和静态图像的编码、解码,例如:MPEG-4,H.263 和 AVC (H.264),JPEG。
 4、语音编码格式:MP3,AAC,AAC+。
 5、视频和图像格式:3GPP,MPEG-4 和 JPEG。
 6、视频会议:基于 H324-M 标准。
 * **/
public class AdjustVolumeActivity extends Activity implements View.OnClickListener {
    private Button play = null;
    private Button down = null;
    private Button up = null;

    private ProgressBar pb = null;
    private int maxVolume = 50; // 最大音量值
    private int curVolume = 20; // 当前音量值
    private int stepVolume = 0; // 每次调整的音量幅度

    private MediaPlayer mediaPlayer = null;// 播放器
    private AudioManager audioMgr = null; // Audio管理器,用了控制音量
    private AssetManager assetMgr = null; // 资源管理器

    private final String musicName = "hehe.mp3";



    private TextView nameTextView;
    private SeekBar seekBar;
    private ListView listView;
    private List, String>> data;
    private int current;
    private MediaPlayer player;
    private Handler handler = new Handler();
    private Button ppButton;
    private boolean isPause;
    private boolean isStartTrackingTouch;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_adjust_volume);
        // 初始化播放器、音量数据等相关工作
        initPlayWork();
        // 初始化视图
        initUI();




        nameTextView = (TextView) findViewById(R.id.name);
        seekBar = (SeekBar) findViewById(R.id.seekBar);
        listView = (ListView) findViewById(R.id.list);
        ppButton = (Button) findViewById(R.id.pp);

        //创建一个音乐播放器
        player = new MediaPlayer();

        //显示音乐播放列表
        generateListView();

        //进度条监听器
        seekBar.setOnSeekBarChangeListener(new MySeekBarListener());

        //播放器监听器
        player.setOnCompletionListener(new MyPlayerListener());

        //意图过滤器
        IntentFilter filter = new IntentFilter();

        //播出电话暂停音乐播放
        filter.addAction("Android.intent.action.NEW_OUTGOING_CALL");
        registerReceiver(new PhoneListener(), filter);


        try {
            //创建一个电话服务
            TelephonyManager manager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
            //监听电话状态,接电话时停止播放
            manager.listen(new MyPhoneStateListener(), PhoneStateListener.LISTEN_CALL_STATE);
        }catch (Exception e){
           // e.fillInStackTrace();
            Log.e("www",e.toString());
        }


    }

    /**
     * 初始化UI
     */
    private void initUI() {
       // play = (Button) findViewById(R.id.play);
        down = (Button) findViewById(R.id.down);
        up = (Button) findViewById(R.id.up);

      // play.setOnClickListener(this);
        down.setOnClickListener(this);
        up.setOnClickListener(this);
        // 设置进度条
        pb = (ProgressBar) findViewById(R.id.progress);
        pb.setMax(maxVolume);
        pb.setProgress(curVolume);
    }

    /**
     * 初始化播放器、音量数据等相关工作
     */
    private void initPlayWork() {
        audioMgr = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        // 获取最大音乐音量
        maxVolume = audioMgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        // 初始化音量大概为最大音量的1/2
        curVolume = maxVolume / 2;
        // 每次调整的音量大概为最大音量的1/6
        stepVolume = maxVolume / 6;

        mediaPlayer = new MediaPlayer();
        assetMgr = this.getAssets();
    }

    /**
     * 准备播放音乐
     *
     * @param
     */
    private void prepareAndPlay() {
        try {
            // 打开指定音乐文件
            AssetFileDescriptor afd = assetMgr.openFd(musicName);
            mediaPlayer.reset();
            // 使用MediaPlayer加载指定的声音文件。
            mediaPlayer.setDataSource(afd.getFileDescriptor(),
                    afd.getStartOffset(), afd.getLength());
            // 准备声音
            mediaPlayer.prepare();
            // 播放
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 调整音量
     */
    private void adjustVolume() {
        audioMgr.setStreamVolume(AudioManager.STREAM_MUSIC, curVolume,
                AudioManager.FLAG_PLAY_SOUND);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
//            case R.id.play://按下播放按钮
//                prepareAndPlay();
//                break;
            case R.id.up://按下增大音量按钮
                curVolume += stepVolume;
                if (curVolume >= maxVolume) {
                    curVolume = maxVolume;
                }
                pb.setProgress(curVolume);
                break;
            case R.id.down://按下减小音量按钮
                curVolume -= stepVolume;
                if (curVolume <= 0) {
                    curVolume = 0;
                }
                pb.setProgress(curVolume);
                break;
            default:
                break;
        }
        // 调整音量
        adjustVolume();
    }

    private final class MyPhoneStateListener extends PhoneStateListener {
        public void onCallStateChanged(int state, String incomingNumber) {
            pause();
        }
    }


    private final class MyPlayerListener implements MediaPlayer.OnCompletionListener {
        //歌曲播放完后自动播放下一首歌曲
        public void onCompletion(MediaPlayer mp) {
            next();
        }
    }


    public void next(View view) {
        next();
    }


    public void previous(View view) {
        previous();
    }


    private void previous() {
        current = current - 1 < 0 ? data.size() - 1 : current - 1;
        play();
    }


    private void next() {
        current = (current + 1) % data.size();
        play();
    }


    private final class MySeekBarListener implements SeekBar.OnSeekBarChangeListener {
        //移动触发
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        }

        //起始触发
        public void onStartTrackingTouch(SeekBar seekBar) {
            isStartTrackingTouch = true;
        }

        //结束触发
        public void onStopTrackingTouch(SeekBar seekBar) {
            player.seekTo(seekBar.getProgress());
            isStartTrackingTouch = false;
        }
    }


    private void generateListView() {
        List list = new ArrayList();

        //获取sdcard中的所有歌曲
        findAll(Environment.getExternalStorageDirectory(), list);

        //播放列表进行排序,字符顺序
        Collections.sort(list);

        data = new ArrayList, String>>();
        for (File file : list) {
            Map, String> map = new HashMap, String>();
            map.put("name", file.getName());
            map.put("path", file.getAbsolutePath());
            data.add(map);
        }

        SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item, new String[] { "name" }, new int[] { R.id.mName });
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new MyItemListener());
    }

    private final class MyItemListener implements AdapterView.OnItemClickListener {
        public void onItemClick(AdapterView parent, View view, int position, long id) {
            current = position;
            play();
        }
    }


    private void play() {
        try {
            //重播
            player.reset();

            //获取歌曲路径
            player.setDataSource(data.get(current).get("path"));

            //缓冲
            player.prepare();

            //开始播放
            player.start();

            //显示歌名
            nameTextView.setText(data.get(current).get("name"));

            //设置进度条长度
            seekBar.setMax(player.getDuration());

            //播放按钮样式
            ppButton.setText("||");

            //发送一个Runnable, handler收到之后就会执行run()方法
            handler.post(new Runnable() {
                public void run() {
                    // 更新进度条状态
                    if (!isStartTrackingTouch)
                        seekBar.setProgress(player.getCurrentPosition());
                    // 1秒之后再次发送
                    handler.postDelayed(this, 1000);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void findAll(File file, List list) {
        File[] subFiles = file.listFiles();
        if (subFiles != null)
            for (File subFile : subFiles) {
                if (subFile.isFile() && subFile.getName().endsWith(".mp3"))
                    list.add(subFile);
                else if (subFile.isDirectory())//如果是目录
                    findAll(subFile, list); //递归
            }
    }


    public void pp(View view) {

        //默认从第一首歌曲开始播放
        if (!player.isPlaying() && !isPause) {
            play();
            return;
        }

        Button button = (Button) view;
        //暂停/播放按钮
        if ("||".equals(button.getText())) {
            pause();
            button.setText("▶");
        } else {
            resume();
            button.setText("||");
        }
    }


    private void resume() {
        if (isPause) {
            player.start();
            isPause = false;
        }
    }


    private void pause() {
        if (player != null && player.isPlaying()) {
            player.pause();
            isPause = true;
        }
    }


    private final class PhoneListener extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            pause();
        }
    }


    protected void onResume() {
        super.onResume();
        resume();
    }
}
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFFFF">


            android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:layout_marginTop="22dp"
        android:layout_marginLeft="22dp"
        android:layout_marginRight="22dp"
        android:layout_marginBottom="22dp">



                    android:id="@+id/name"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            />
                    android:id="@+id/seekBar"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="5dp"
            />

                    android:layout_width="wrap_content"
            android:layout_height="wrap_content">


        


                    android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="20dp"
            android:layout_marginTop="15dp"
            >
            
<1>在新建一个item文件XIM
xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    >
            android:id="@+id/mName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="15sp"
        />

<在平板运行程序>

你可能感兴趣的:(Android音乐代码)