如何在Android中设置DataSource循环播放音乐?

5vf7fwbs  于 2023-02-06  发布在  Android
关注(0)|答案(3)|浏览(192)
String path ="";

        mediaPlayer.setDataSource(path); //path url mp3
        mediaPlayer.prepare();
        textTotalDuration.setText(milliSecondsToTimer(mediaPlayer.getDuration()));

示例读取下载文件夹或特定路径中的所有mp3

ttp71kqs

ttp71kqs1#

如果你能多解释一下你的问题会更好。据我所知,你想循环你的媒体播放器。如果你想循环你的媒体播放器,然后添加

mediaPlayer.setLooping(true);
7uzetpgm

7uzetpgm2#

我想你是在问如何添加数据源路径。所以,如果你问的是这个,那么试试这个:

String path = Environment.getExternalStorageDirectory()+"/Download/music.mp3";
        mediaPlayer.setDataSource(path); 
        mediaPlayer.prepare();
        textTotalDuration.setText(milliSecondsToTimer(mediaPlayer.getDuration()));

如果您询问循环媒体播放,则:

mediaPlayer.setLooping(true);
vktxenjb

vktxenjb3#

读取文件夹中的所有mp3 & m4a & wav & aac音乐:

private int trackIndex = 0;
private List<String> tracks;
private MediaPlayer mediaPlayer;

private void initMediaPlayer() {
    tracks = new ArrayList<>();
    addTracksInDirectory("/storage/emulated/0/Music/");////path url mp3
    mediaPlayer = new MediaPlayer();
    setTrack(trackIndex);
}

private void setTrack(int index) {
    try {
        trackIndex = index;
        mediaPlayer.reset();
        mediaPlayer.setDataSource(tracks.get(trackIndex));
        mediaPlayer.prepare();
        mediaPlayer.start();

        // Listen for the end of the track and play the next one
        mediaPlayer.setOnCompletionListener(mediaPlayer -> {
            trackIndex = (trackIndex + 1) % tracks.size();
            setTrack(trackIndex);
        });
    } catch (IOException e) {
        // Handle the error
    }
}

private void addTracksInDirectory(String directoryPath) {
    File directory = new File(directoryPath);
    File[] files = directory.listFiles();
    if (files != null) {
        for (File file : files) {
            if (file.isFile() && isAudioFile(file.getName())) {
                tracks.add(file.getAbsolutePath());
            }
        }
    }
}

private boolean isAudioFile(String fileName) {
    String[] audioFileExtensions = {".mp3", ".m4a", ".wav", ".aac"};
    for (String extension : audioFileExtensions) {
        if (fileName.endsWith(extension)) {
            return true;
        }
    }
    return false;
}

相关问题