gpt4 book ai didi

android - 如何使用Android MediaPlayer在毫秒范围内播放mp3文件?

转载 作者:行者123 更新时间:2023-12-03 02:08:18 24 4
gpt4 key购买 nike

我可以使用android的MediaPlayer对象播放mp3文件。但是我想在毫秒范围内播放,例如30000 ms到40000 ms之间(仅10秒)。我该如何实现?

目前,我拥有以下代码,

private MediaPlayer mPlayer;
public void play() {
try {
mPlayer = MediaPlayer.create(getApplicationContext(), R.raw.mp3_file);
if (mPlayer != null) {
int currentPosition = mPlayer.getCurrentPosition();
if (currentPosition + 30000 <= mPlayer.getDuration()) {
mPlayer.seekTo(currentPosition + 30000);
} else {
mPlayer.seekTo(mPlayer.getDuration());
}
mPlayer.start();
}
}
catch(Exception e) {
}
}

任何帮助是极大的赞赏。谢谢!

最佳答案

您可以使用以下方法:

public int getCurrentPosition ()

要获取以milSeconds为单位的当前时间,也许是在每1000 milSeconds运行一次的Handler中进行测试,以查看:
if(mPlayer.getCurrentPosition() >= (mPlayer.getDuration + 40000));

使用完媒体文件后,请不要忘记 release:
public void release();
mPlayer.release();

Releases resources associated with this MediaPlayer object. It is considered good practice to call this method when you're done using the MediaPlayer. In particular, whenever an Activity of an application is paused (its onPause() method is called), or stopped (its onStop() method is called), this method should be invoked to release the MediaPlayer object, unless the application has a special need to keep the object around. In addition to unnecessary resources (such as memory and instances of codecs) being held, failure to call this method immediately if a MediaPlayer object is no longer needed may also lead to continuous battery consumption for mobile devices, and playback failure for other applications if no multiple instances of the same codec are supported on a device. Even if multiple instances of the same codec are supported, some performance degradation may be expected when unnecessary multiple instances are used at the same time.

关于android - 如何使用Android MediaPlayer在毫秒范围内播放mp3文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26369993/

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