Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 11 total  RSS 

Reencoding MP3s to lower Bitrate

http://ubuntuforums.org/showthread.php?t=347176
Batch-reencode MP3s using a terminal tool.

this installs lame (http://lame.sourceforge.net/index.php), an MP3 enconder
sudo apt-get install lame


this reencodes all MP3s in the current folder to a bitrate of 32
for x in [ `ls -1 *.mp3` ]; do lame --preset 32 $x new32-${x}; done

GStreamer Pipeline for ripping MP3s

// GStreamer Pipeline for ripping MP3s

audio/x-raw-int,rate=44100,channels=2 ! lame name=enc preset=1001 ! xingmux ! id3v2mux

Convert a video file to an audio file (.mp4 to .mp3)

Convert an mp4 file to avi, then to mp3 (including mixing the stereo down to mono). This code was executed from the command-line on Ubuntu 7.04.

mencoder video.mp4 -ovc lavc -vf scale=123:100 -oac lavc -o video.avi
ffmpeg -i video.avi -ac 1 audio1.mp3 

Flac to mp3

Converts all *.flac files in the current dir to mp3.

#!/bin/bash

for file in *.flac
do
	echo Converting $file
	flac123 -q --wav=- "$file" | lame - "$file".mp3
done

Play MP3 files

public class Player
{
  private string _command;
  private bool isOpen;
 [DllImport("winmm.dll")]
private static extern long mciSendString(string strCommand,StringBuilder strReturn,int iReturnLength, IntPtr hwndCallback);
  
public Player()
 {
   
 }
public void Close()
 {
  _command = "close MediaFile";
  mciSendString(_command, null, 0, IntPtr.Zero);
       isOpen=false;
 }

public void Open(string sFileName)
 {
  _command = "open \"" + sFileName + "\" type mpegvideo alias MediaFile";
  mciSendString(_command, null, 0, IntPtr.Zero);
  isOpen = true;
 }

public void Play(bool loop)
 {
  if(isOpen)
  {
   _command = "play MediaFile";
   if (loop)
    _command += " REPEAT";
    mciSendString(_command, null, 0, IntPtr.Zero);
   }
 }

}

tamilbeat.com mp3 crawler

create a file called links.dat and put the songs link from tamilbeat.com

#!/usr/bin/env ruby
require 'net/http'
require 'socket'
                                                                                                                            
Thread.abort_on_exception = true
threads = []
                                                                                                                            
line = File.open("links.dat")
IO.foreach("links.dat") {|line|
  if %r{http://([^/]+)/([^/]+/+.+)}i =~ line
    domain,path = $1, $2
  end
  web = TCPSocket.new(domain,"http")
  web.print "GET /"+path+" HTTP/1.0\n\n"
  web.print "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.2) Gecko/20070220 Firefox/2.0.0.2"
  answer = web.gets(nil)
  web.close
                                                                                                                            
  # for mp3
  arr = answer.scan(/http:\/\/www.+mp3/)
                                                                                                                            
  arr.each do |e|
    threads << Thread.new(e){|mp3|
      if %r{http://([^/]+)/([^/]+/+.+)/(.+mp3)}i =~ mp3
        website,song,name = $1, $2, $3
      end
      a=Net::HTTP.new(website,80)
      song_get = "/"+song+"/"+name
      puts "Fetching #{website}#{song_get}"
      resp, data = a.get(song_get,nil)
      puts "Got #{website}#{song_get}: #{resp.message}"
      open(name,'w'){|f| f.write(data)}
    }
  end
}
threads.each {|aThread| aThread.join}

Python id3 tag from containing folder

// Total noob python script for renaming the 'album' tag in an untagged mp3 file. I plug it into podnova (using advanced -> run command) as it downloads my podcasts so that they get sorted correctly when I copy them onto my ipod.

PodNova organizes podcasts by folder. the iPod organizes podcasts by album tag. If you use GtkPod to copy podcasts from PodNova, this can help keep mp3 podcasts categorized properly.

#!/usr/bin/python
import sys

# requires ID3 module, easily googled
from ID3 import *
for arg in sys.argv:
    fullfilename = arg

# This only works for mp3 files, I would love suggestions for mp4 tags
id3info = ID3(fullfilename)

# Print command useful for logging.
print id3info

# Check if album info exists
if not id3info.has_key('ALBUM'):
    print 'appending album tag'
    # truncate to just containing directory:
    folder = fullfilename[1:rfind(fullfilename,'/')]
    # define album based on podcast's directory
    album = (folder[rfind(folder,'/'):]).strip('/')
    id3info.album = album
    if id3info.album == album:
        print 'success!'
else:
    print 'nothing to change'
    

My handy mp3 "alarm clock" written in Ruby.

// Simple tool to help wake me up in the morning. Not the cleanest code, but it took no time to write. Ruby rocks!

#!/bin/env ruby
#
# A helper to setup an alarm to slowly and leisurely wake up in the morning.
#
# $Id: mp3wakeup.rb 6 2007-01-31 16:02:57Z btek $
#

if ARGV.length < 1
	puts "Usage: #{$0} <time> [mp3dir]"
	exit 1
end

#############################
# Configuration parameters. #
#############################

NUM_STEPS = 15
STEP_DURATION = 60 * 1

FINAL_VOLUME = 95
INITIAL_VOLUME = 30
VOLUME_STEP = (FINAL_VOLUME - INITIAL_VOLUME) / NUM_STEPS

MIN_SEC_BEFORE_ALARM = NUM_STEPS * STEP_DURATION

#############################
#############################

time = Regexp.quote ARGV[0]
mp3dir = Regexp.quote(ARGV[1]) if ARGV.length > 1

def get_alarm_time(desired_hour, desired_minute)
  now = Time.new
  
  alarm_time = Time.local(now.year, now.month, now.day, desired_hour, desired_minute, 0, 0)
  
  if alarm_time - now < MIN_SEC_BEFORE_ALARM
    alarm_time = alarm_time + 60*60*24
  end
  
  return alarm_time
end

def run(cmd)
  #puts cmd
  system cmd
end

puts "Waking you up by #{time} with songs from #{mp3dir}."

match = time.match(/(\d+)(:(\d+))?/)
hour = match[1].to_i
minute = if (match.length > 1)
           match[3].to_i 
         else
           0
         end

alarm_time = get_alarm_time(hour, minute)

for i in 0..NUM_STEPS
  alert_time = alarm_time - (STEP_DURATION * i)
  volume = FINAL_VOLUME - (VOLUME_STEP * i)
  
  at_cmd = "at #{alert_time.hour.to_s.rjust(2, '0')}:#{alert_time.min.to_s.rjust(2, '0')}"
  run "echo amixer sset PCM #{volume}% | #{at_cmd}"
  
  if i == NUM_STEPS
    # Start playing after time is confirmed set.
    alert_time = alert_time + (60)
    at_cmd = "at #{alert_time.hour.to_s.rjust(2, '0')}:#{alert_time.min.to_s.rjust(2, '0')}"
    
    if mp3dir != nil
      run "echo audacious #{mp3dir} | #{at_cmd}"
    else
      run "echo audtool playback-play | #{at_cmd}"
    end
  end
end

Java - Example Very Simple Player (JMF)

// Main Class

package org.jmf.example;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.plaf.metal.MetalLookAndFeel;

public class ExampleJMF
{
	public static void main(String[] args)
	{
		JFrame.setDefaultLookAndFeelDecorated(true); 
		JDialog.setDefaultLookAndFeelDecorated(true);
		
		try
		{
			UIManager.setLookAndFeel(new MetalLookAndFeel());
		}
		catch(UnsupportedLookAndFeelException e)
		{
			e.printStackTrace();
		}
		
		new exampleFrame();
	}
}


// Frame Class

package org.jmf.example;

import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;

public class exampleFrame extends JFrame
{
	private static final long serialVersionUID = 1L;
	
	public exampleFrame()
	{
		super("JMF - Example...");
		
		setSize(400, 300);
		setLocation((Toolkit.getDefaultToolkit().getScreenSize().width - getWidth())/2, (Toolkit.getDefaultToolkit().getScreenSize().height - getHeight())/2);
		
		addWindowListener(new WindowAdapter()
		{
			public void windowClosing(WindowEvent evt)
			{
				System.exit(0);
			}
		});
		
		setContentPane(new examplePanel());
		setVisible(true);
	}
}


// Panel Class

package org.jmf.example;

import java.awt.Component;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.media.ControllerEvent;
import javax.media.ControllerListener;
import javax.media.Manager;
import javax.media.NoPlayerException;
import javax.media.Player;
import javax.media.RealizeCompleteEvent;
import javax.swing.JPanel;

public class examplePanel extends JPanel implements ActionListener, ControllerListener
{
	private static final long serialVersionUID = 1L;
	
	private Component visualComponent;
	private Player player;
	
	public examplePanel()
	{
		try
		{
			player = Manager.createPlayer(new URL("file:///tmp/a.mpg"));
			player.addControllerListener(this);
			
			player.start();
		}
		catch(NoPlayerException e)
		{
			e.printStackTrace();
		}
		catch(MalformedURLException e)
		{
			e.printStackTrace();
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
	}
	
	public void paintComponent(Graphics g)
	{
		super.paintComponent(g);
	}

	public void actionPerformed(ActionEvent e)
	{

	}

	public void controllerUpdate(ControllerEvent c)
	{
		if(player == null)
			return;
		
		if(c instanceof RealizeCompleteEvent)
		{
			if((visualComponent = player.getVisualComponent()) != null)
				add(visualComponent);
		}
	}
}

Playlist generator

Bash script to generate a playlist with all your mp3s and oggs in.

rm ~/Desktop/playlist.m3u
find ~/music/ -iname "*.mp3" -print >> ~/Desktop/playlist.m3u
find ~/music/ -iname "*.ogg" -print >> ~/Desktop/playlist.m3u
« Newer Snippets
Older Snippets »
Showing 1-10 of 11 total  RSS