gpt4 book ai didi

java - 如何向我的媒体播放器添加 seekbar Plus 快退和快进按钮

转载 作者:行者123 更新时间:2023-11-29 06:38:42 25 4
gpt4 key购买 nike

大家好,我正在为我的 Android 设备开发媒体播放器,但不确定如何让搜索栏正常工作,而且我希望能够通过按住按钮而不是按一次来快进和快退

这是我目前所拥有的

MyMediaPlayerActivity 类:

     package com.technegames.mymediaplayer;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MyMediaPlayerActivity extends Activity {
WakeLock wakeLock;
private static final String[] EXTENSIONS = { ".mp3", ".mid", ".wav", ".ogg", ".mp4" }; //Playable Extensions

List<String> trackNames; //Playable Track Titles

List<String> trackArtworks; //Track artwork names

AssetManager assets; //Assets (Compiled with APK)

File path; //directory where music is loaded from on SD Card

File path2; //directory where album artwork is loaded from on SD Card

Music track; //currently loaded track

ImageView bg; //Track artwork

Button btnPlay; //The play button will need to change from 'play' to 'pause', so we need an instance of it

Random random; //used for shuffle

boolean shuffle; //is shuffle mode on?

boolean isTuning; //is user currently jammin out, if so automatically start playing the next track

int currentTrack; //index of current track selected

int type; //0 for loading from assets, 1 for loading from SD card

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "Lexiconda");
setContentView(R.layout.main);

initialize(0);
}

@Override
public void onResume(){
super.onResume();
wakeLock.acquire();
}

@Override
public void onPause(){
super.onPause();
wakeLock.release();
if(track != null){
if(track.isPlaying()){
track.pause();
isTuning = false;
btnPlay.setBackgroundResource(R.drawable.play);
}
if(isFinishing()){
track.dispose();
finish();
}
} else{
if(isFinishing()){
finish();
}
}
}

private void initialize(int type){
bg = (ImageView) findViewById(R.id.bg);
btnPlay = (Button) findViewById(R.id.btnPlay);
btnPlay.setBackgroundResource(R.drawable.play);
trackNames = new ArrayList<String>();
trackArtworks = new ArrayList<String>();
assets = getAssets();
currentTrack = 0;
shuffle = false;
isTuning = false;
random = new Random();
this.type = type;

addTracks(getTracks());
loadTrack();
}

//Generate a String Array that represents all of the files found
private String[] getTracks(){
if(type == 0){
try {
String[] temp = getAssets().list("");
return temp;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
} else if(type == 1){
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
|| Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY)){
path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
path2 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String[] temp = path.list();
return temp;
} else{
Toast.makeText(getBaseContext(), "SD Card is either mounted elsewhere or is unusable", Toast.LENGTH_LONG).show();
}
}
return null;
}

//Adds the playable files to the trackNames List
private void addTracks(String[] temp){
if(temp != null){
for(int i = 0; i < temp.length; i++){
//Only accept files that have one of the extensions in the EXTENSIONS array
if(trackChecker(temp[i])){
trackNames.add(temp[i]);
trackArtworks.add(temp[i].substring(0, temp[i].length()-4));
}
}
Toast.makeText(getBaseContext(), "Loaded " + Integer.toString(trackNames.size()) + " Tracks", Toast.LENGTH_SHORT).show();
}
}

//Checks to make sure that the track to be loaded has a correct extenson
private boolean trackChecker(String trackToTest){
for(int j = 0; j < EXTENSIONS.length; j++){
if(trackToTest.contains(EXTENSIONS[j])){
return true;
}
}
return false;
}

//Loads the track by calling loadMusic
private void loadTrack(){
if(track != null){
track.dispose();
}
if(trackNames.size() > 0){
track = loadMusic(type);
setImage("drawable/" + trackArtworks.get(currentTrack));
}
}

//loads a Music instance using either a built in asset or an external resource
private Music loadMusic(int type){
switch(type){
case 0:
try{
AssetFileDescriptor assetDescriptor = assets.openFd(trackNames.get(currentTrack));
return new Music(assetDescriptor);
} catch(IOException e){
e.printStackTrace();
Toast.makeText(getBaseContext(), "Error Loading " + trackNames.get(currentTrack), Toast.LENGTH_LONG).show();
}
return null;
case 1:
try{
FileInputStream fis = new FileInputStream(new File(path, trackNames.get(currentTrack)));
FileDescriptor fileDescriptor = fis.getFD();
return new Music(fileDescriptor);
} catch(IOException e){
e.printStackTrace();
Toast.makeText(getBaseContext(), "Error Loading " + trackNames.get(currentTrack), Toast.LENGTH_LONG).show();
}
return null;
default:
return null;
}
}

//Sets the background image to match the track currently playing or a default image
private void setImage(String name) {
if(type == 0){
int imageResource = getResources().getIdentifier(name, null, getPackageName());
if(imageResource != 0){
Drawable image = getResources().getDrawable(imageResource);
bg.setImageDrawable(image);
} else{
int defaultImageResource = getResources().getIdentifier("drawable/defaultbg", null, getPackageName());
if(defaultImageResource != 0){
Drawable image = getResources().getDrawable(defaultImageResource);
bg.setImageDrawable(image);
}
}
} else if(type == 1){
if(new File(path2.getAbsolutePath(), trackArtworks.get(currentTrack) + ".jpg").exists()){
bg.setImageDrawable(Drawable.createFromPath(path2.getAbsolutePath() + "/" + trackArtworks.get(currentTrack) + ".jpg"));
} else{
int defaultImageResource = getResources().getIdentifier("drawable/defaultbg", null, getPackageName());
if(defaultImageResource != 0){
Drawable image = getResources().getDrawable(defaultImageResource);
bg.setImageDrawable(image);
}
}
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
createMenu(menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case 0:
//Set Looping
synchronized(this){
if(track.isLooping()){
track.setLooping(false);
Toast.makeText(getBaseContext(), "Playing Tracks Sequentially", Toast.LENGTH_SHORT).show();
} else{
track.setLooping(true);
Toast.makeText(getBaseContext(), "Looping " + trackNames.get(currentTrack), Toast.LENGTH_SHORT).show();
}
}
return true;
case 1:
//Set Shuffle
synchronized(this){
if(shuffle){
setShuffle(false);
} else{
setShuffle(true);
}
}
return true;
case 2:
//Stop Music
synchronized(this){
track.switchTracks();
btnPlay.setBackgroundResource(R.drawable.play);
}
return true;
case 3:
//Change Source from Assets to SD Card and vice versa
synchronized(this){
type++;
if(type > 1){
type = 0;
}
}
if(type == 0){
Toast.makeText(getBaseContext(), "Loading Tracks from Assets ", Toast.LENGTH_SHORT).show();
} else if(type == 1){
Toast.makeText(getBaseContext(), "Loading Tracks from SD Card", Toast.LENGTH_SHORT).show();
}
initialize(type);
return true;
default:
return false;
}
}

private void createMenu(Menu menu){
MenuItem miLooping = menu.add(0, 0, 0, "Looping");{
miLooping.setIcon(R.drawable.looping);
}
MenuItem miShuffle = menu.add(0, 1, 1, "Shuffle");{
miShuffle.setIcon(R.drawable.shuffle);
}
MenuItem miStop = menu.add(0, 2, 2, "Stop");{
miStop.setIcon(R.drawable.stop);
}
MenuItem miSource = menu.add(0, 3, 3, "Source");{
miSource.setIcon(R.drawable.source);
}
}

public void click(View view){
int id = view.getId();
switch(id){
case R.id.btnPlay:
synchronized(this){
if(isTuning){
isTuning = false;
btnPlay.setBackgroundResource(R.drawable.play);
track.pause();
} else{
isTuning = true;
btnPlay.setBackgroundResource(R.drawable.pause);
playTrack();
}
}
return;
case R.id.btnPrevious:
setTrack(0);
loadTrack();
playTrack();
return;
case R.id.btnNext:
setTrack(1);
loadTrack();
playTrack();
return;
default:
return;
}
}

private void setTrack(int direction){
if(direction == 0){
currentTrack--;
if(currentTrack < 0){
currentTrack = trackNames.size()-1;
}
} else if(direction == 1){
currentTrack++;
if(currentTrack > trackNames.size()-1){
currentTrack = 0;
}
}
if(shuffle){
int temp = random.nextInt(trackNames.size());
while(true){
if(temp != currentTrack){
currentTrack = temp;
break;
}
temp++;
if(temp > trackNames.size()-1){
temp = 0;
}
}
}
}

//Plays the Track
private void playTrack(){
if(isTuning && track != null){
track.play();
Toast.makeText(getBaseContext(), "Playing " + trackNames.get(currentTrack).substring(0, trackNames.get(currentTrack).length()-4), Toast.LENGTH_SHORT).show();
}
}

//Simply sets shuffle to isShuffle and then displays a message for confirmation
private void setShuffle(boolean isShuffle) {
shuffle = isShuffle;
if(shuffle){
Toast.makeText(getBaseContext(), "Shuffle On", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(getBaseContext(), "Shuffle Off", Toast.LENGTH_SHORT).show();
}
}

}

音乐类:

    import java.io.FileDescriptor;
import java.io.IOException;

import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;

public class Music implements OnCompletionListener{
MediaPlayer mediaPlayer;
boolean isPrepared = false;

public Music(AssetFileDescriptor assetDescriptor){
mediaPlayer = new MediaPlayer();
try{
mediaPlayer.setDataSource(assetDescriptor.getFileDescriptor(), assetDescriptor.getStartOffset(), assetDescriptor.getLength());
mediaPlayer.prepare();
isPrepared = true;
mediaPlayer.setOnCompletionListener(this);
} catch(Exception ex){
throw new RuntimeException("Couldn't load music, uh oh!");
}
}

public Music(FileDescriptor fileDescriptor){
mediaPlayer = new MediaPlayer();
try{
mediaPlayer.setDataSource(fileDescriptor);
mediaPlayer.prepare();
isPrepared = true;
mediaPlayer.setOnCompletionListener(this);
} catch(Exception ex){
throw new RuntimeException("Couldn't load music, uh oh!");
}
}

public void onCompletion(MediaPlayer mediaPlayer) {
synchronized(this){
isPrepared = false;
}
}

public void play() {
if(mediaPlayer.isPlaying()){
return;
}
try{
synchronized(this){
if(!isPrepared){
mediaPlayer.prepare();
}
mediaPlayer.start();
}
} catch(IllegalStateException ex){
ex.printStackTrace();
} catch(IOException ex){
ex.printStackTrace();
}
}

public void stop() {
mediaPlayer.stop();
synchronized(this){
isPrepared = false;
}
}

public void switchTracks(){
mediaPlayer.seekTo(0);
mediaPlayer.pause();
}

public void pause() {
mediaPlayer.pause();
}

public boolean isPlaying() {
return mediaPlayer.isPlaying();
}

public boolean isLooping() {
return mediaPlayer.isLooping();
}

public void setLooping(boolean isLooping) {
mediaPlayer.setLooping(isLooping);
}

public void setVolume(float volumeLeft, float volumeRight) {
mediaPlayer.setVolume(volumeLeft, volumeRight);
}

public void dispose() {
if(mediaPlayer.isPlaying()){
stop();
}
mediaPlayer.release();
}
}

最佳答案

希望这对您有所帮助。此代码用于我们的项目

public class MusicPlayer extends Activity
implements OnCompletionListener, SeekBar.OnSeekBarChangeListener {

private ImageButton btnPlay;
private ImageButton btnForward;
private ImageButton btnBackward;
private ImageButton btnPlaylist;
private ImageButton btnRepeat;
private ImageButton btnShuffle;
private SeekBar songProgressBar;
private TextView songTitleLabel;
private TextView songCurrentDurationLabel;
private TextView songTotalDurationLabel;
// Media Player
private MediaPlayer mp;
// Handler to update UI timer, progress bar etc,.
private Handler mHandler = new Handler();;
private SongsManager songManager;
private Utilities utils;
private int seekForwardTime = 5000; // 5000 milliseconds
private int seekBackwardTime = 5000; // 5000 milliseconds
private int currentSongIndex = 0;
private boolean isShuffle = false;
private boolean isRepeat = false;
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player);

// All player buttons
btnPlay = (ImageButton) findViewById(R.id.btnPlay);
btnForward = (ImageButton) findViewById(R.id.btnForward);
btnBackward = (ImageButton) findViewById(R.id.btnBackward);
btnPlaylist = (ImageButton) findViewById(R.id.btnPlaylist);
btnRepeat = (ImageButton) findViewById(R.id.btnRepeat);
btnShuffle = (ImageButton) findViewById(R.id.btnShuffle);
songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
songTitleLabel = (TextView) findViewById(R.id.songTitle);
songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);

// Mediaplayer
mp = new MediaPlayer();
songManager = new SongsManager();
utils = new Utilities();

// Listeners
songProgressBar.setOnSeekBarChangeListener(this); // Important
mp.setOnCompletionListener(this); // Important

// Getting all songs list
songsList = songManager.getPlayList();

// By default play first song
playSong(0);

/**
* Play button click event plays a song and changes button to pause
* image pauses a song and changes button to play image
* */
btnPlay.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// check for already playing
if (mp.isPlaying()) {
if (mp != null) {
mp.pause();
// Changing button image to play button
btnPlay.setImageResource(R.drawable.btn_play);
}
} else {
// Resume song
if (mp != null) {
mp.start();
// Changing button image to pause button
btnPlay.setImageResource(R.drawable.btn_pause);
}
}

}
});

btnForward.setOnLongClickListener(new OnLongClickListener() {

@Override
public boolean onLongClick(View v) {
// get current song position
int currentPosition = mp.getCurrentPosition();
// check if seekForward time is lesser than song duration
if (currentPosition + seekForwardTime <= mp.getDuration()) {
// forward song
mp.seekTo(currentPosition + seekForwardTime);
} else {
// forward to end position
mp.seekTo(mp.getDuration());
}
return false;
}
});

/**
* Forward button click event Forwards song specified seconds
* */
btnForward.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// get current song position
// check if next song is there or not
if (currentSongIndex < (songsList.size() - 1)) {
playSong(currentSongIndex + 1);
currentSongIndex = currentSongIndex + 1;
} else {
// play first song
playSong(0);
currentSongIndex = 0;
}
}
});

btnBackward.setOnLongClickListener(new OnLongClickListener() {

@Override
public boolean onLongClick(View v) {
int currentPosition = mp.getCurrentPosition();
// check if seekBackward time is greater than 0 sec
if (currentPosition - seekBackwardTime >= 0) {
// forward song
mp.seekTo(currentPosition - seekBackwardTime);
} else {
// backward to starting position
mp.seekTo(0);
}
return false;
}
});

/**
* Backward button click event Backward song to specified seconds
* */
btnBackward.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
if (currentSongIndex > 0) {
playSong(currentSongIndex - 1);
currentSongIndex = currentSongIndex - 1;
} else {
// play last song
playSong(songsList.size() - 1);
currentSongIndex = songsList.size() - 1;
}

}
});

/**
* Button Click event for Repeat button Enables repeat flag to true
* */
btnRepeat.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
if (isRepeat) {
isRepeat = false;
Toast.makeText(getApplicationContext(), "Repeat is OFF",
Toast.LENGTH_SHORT).show();
btnRepeat.setImageResource(R.drawable.btn_repeat);
} else {
// make repeat to true
isRepeat = true;
Toast.makeText(getApplicationContext(), "Repeat is ON",
Toast.LENGTH_SHORT).show();
// make shuffle to false
isShuffle = false;
btnRepeat.setImageResource(R.drawable.btn_repeat_focused);
btnShuffle.setImageResource(R.drawable.btn_shuffle);
}
}
});

/**
* Button Click event for Shuffle button Enables shuffle flag to true
* */
btnShuffle.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
if (isShuffle) {
isShuffle = false;
Toast.makeText(getApplicationContext(), "Shuffle is OFF",
Toast.LENGTH_SHORT).show();
btnShuffle.setImageResource(R.drawable.btn_shuffle);
} else {
// make repeat to true
isShuffle = true;
Toast.makeText(getApplicationContext(), "Shuffle is ON",
Toast.LENGTH_SHORT).show();
// make shuffle to false
isRepeat = false;
btnShuffle.setImageResource(R.drawable.btn_shuffle_focused);
btnRepeat.setImageResource(R.drawable.btn_repeat);
}
}
});

/**
* Button Click event for Play list click event Launches list activity
* which displays list of songs
* */
btnPlaylist.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(),
PlayListActivity.class);
startActivityForResult(i, 100);
}
});

}

/**
* Receiving song index from playlist view and play the song
* */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) {
currentSongIndex = data.getExtras().getInt("songIndex");
// play selected song
playSong(currentSongIndex);
}

}

/**
* Function to play a song
*
* @param songIndex
* - index of song
* */
public void playSong(int songIndex) {
// Play song
try {
mp.reset();
mp.setDataSource(songsList.get(songIndex).get("songPath"));
mp.prepare();
mp.start();
// Displaying Song title
String songTitle = songsList.get(songIndex).get("songTitle");
songTitleLabel.setText(songTitle);

// Changing Button Image to pause image
btnPlay.setImageResource(R.drawable.btn_pause);

// set Progress bar values
songProgressBar.setProgress(0);
songProgressBar.setMax(100);

// Updating progress bar
updateProgressBar();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* Update timer on seekbar
* */
public void updateProgressBar() {
mHandler.postDelayed(mUpdateTimeTask, 100);
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK) {
mHandler.removeCallbacks(mUpdateTimeTask);
mp.release();
}
return super.onKeyDown(keyCode, event);
}

/**
* Background Runnable thread
* */
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();

// Displaying Total Duration time
songTotalDurationLabel.setText(""
+ utils.milliSecondsToTimer(totalDuration));
// Displaying time completed playing
songCurrentDurationLabel.setText(""
+ utils.milliSecondsToTimer(currentDuration));

// Updating progress bar
int progress = (int) (utils.getProgressPercentage(currentDuration,
totalDuration));
// System.out.println("Progress : "+progress);
songProgressBar.setProgress(progress);

// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100);
}
};

/**
*
* */
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromTouch) {

}

/**
* When user starts moving the progress handler
* */
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// remove message Handler from updating progress bar
mHandler.removeCallbacks(mUpdateTimeTask);
}

/**
* When user stops moving the progress hanlder
* */
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
mHandler.removeCallbacks(mUpdateTimeTask);
int totalDuration = mp.getDuration();
int currentPosition = utils.progressToTimer(seekBar.getProgress(),
totalDuration);

// forward or backward to certain seconds
mp.seekTo(currentPosition);

// update timer progress again
updateProgressBar();
}

/**
* On Song Playing completed if repeat is ON play same song again if shuffle
* is ON play random song
* */
@Override
public void onCompletion(MediaPlayer arg0) {

// check for repeat is ON or OFF
if (isRepeat) {
// repeat is on play same song again
playSong(currentSongIndex);
} else if (isShuffle) {
// shuffle is on - play a random song
Random rand = new Random();
currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
playSong(currentSongIndex);
} else {
// no repeat or shuffle ON - play next song
if (currentSongIndex < (songsList.size() - 1)) {
playSong(currentSongIndex + 1);
currentSongIndex = currentSongIndex + 1;
} else {
// play first song
playSong(0);
currentSongIndex = 0;
}
}
}

@Override
public void onDestroy() {
super.onDestroy();
mp.release();
}

关于java - 如何向我的媒体播放器添加 seekbar Plus 快退和快进按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15978637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com