gpt4 book ai didi

java - 识别正在播放的音频文件的运行时间

转载 作者:行者123 更新时间:2023-12-02 22:37:57 25 4
gpt4 key购买 nike

我正在开发一个简单的音频播放器,当我暂停/停止它时,它将显示音频播放了多长时间(编辑:例如,如果我在 52 秒处重新开始音乐,然后在 55 秒处暂停, toast 会说“3")。截至目前,我正在使用这个:

long startTime = System.currentTimeMillis();
long stopTime = System.currentTimeMillis();
Toast.makeText(getApplicationContext(), "Elapsed time was " + ((stopTime - startTime)/1000) + " seconds.", Toast.LENGTH_LONG).show();}

显示时差。我遇到的问题是 startTime 是从我第一次点击播放开始的,而不是最近的时间(只是不断地计数)。
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private Button playMusic;
private MediaPlayer mediaPlayer;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mediaPlayer = new MediaPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.adele);
mediaPlayer.setLooping(true);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
@Override
public void onCompletion(MediaPlayer mp){
int duration = mp.getCurrentPosition()/1000;
Toast.makeText(getApplicationContext(), "Duration:" + duration + " seconds", Toast.LENGTH_LONG).show();
}
});

playMusic = (Button) findViewById(R.id.playButton);
playMusic.setOnClickListener(new View.OnClickListener(){
long startTime = System.currentTimeMillis();
@Override
public void onClick(View v){

if (mediaPlayer.isPlaying()) {
pauseMusic();
long stopTime = System.currentTimeMillis();
Toast.makeText(getApplicationContext(), "Elapsed time was " + ((stopTime - startTime)/1000) + " seconds.", Toast.LENGTH_LONG).show();}
else {
startMusic();
}
}
});

setVolumeControlStream(AudioManager.STREAM_MUSIC);
}

public void pauseMusic(){
if (mediaPlayer !=null){
mediaPlayer.pause();
playMusic.setText(getString(R.string.button_start));
}
}

public void startMusic(){
if (mediaPlayer != null){
mediaPlayer.start();
playMusic.setText(getString(R.string.button_pause));
}
}

protected void onDestroy(){
if (mediaPlayer !=null && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
super.onDestroy();
}
}

最佳答案

首先将 long startTime 和 stopTime 放在 onCreate() 方法之上。现在,尝试在 onPause() 方法中添加这些代码行并像这样更改代码:

public void pauseMusic(){
if (mediaPlayer !=null){
mediaPlayer.pause();
startTime=mediaPlayer.getCurrentPosition();
playMusic.setText(getString(R.string.button_start));
}
}

关于java - 识别正在播放的音频文件的运行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42966666/

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