背景播放音乐

本次编程运用了MediaPlayer类,实现对手机歌曲的读取。

1.上下首播放;

2,。音量的设置;

3.播放进度的显示。

代码:MediaPlayerActivity.java

import java.io.BufferedReader;

import java.io.File;

import java.io.IOException;

import java.io.StringReader;

import java.util.ArrayList;

import java.util.List;

 

import com.briup.R;

 

import android.app.Activity;

import android.content.Context;

import android.media.AudioManager;

import android.media.MediaPlayer;

import android.media.MediaPlayer.OnCompletionListener;

import android.media.MediaPlayer.OnErrorListener;

import android.os.Bundle;

import android.os.Environment;

import android.os.Handler;

import android.os.Message;

import android.util.Log;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.ImageButton;

import android.widget.ImageView;

import android.widget.SeekBar;

import android.widget.Toast;

import android.widget.SeekBar.OnSeekBarChangeListener;

import android.widget.TextView;

 

public class MediaPlayerActivity extends Activity

{

MediaPlayer mp;

SeekBar bar;

SeekBar vbar;

TextView currentTime;

TextView allTime;

Handler handler = new Handler();

File path;

List<String> files;

String currentfile;

TextView filenameTv;

TextView txtLrc;// 歌词

String lrccon;// 歌词内容

// 子线程监听进度的改变

private Runnable thread = new Runnable()

{

@Override

public void run()

{

updateTextView();

playNext(true);

showLrc();

handler.postDelayed(thread, 1000);

}

};

 

@Override

public void onCreate(Bundle savedInstanceState)

{

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

filenameTv = (TextView) findViewById(R.id.filename);

allTime = (TextView) findViewById(R.id.all);

if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))

{

path = Environment.getExternalStorageDirectory();

} else

{

Toast.makeText(this, "请插入sdcard", Toast.LENGTH_SHORT).show();

return;

}

// 获取所有音乐文件

files = FileUtil.getFiles(path);

 

mp = new MediaPlayer();

// 刚开始播放时初始化

play(this.getIntent().getStringExtra("file"));

// 显示歌词

txtLrc = (TextView) findViewById(R.id.lrc);

isExistLrc();

// 控制音轨

bar = (SeekBar) findViewById(R.id.bar);

bar.setMax(mp.getDuration());

currentTime = (TextView) findViewById(R.id.current);

currentTime.setText("0:00");

new Thread(thread).start();

bar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()

{

@Override

public void onStopTrackingTouch(SeekBar seekBar)

{

}

 

@Override

public void onStartTrackingTouch(SeekBar seekBar)

{

}

 

@Override

public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)

{

if (fromUser)

{

mp.seekTo(progress);

}

}

});

// 控制音量

vbar = (SeekBar) findViewById(R.id.vbar);

final AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

vbar.setMax(am.getStreamMaxVolume(AudioManager.STREAM_MUSIC));

vbar.setProgress(am.getStreamVolume(AudioManager.STREAM_MUSIC));

vbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()

{

@Override

public void onStopTrackingTouch(SeekBar seekBar)

{

}

 

@Override

public void onStartTrackingTouch(SeekBar seekBar)

{

}

 

@Override

public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)

{

am.setStreamVolume(AudioManager.STREAM_MUSIC, vbar.getProgress(), 0);

}

});

final ImageView play = (ImageView) findViewById(R.id.play);

final ImageView pre = (ImageView) findViewById(R.id.pre);

final ImageView next = (ImageView) findViewById(R.id.next);

final ImageView stop = (ImageView) findViewById(R.id.stop);

 

ImageView volumn = (ImageView) findViewById(R.id.volumn);

 

// 播放

play.setOnClickListener(new OnClickListener()

{

@Override

public void onClick(View v)

{

if (!mp.isPlaying())

{

mp.start();

play.setImageResource(R.drawable.pause);

 

} else if (mp.isPlaying())

{

mp.pause();

play.setImageResource(R.drawable.play);

}

}

});

// 停止

stop.setOnClickListener(new OnClickListener()

{

 

@Override

public void onClick(View v)

{

mp.stop();

play.setImageResource(R.drawable.play);

try

{

mp.prepare();

} catch (Exception e)

{

e.printStackTrace();

}

}

});

// 上一首

pre.setOnClickListener(new OnClickListener()

{

@Override

public void onClick(View v)

{

int pos = files.indexOf(currentfile);

if (pos - 1 >= 0)

{

play(files.get(pos - 1));

mp.start();

play.setImageResource(R.drawable.pause);

} else

Toast.makeText(MediaPlayerActivity.this, "没有歌曲", Toast.LENGTH_SHORT).show();

}

});

// 下一首

next.setOnClickListener(new OnClickListener()

{

@Override

public void onClick(View v)

{

// 播放下一首歌

playNextMusic();

play.setImageResource(R.drawable.pause);

}

});

 

}

 

// 播放

private void play(String filename)

{

mp.reset();

try

{

// Log.i("MediaPlayerActivity","文件内存:"+files.size()+"");

// Log.i("MediaPlayerActivity", "第一首歌:"+filename);

mp.setDataSource(path + "/" + filename);

currentfile = filename;

filenameTv.setText(currentfile);

mp.prepare();

int m = mp.getDuration() / 1000;

int s = m / 60;

int add = m % 60;

allTime.setText(s + ":" + add);

lrccon = PlayLrc.read(path, currentfile);

} catch (Exception e)

{

e.printStackTrace();

}

}

 

public void onDestroy()

{

mp.release();

mp = null;

super.onDestroy();

}

 

/**

 * 更新进度

 */

private void updateTextView()

{

if (mp != null)

{

int m = mp.getCurrentPosition() / 1000;

int s = m / 60;

int add = m % 60;

if (add < 10)

currentTime.setText(s + ":0" + add);

else

currentTime.setText(s + ":" + add);

bar.setProgress(mp.getCurrentPosition());

}

}

 

/**

 * 播放下一首

 * 

 * @param flag

 *            true:表示自动播放下一首

 */

private void playNext(boolean flag)

{

if (!flag)

{

playNextMusic();

} else

{

if (currentTime.getText().equals(allTime.getText()))

{

playNextMusic();

}

}

}

 

/**

 * 播放一首歌

 */

private void playNextMusic()

{

int pos = files.indexOf(currentfile);

if (pos + 1 < files.size())

{

play(files.get(pos + 1));

mp.start();

} else

{

play(files.get(0));

mp.start();

}

isExistLrc();

}

 

/**

 * 判断歌词是否存在

 */

private void isExistLrc()

{

if (PlayLrc.read(path, currentfile).length() == 0)

txtLrc.setText("歌词不存在");

}

 

/**

 * 显示歌词

 */

private void showLrc()

{

BufferedReader br = new BufferedReader(new StringReader(lrccon));

String temp;

try

{

while ((temp = br.readLine()) != null)

{

if (mp != null && temp.substring(temp.indexOf("]") + 1).length() > 0)

{

Log.i("test", "显示歌词线程进来了");

String time = PlayLrc.formatMS(mp.getCurrentPosition());

 

if (temp.contains(time))

{

Log.i("test", "歌词进来了");

txtLrc.setText(temp.substring(temp.indexOf("]") + 1));

br.close();

}

}

}

} catch (IOException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

功能界面:

 

程序中又增加了歌曲列表的展示:

代码:MainList.java

import java.io.File;

 

import com.briup.R;

 

import android.app.Activity;

import android.app.AlertDialog;

import android.app.AlertDialog.Builder;

import android.content.DialogInterface;

import android.content.DialogInterface.OnClickListener;

import android.content.Intent;

import android.os.Bundle;

import android.os.Environment;

import android.view.View;

import android.widget.AdapterView;

import android.widget.AdapterView.OnItemClickListener;

import android.widget.ArrayAdapter;

import android.widget.ListView;

import android.widget.TextView;

 

public class MainList extends Activity

{

 

@Override

protected void onCreate(Bundle savedInstanceState)

{

// TODO Auto-generated method stub

super.onCreate(savedInstanceState);

setContentView(R.layout.list);

ListView list = (ListView) findViewById(R.id.list);

if (getPath() == null)

alert("信息提示","请插入sd!");

else if(FileUtil.getFiles(getPath())==null)

alert("信息提示","sd卡没有歌曲");

  else{

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, FileUtil.getFiles(getPath()));

list.setAdapter(adapter);

list.setOnItemClickListener(new OnItemClickListener()

{

@Override

public void onItemClick(AdapterView<?> parent, View view, int position, long id)

{

Intent intent=new Intent(MainList.this,MediaPlayerActivity.class);

intent.putExtra("file",((TextView)view).getText());

startActivity(intent);

}

});

}

}

 

//弹出对话框

private void alert(String title,String msg)

{

AlertDialog.Builder dialog = new Builder(this);

dialog.setTitle(title);

dialog.setMessage(msg);

dialog.setPositiveButton("退出", new OnClickListener()

{

@Override

public void onClick(DialogInterface dialog, int which)

{

 

}

});

dialog.create().show();

}

 

private File getPath()

{

File path = null;

if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))

{

path = Environment.getExternalStorageDirectory();

}

return path;

}

}

列表界面:ListView

 

列表类展示:


 

Main.xml代码:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:padding="5dip" >

 

    <LinearLayout

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:layout_above="@+id/ll"

        android:layout_marginBottom="10dip"

        android:orientation="vertical" >

 

        <TextView

            android:id="@+id/filename"

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:gravity="center"

            android:text="音乐播放器" />

 

        <ImageView

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:src="@drawable/bg" />

 

        <TextView

            android:id="@+id/lrc"

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:gravity="center_horizontal" />

    </LinearLayout>

 

    <LinearLayout

        android:id="@+id/ll"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:layout_alignParentBottom="true"

        android:orientation="vertical" >

 

        <LinearLayout

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:orientation="horizontal" >

 

            <TextView

                android:id="@+id/current"

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:text="0:00" />

 

            <SeekBar

                android:id="@+id/bar"

                android:layout_width="240dip"

                android:layout_height="8px"

                android:layout_marginLeft="5dip"

                android:layout_marginRight="5dip"

                android:progressDrawable="@drawable/seekbar_img"            

                android:thumb="@drawable/bthumb" />

 

            <TextView

                android:id="@+id/all"

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:text="0:00" />

        </LinearLayout>

 

        <LinearLayout

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_marginLeft="30dip"

            android:gravity="center_vertical"

            android:orientation="horizontal" >

 

            <ImageView

                android:id="@+id/pre"

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:layout_marginLeft="10dip"

                android:src="@drawable/pre" />

 

            <ImageView

                android:id="@+id/play"

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:layout_marginLeft="10dip"

                android:src="@drawable/play" />

 

            <ImageView

                android:id="@+id/stop"

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:layout_marginLeft="10dip"

                android:src="@drawable/reset" />

 

            <ImageView

                android:id="@+id/next"

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:layout_marginLeft="10dip"

                android:src="@drawable/next" />

 

            <ImageView

                android:id="@+id/volumn"

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:layout_marginLeft="10dip"

                android:src="@drawable/volumn" />

 

            <SeekBar

                android:id="@+id/vbar"

                android:layout_width="94dip"

                android:layout_height="6px"

                android:layout_marginLeft="5dip"

                android:progressDrawable="@drawable/vseekbar_img"

                android:thumb="@drawable/thumb" />

        </LinearLayout>

    </LinearLayout>

</RelativeLayout>

List.xml代码;

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:orientation="vertical"

    android:padding="5dip" >

      <TextView

        android:id="@+id/filename"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="歌曲列表" />

  <ListView android:id="@+id/list"

       android:layout_width="fill_parent"

       android:layout_height="fill_parent" 

      android:divider="@android:color/white"       

       ></ListView>

  <Button android:id="@+id/exit"

      android:layout_alignParentBottom="true"

      android:layout_width="wrap_content"

      android:layout_height="wrap_content"

      android:textColor="@android:color/white"

      android:text="退出"

    android:layout_centerInParent="true"

      android:background="@android:color/background_dark"/>

</RelativeLayout>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,您可以使用以下代码创建一个在背景播放音乐并且带有切换音乐的按钮的网页: ``` <!DOCTYPE html> <html> <head> <title>Background Music Player</title> </head> <body> <h1>Background Music Player</h1> <button onclick="play()">Play</button> <button onclick="pause()">Pause</button> <button onclick="prev()">Prev</button> <button onclick="next()">Next</button> <br><br> <audio id="musicPlayer" autoplay loop> <source src="music1.mp3" type="audio/mpeg"> </audio> <script> var musicPlayer = document.getElementById("musicPlayer"); var musicList = ["music1.mp3", "music2.mp3", "music3.mp3"]; var currentMusicIndex = 0; function play() { musicPlayer.play(); } function pause() { musicPlayer.pause(); } function prev() { currentMusicIndex--; if (currentMusicIndex < 0) { currentMusicIndex = musicList.length - 1; } musicPlayer.src = musicList[currentMusicIndex]; musicPlayer.play(); } function next() { currentMusicIndex++; if (currentMusicIndex >= musicList.length) { currentMusicIndex = 0; } musicPlayer.src = musicList[currentMusicIndex]; musicPlayer.play(); } </script> </body> </html> ``` 在上面的代码中,我们创建了一个带有四个按钮的网页,分别是播放、暂停、上一曲和下一曲。我们使用了 HTML5 的 audio 元素来播放音乐,并设置了 autoplay 和 loop 属性来使音乐在背景中自动播放并循环播放。我们还定义了一个音乐列表(musicList)和一个当前播放的音乐索引(currentMusicIndex),并在 JavaScript 函数中实现了播放、暂停、上一曲和下一曲的功能。最后,我们使用了一个 script 标签将 JavaScript 代码添加到 HTML 文件中。 这样,您就可以创建一个在背景播放音乐并且带有切换音乐的按钮的网页了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值