Использование медиапланера для воспроизведения аудиофайла.
Все работает отлично, но прошедшее время звука необходимо обновить в текстовом виде.
textview.setText(mediaplayer.getCurrentPosition()/100000.0).toString();
Это дает двойное значение, но если время окончания больше минуты, и прошедшее время равно 1 минутам, оно показывает 0:60... но оно должно быть как 1:00...
Есть ли другой способ показать прошедшее время на основе прогресса поисковой системы?
Спасибо.
Это работает. Ответ, взятый из другого сообщения: Как правильно отобразить позицию/продолжительность MediaPlayer?
DateFormat работает для дат, а не для временных интервалов. Поэтому, если вы получаете позицию в 1 секунду, формат данных интерпретирует это как означающий, что дата/время составляет 1 секунду после начала календаря.
private String getTimeString(long millis) {
StringBuffer buf = new StringBuffer();
int hours = millis / (1000*60*60);
int minutes = ( millis % (1000*60*60) ) / (1000*60);
int seconds = ( ( millis % (1000*60*60) ) % (1000*60) ) / 1000;
buf
.append(String.format("%02d", hours))
.append(":")
.append(String.format("%02d", minutes))
.append(":")
.append(tring.format("%02d", seconds));
return buf.toString();
}
И затем сделайте что-то вроде
totalTime.setText(getTimeString(duration));
currentTime.setText(getTimeString(position));
Приложение примера музыки содержит класс MusicUtils:
/* Try to use String.format() as little as possible, because it creates a
* new Formatter every time you call it, which is very inefficient.
* Reusing an existing Formatter more than tripled the speed of
* makeTimeString().
* This Formatter/StringBuilder are also used by makeAlbumSongsLabel()
*/
private static StringBuilder sFormatBuilder = new StringBuilder();
private static Formatter sFormatter = new Formatter(sFormatBuilder, Locale.getDefault());
private static final Object[] sTimeArgs = new Object[5];
public static String makeTimeString(Context context, long secs) {
String durationformat = context.getString(
secs < 3600 ? R.string.durationformatshort : R.string.durationformatlong);
/* Provide multiple arguments so the format can be changed easily
* by modifying the xml.
*/
sFormatBuilder.setLength(0);
final Object[] timeArgs = sTimeArgs;
timeArgs[0] = secs / 3600;
timeArgs[1] = secs / 60;
timeArgs[2] = (secs / 60) % 60;
timeArgs[3] = secs;
timeArgs[4] = secs % 60;
return sFormatter.format(durationformat, timeArgs).toString();
}
который вы можете использовать.
Но решение carlovv тоже будет работать, если вы разделите результат getCurrentPosition() на 1000, так как метод возвращает миллисекунды.
вот что входит в ваши строки .xml
<string translatable="false" name="durationformatshort">
<xliff:g id="format">%2$d:%5$02d</xliff:g>
</string>
<string translatable="false" name="durationformatlong">
<xliff:g id="format">%1$d:%3$02d:%5$02d</xliff:g>
</string>
вы можете преобразовать getCurrentPosition в дату и использовать dateFormat для установки выходной строки.
Date d = new Date();
d.setTime(mediaplayer.getCurrentPosition());
private final SimpleDateFormat timeFormat = new SimpleDateFormat("HH.mm");
String time = timeFormat.format(d).toString();