⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mp3encode.java~

📁 java桌球游戏java桌球游戏java桌球游戏java桌球游戏
💻 JAVA~
字号:
import javax.swing.*;
import java.io.*;
import javax.sound.sampled.*;
import javax.sound.midi.*;
import java.awt.*;
import java.awt.event.*;
import javax.sound.sampled.AudioFormat.Encoding;
import java.util.*;

public class Mp3Encode implements Runnable {

	public String filename;
	public AudioInputStream stream;
	public SourceDataLine playLine;
	public AudioFormat baseFormat;
	public long currentByte = 0;
	public int numThread = 0;
	public int numBytesRead = -1;
	public int bufferSize;
	private FileInputStream in;

	public Mp3Encode(String name) {
		filename = name;	
	}
	
	private void getFormat(String filename) {
		try {
			stream = AudioSystem.getAudioInputStream(
					new File(filename));
		} catch (Exception e) {
			e.printStackTrace();
		}
		baseFormat = stream.getFormat();
		int fIndex = filename.lastIndexOf(".");
		String extend = filename.substring(fIndex + 1);
		if ( extend.equalsIgnoreCase("wav") ) {
			baseFormat = decodingMusic(baseFormat);
		}		
	}

	private AudioFormat decodingMusic(AudioFormat format) {
		AudioFormat decodedFormat = new AudioFormat(
			AudioFormat.Encoding.PCM_SIGNED,
			format.getSampleRate(), format.getSampleSizeInBits(),
			format.getChannels(), format.getFrameSize(),
			format.getFrameRate(), format.isBigEndian()
		);
		return decodedFormat;
	}

	private SourceDataLine getLine(AudioFormat f) {
		RandomAccessFile source = null;
		try {
			source = new RandomAccessFile(filename, "r");
		} catch (Exception e) {
			e.printStackTrace();
		}
		SourceDataLine line = null;
		DataLine.Info info = new DataLine.Info(SourceDataLine.class, f);
		bufferSize = baseFormat.getFrameSize() * Math.round(
				baseFormat.getSampleRate() / 10);
		byte[] buffer = new byte[bufferSize];
		try {
			line = (SourceDataLine)AudioSystem.getLine(info);
			line.open(f, bufferSize);
		} catch (LineUnavailableException e) {
			e.printStackTrace();
		}
		line.start();

		try {
			if ( numBytesRead == -1 ) {
				currentByte = buffer.length;
				numBytesRead = 0;
			}
			source.seek(currentByte);
			while ( (numBytesRead != -1) ) {
				numBytesRead = source.read(buffer, 0, buffer.length);
				currentByte += numBytesRead;
				if ( numBytesRead != -1 ) {
					line.write(buffer, 0, numBytesRead);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return line;

	}
	
	public void run() {
		play();
	}

	public synchronized void play() {
		getFormat(filename);
		playLine = getLine(baseFormat);
		playLine.close();

	}


	// 这边涉及单元测试的, 一种技巧
/*
 * 	public static void main(String args[]) {
		new Thread(new Mp3Encode("resource/bomb.wav")).start();
	}
       	*/

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -