---
title: "j2me 一个播放音乐的线程类"
author: "tianmingqi"
date: "2011-07-13T08:37:51Z"
tags: []
categories: ["移动开发"]
slug: "j2me"
draft: false
lastmod: "2011-07-13T08:37:51Z"
id: 1122979
url: "https://tmq.iteye.com/blog/1122979"
---

```
public class MusicThread  implements Runnable{
	InputStream is;
	Player  p;
	/*
	 * @str : 音乐文件
	 */
	public MusicThread(String str){
		is = this.getClass().getResourceAsStream(str);
		try {
			p = Manager.createPlayer(is,"audio/midi");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MediaException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    
	}
	/*
	 * 线程启动自动播放
	 * @see java.lang.Runnable#run()
	 */
	public void run() {
		try {
			p.prefetch();
			p.start();
		} catch (MediaException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void startMusic(){
		if(p!=null){
			try {
				p.start();
			} catch (MediaException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	public void stopMusic(){
		try {
			p.stop();
			p.close();
			p=null;
			
		} catch (MediaException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
```