Sunday, July 25, 2010

Shuffle my songs

I have recently hit upon a limitation with my car MP3 player playing songs from my USB. It doesn’t have a SHUFFLE option :( and I had to always listen in the same order again and again.

It might sound obvious and simple to manually rename the files and sort, but if you have huge list of songs under multiple folders, you would certainly require a smart program which does this job for you.

This program uses the new NIO.2 from JDK7. It recursively goes through all the subfolders and search for .mp3/.MP3 files, copy to target folder after renaming. Please use latest JDK 7 to run this program.

More about NIO.2 http://java.sun.com/developer/technicalArticles/javase/nio/

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.util.UUID;
import static java.nio.file.StandardCopyOption.*;

public class ShuffleMp3 {
private static final String SOURCE= "/TEMP";
private static final String TARGET= "/TEST/";
private static void copyThisFile(Path file) throws IOException {
Path targetPath = Paths.get(TARGET+UUID.randomUUID().toString().replaceAll("-","")+".mp3");
file.copyTo(targetPath, REPLACE_EXISTING);
System.out.println("Copied " + file.toString() + " to " + targetPath.toString());
}

static class Mp3FileVisitor extends SimpleFileVisitor<Path> {

@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
try {
if(file.getName().toString().lastIndexOf(".mp3") >=0
file.getName().toString().lastIndexOf(".MP3") >=0)
copyThisFile(file);
} catch (Exception exc) { exc.printStackTrace(); }
return FileVisitResult.CONTINUE;
}
}
public static void main(String... arg) {
final Path path = Paths.get(SOURCE);
Files.walkFileTree(path, new Mp3FileVisitor());
}
}

While storing back in your USB/SD/’Memory device’ please sort. As some parameter needs to supply like source and target, don’t try this program on your master list. I suggest taking a backup of the files before running this utility program against it.

$javac ShuffleMp3

$ java ShuffleMp3

Copied /TEMP/English/Old/OldTest.mp3 to /TEST/9ad4282b-c775-4508-8133-74f45b8a0197.mp3

Copied /TEMP/English/TEST.mp3 to /TEST/fc03dbdb-04f2-4eb8-98f8-ff50b0668411.mp3

Copied /TEMP/Telugu/TEST1.mp3 to /TEST/8b97aa92-7a17-4e8d-926b-cf3ff4344f6c.mp3