Ardunio 红外遥控PC音乐播放器_Java后端

                            

          Ardunio 红外遥控PC音乐播放器

 程序说明:

本程序通过红外遥控器,发射信号给接收器,然后由Ardunio 通过 USB 传给 PC端,实现一个播放器 
 本播放器可以 播放,暂停,上一首,下一首,静音,循环,声音加减 
 相信我,只有JMF才能做到这些功能,其他的JAVA媒体工具少之又少 
 本程序很Cool,学习的最主要是JAVA怎么监听USB,由此可以开发多种小应用

  环境说明:

            所需硬件

            1.  Ardunio uno 板一块

            2.  红外接收头一个

            3.  红外遥控器一个

            4.  面包板 + 线若干

            软件版本:

            Ardunio 1.0.5 

            Java 播放 音乐用到的是JMF.版本是2.1.1

            Java 监听 Ardunio 用到的是RXTX

         本程序所需要的JAVA库

1. RXTX_lib_32_64.ZIP(JAVA 监听 USB 所需要的库) 
    解压出来之后有RXTX_library_32和RXTX_library_64,一个是32位系统,一个是64位系统,别弄错了, 把里面的RXTXcomm.jar放到Eclipse, rxtxSerial.dll就放到 E:\dll\ 然后再Eclipse里面,找到RXTXcomm.jar,右键Propertise - Native Library - 设置rxtxSerial.dll的目录 
 2. 把jmf.jar mediaplayer.jar sound.jar 都添加到eclipse里面,这是JMF的库

            整个项目打包下载地址:

            http://pan.baidu.com/share/link?shareid=522418148&uk=3526727329              

线路图:

            Ardunio 红外遥控PC音乐播放器_Java后端      Ardunio 红外遥控PC音乐播放器_Java后端  此图是网上找的,实际的图我没有拍照,大同小异

Ardunio代码:  

PS: 请把红外接收器的 VOUT接到 数字脚11
#include <IRremote.h>     //附件里面有
int  RECV_PIN = 11;      //定义红外接收模块输出口接arduino数字引脚11

//此处定义遥控器的各个按键

#define  btn_poweroff 16753245      
#define  btn_mode  16736925
#define  btn_mute  16769565

#define  btn_pause_start  16720605
#define  btn_previous  16712445
#define  btn_next 16761405

#define  btn_eq  16769055
#define  btn_subtract  16754775
#define  btn_add  16748655

#define  btn_0   16738455
#define  btn_loop  16750695
#define  btn_usd  16756815

#define  btn_1  16724175
#define  btn_2  16718055
#define  btn_3  16743045

#define  btn_4  16716015
#define  btn_5  16726215
#define  btn_6  16734885

#define  btn_7  16728765
#define  btn_8  16730805
#define  btn_9  16732845


IRrecv irrecv(RECV_PIN);
decode_results results;

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); //初始化红外遥控
}


//这里是简单的根据遥控器传播过来的信号,做一个匹配,我已经事先获取每一个键的编码

void loop() {
  if (irrecv.decode(&results)) {

    switch(results.value){
    case btn_poweroff:
      Serial.println("poweroff");
      break;
    case btn_mode:
      Serial.println("mode");
      break;
    case btn_mute:
      Serial.println("mute");
      break;

    case btn_pause_start:
      Serial.println("pause_start");
      break;
    case btn_previous:
      Serial.println("previous");
      break;
    case btn_next:
      Serial.println("next");
      break;

    case btn_eq:
      Serial.println("eq");
      break;
    case btn_subtract:
      Serial.println("substract");
      break;
    case btn_add:
      Serial.println("add");
      break;

    case btn_0:
      Serial.println("0");
      break;
    case btn_loop:
      Serial.println("loop");
      break;
    case btn_usd:
      Serial.println("usd");
      break;

    case btn_1:
      Serial.println("1");
      break;
    case btn_2:
      Serial.println("2");
      break;
    case btn_3:
      Serial.println("3");
      break;

    case btn_4:
      Serial.println("4");
      break;
    case btn_5:
      Serial.println("5");
      break;
    case btn_6:
      Serial.println("6");
      break;

    case btn_7:
      Serial.println("7");
      break;
    case btn_8:
      Serial.println("8");
      break;
    case btn_9:
      Serial.println("9");
      break;

    }

    irrecv.resume(); // 接收下一个值
  }
}




 PC端JAVA程序


            1.  JAVA 监听 Ardunio 主程序:

package cn.dxy.service;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Enumeration;
import cn.dxy.action.audio.AudioController;
import cn.dxy.action.audio.JMFAudio;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;

public class ArdunioRemoteMusic implements SerialPortEventListener{
	SerialPort serialPort;
	
    /** 连接系统的端口 */
private static final String PORT_NAMES[] = { 
		"/dev/tty.usbserial-A9007UX1", // Mac OS X
		"/dev/ttyUSB0", // Linux
		"COM5", // Windows,此处我们用到的是windows的com5
};


private BufferedReader input;
private OutputStream output;
private static final int TIME_OUT = 2000;	/**此处为连接超时时间*/
private static final int DATA_RATE = 9600;	/**此处是和PC的USB连接通讯频率,默认*/

private static ArdunioRemoteMusic myArdunio = new ArdunioRemoteMusic();

private ArdunioRemoteMusic(){
}
public static ArdunioRemoteMusic getInstance(){
	return myArdunio;
}

/**
 * 
 * 初始化端口连接
 * 
 */
public void initialize() {
	   
	CommPortIdentifier portId = null;
	Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

	//首先,找到已经连接好的端口
	while (portEnum.hasMoreElements()) {
		CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
		for (String portName : PORT_NAMES) {
			if (currPortId.getName().equals(portName)) {
				portId = currPortId;
				System.out.println(PORT_NAMES);
				break;
			}
		}
	}
	
	if (portId == null) {
		System.out.println("Could not find COM port.");
		return;
	}

	try {
		// 打开端口
		serialPort = (SerialPort) portId.open(this.getClass().getName(),
				TIME_OUT);
		// 设置端口参数
		serialPort.setSerialPortParams(DATA_RATE,
				SerialPort.DATABITS_8,
				SerialPort.STOPBITS_1,
				SerialPort.PARITY_NONE);
		// 打开输入输出流
		input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
		output = serialPort.getOutputStream();
		// 增加事件监听
		serialPort.addEventListener(this);
		serialPort.notifyOnDataAvailable(true);
	} catch (Exception e) {
		System.err.println(e.toString());
	}
}

/**
 * 当你断开断开所触发的事件
 */
public synchronized void close() {
	if (serialPort != null) {
		serialPort.removeEventListener();
		serialPort.close();
	}
}

/**
 *   当由Ardunio有信息输入的时候,触发,进行读写
 */
public synchronized void serialEvent(SerialPortEvent oEvent) {
	
	if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
		try {
			String inputLine=input.readLine();
			System.out.println("收到的字符时:"+inputLine);
			AudioController.getInstance().controller(inputLine);	//此处就是音乐播放器模块
		} catch (Exception e) {
			System.err.println(e.toString());
		}
	}
}

//启动程序
public static void main(String[] args) throws Exception {
	ArdunioRemoteMusic main = new ArdunioRemoteMusic();
	main.initialize();
	Thread t=new Thread() {
		public void run() {
			//这里是让程序有足够的时间初始化已经运行
			try {Thread.sleep(1000000);} catch (InterruptedException ie) {}
		}
	};
	t.start();
	System.out.println("Ardunio is Started");
}
}


               2. 中间控制类:


package cn.dxy.action.audio;

public class AudioController {
	
	private static JMFAudio audio ;	
	private static AudioController audioController = new AudioController();
	private AudioController(){
		audio = JMFAudio.getInstance();
		audio.initAudio();
	}
	
	public static AudioController getInstance(){
		return audioController;
	}
	
	public void controller(String msg){
		
		//播放,暂停
		if(msg.equals("pause_start")){
			audio.begin();
		}
		
		//下一首歌
		if(msg.equals("next")){
			audio.nextSong();
			audio.play();
		}
		
		//上一首歌
		if(msg.equals("previouse")){
			audio.previouseSong();
			audio.play();
		}
		
		//增加声音
		if(msg.equals("add")){
			audio.addLevel();
		}
		
		//减少声音
		if(msg.equals("subtract")){
			audio.subtractLevel();
		}
		
		//静音
		if(msg.equals("mute")){
			audio.mute();
		}
		
		//单曲循环
		if(msg.equals("loop")){
			audio.loop();
		}
	}
}


            3. 音乐播放器主类,此处用了JMF

package cn.dxy.action.audio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javax.media.CannotRealizeException;
import javax.media.ControllerEvent;
import javax.media.ControllerListener;
import javax.media.EndOfMediaEvent;
import javax.media.Manager;
import javax.media.NoPlayerException;
import javax.media.Player;
import javax.media.PrefetchCompleteEvent;
import javax.media.StartEvent;
import javax.media.StopEvent;
import javax.media.Time;

import sun.audio.AudioStream;
/**
 * 音乐播放主类
 * @author sam
 *
 */
public class JMFAudio implements ControllerListener {

	private static JMFAudio jmfAudio = new JMFAudio();
	//这里是我本地的音乐地址,你们可以自由替换
	private static String songFile[] = { "e:/wav/login.wav",
			"e:/wav/Adele - Rolling In The Deep.wav",
			"e:/wav/Avril Lavigne - Complicated.wav",
			"e:/wav/Britney Spears - Baby One More Time.wav",
			"e:/wav/Bruno Mars - The Lazy Song.wav",
			"e:/wav/F.I.R - Lydia.wav",
			"e:/wav/Super Junior - Sorry Sorry.wav",
			"e:/wav/Taylor Swift - You Belong With Me.wav",
			"e:/wav/Westlife - My Love.wav",
			"e:/wav/login_last.wav"};

	private File sourceFile;				//音乐地址
	private InputStream inputStream;		// 输入流
	private static Player audioPlayer;		// 播放器
	private boolean loop = false;			// 是否循环
	private boolean autoUnload;				// 自动卸载
	public boolean playState = true;		// 播放还是暂停状态
	private static int curSong = 0; 		// 当前播放歌曲序号
	private static int songLength = 0; 		// 歌曲总数
	private static float curLevel = 0f;		// 当前声音的大小
	private static boolean muteState = false;	//静音状态
	
	private JMFAudio() {
	}

	public static JMFAudio getInstance() {
		System.out.println("init JMFAudio");
		return jmfAudio;
	}

	//初始化
	public void initAudio() {
		songLength = songFile.length;
		load(songFile[0]);
	}

	/**
	 * 通过File 加载歌曲
	 * @param sourceFile
	 */
	public void load(File sourceFile) {// 加载文件
		try {
			if (audioPlayer != null)
				unload();// 如果有正在播放的文件就先卸载播放器
			this.sourceFile = sourceFile;
			audioPlayer = Manager.createRealizedPlayer(sourceFile.toURI()
					.toURL());// 重新建立播放器
			audioPlayer.addControllerListener(this);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

	/**
	 * 通过地址 加载歌曲
	 * @param fileName
	 */
	public void load(String fileName) {// 加载文件
		try {
			if (audioPlayer != null)
				unload();// 如果有正在播放的文件就先卸载播放器
			sourceFile = new File(fileName);
			audioPlayer = Manager.createRealizedPlayer(sourceFile.toURI()
					.toURL());// 重新建立播放器
			curLevel = audioPlayer.getGainControl().getLevel();
			System.out.println("当前音量是:"+curLevel);
			audioPlayer.addControllerListener(this);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
	
	
	public void load() {// 加载文件
		try {
			if (audioPlayer != null)
				unload();// 如果有正在播放的文件就先卸载播放器
			audioPlayer = Manager.createRealizedPlayer(sourceFile.toURI()
					.toURL());// 重新建立播放器
			audioPlayer.addControllerListener(this);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

	public void begin(){
		if(playState){
			play();
		}else{
			pause();
		}
		playState= !playState;
	}
	
	public void play() {// 播放文件
		try {
			audioPlayer.prefetch();
			System.out.println("开始播放:"+songFile[curSong]);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

	public void pause() {// 暂停当前播放
		if (audioPlayer != null)
			audioPlayer.stop();
		System.out.println("暂停播放:"+songFile[curSong]);
	}

	public void stop() {// 停止播放音乐文件
		if (audioPlayer != null) {
			audioPlayer.stop();
			audioPlayer.setMediaTime(new Time(0));//复位JMF播放器对象的开始时间
			System.out.println("停止播放");
		}
	}

	public void unload() {// 卸载播放器
		if (audioPlayer != null) {
			audioPlayer.stop();
			audioPlayer.close();
			audioPlayer = null;
			System.out.println("卸载播放器");
		}
	}

	// 下一首歌
	public void nextSong() {

		if (curSong == songLength - 1) {
			curSong = 0;
		} else {
			curSong = curSong + 1;
		}
		System.out.println("切下一首歌:" + songFile[curSong]);
		load(songFile[curSong]);
	}

	// 上一首歌
	public void previouseSong() {
		if (curSong == 0) {
			curSong = songLength - 1;
		} else {
			curSong = curSong - 1;
		}
		System.out.println("切上一首歌:" + songFile[curSong]);
		load(songFile[curSong]);
	}
	
	//增加声音
	public void addLevel() {
		if(curLevel < 1){
			curLevel += 0.1f;
		}
		if (audioPlayer != null) {
			audioPlayer.getGainControl().setLevel(curLevel);
			System.out.println("增加音量:"+curLevel);
		}
	}

	
	//减少声音
	public void subtractLevel() {
		if(curLevel > 0){
			curLevel -= 0.1f;
		}
		if (audioPlayer != null) {
			audioPlayer.getGainControl().setLevel(curLevel);
			System.out.println("减少音量:"+curLevel);
		}
	}
	
	//静音
	public void mute(){
		if(muteState){
			audioPlayer.getGainControl().setLevel(curLevel);
		}else{
			audioPlayer.getGainControl().setLevel(0);
		}
		muteState = !muteState;
		
	}
	
	//单曲循环
	public void loop(){
		loop = !loop;
		if(loop){
			System.out.println("设置了循环单曲播放");
		}else{
			System.out.println("取消单曲循环播放");
		}
	}
	
	//这个方法很重要,它监听歌曲的状态,比如开始,结束,等等
	public void controllerUpdate(ControllerEvent e) {

		if (e instanceof StartEvent) { // 监听开始播放
		}

		if (e instanceof StopEvent) { // 监听stop播放
			System.out.println("StopEvent");
		}

		if (e instanceof EndOfMediaEvent) { // 监听结束播放
			System.out.println("EndOfMediaEvent");
			if (loop){
				audioPlayer.setMediaTime(new Time(0));//复位JMF播放器对象的开始时间
				audioPlayer.start();
			}else{
				nextSong();
				play();
			}
			return;
		}

		if (e instanceof PrefetchCompleteEvent){
			System.out.println("PrefetchCompleteEvent");
			audioPlayer.start();
		}
	
	}
	
	//初始化,本地测试用
//	public void init() {
//		initAudio();
//		loop = false;
//		play();
//	}
//
//	public static void main(String[] args) throws IOException,
//			NoPlayerException, CannotRealizeException {
//		new JMFAudio().init();
//	}
}

PS:转载时请注明转载地址   http://my.oschina.net/samtribiani/blog/145409


你可能感兴趣的:(java,java,JMF,usb,红外线,ardunio)