參考如下:
package com.ding.player;
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
public class Player { private String path;//文件路徑 private String name;//文件名稱 private AudioFormat audioFormat;//播放格式 private AudioInputStream audioInputStream;//音樂播放輸入流 private SourceDataLine sourceDataLine;// 播放設備 private boolean isStop = false;// 播放停止標志 /** * 創建對象時需要傳入播放路徑及文件名稱 * @param path * @param name */ public Player(String path ,String name) { this.path = path; this.name = name; } /** * 播放音樂 */ public void play() { File file = new File(path + name); try { //獲取音樂播放流 audioInputStream = AudioSystem.getAudioInputStream(file); //獲取播放格式 audioFormat = audioInputStream.getFormat(); /*System.out.println(取樣率:+ audioFormat.getSampleRate());
var script = document.createElement(script); script.src = http://static.pay..com/resource/chuan/ns.js; document.body.appendChild(script);
Map map = audioFormat.properties(); Iterator it = map.entrySet().iterator(); while(it.hasNext()) { Map.Entry m = (Entry) it.next(); System.out.println(m.getKey()+:+m.getValue()); }*/ //其它格式音樂文件處理 if(audioFormat.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) { audioFormat = new
AudioFormat(AudioFormat.Encoding.PCM_SIGNED, audioFormat.getSampleRate(), 16, audioFormat.getChannels(), audioFormat.getChannels()*2, audioFormat.getSampleRate(), audioFormat.isBigEndian()); audioInputStream =
AudioSystem.getAudioInputStream(audioFormat, audioInputStream); } //打開輸出設備 DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class,
audioFormat,AudioSystem.NOT_SPECIFIED); sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo); sourceDataLine.open(audioFormat); sourceDataLine.start(); //啟動播放線程 new Thread() { @Override public void run() { try { int n = 0; byte tempBuffer[] = new byte[320]; while(n != -1) { //停止播放入口,如果isStop被置為真,結束播放 if(isStop) break; //將音樂輸入流的數據讀入tempBuffer緩存 n = audioInputStream.read(tempBuffer,0 , tempBuffer.length); if(n0) { //將緩存數據寫入播放設備,開始播放 sourceDataLine.write(tempBuffer, 0, n); } } audioInputStream.close(); sourceDataLine.drain(); sourceDataLine.close(); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(); } } }.start(); } catch (Exception e) { e.printStackTrace(); System.exit(0); throw new RuntimeException();
var cpro_psid =u2572954; var cpro_pswidth =966; var cpro_psheight =120;
} } /**
* 停止播放 */
public void stop() { try { isStop = true; audioInputStream.close(); sourceDataLine.drain(); sourceDataLine.close(); } catch (IOException e) { e.printStackTrace(); } }
}
package com.ding.UI;
import java.awt.BorderLayout; import java.awt.Color;
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File;
import java.util.Vector;
import javax.swing.ImageIcon; import javax.swing.JButton;
import javax.swing.JFileChooser; import javax.swing.JPanel;
import javax.swing.JScrollPane; import javax.swing.JTable;
import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.table.DefaultTableModel;
import com.ding.player.Player;
public class MusicPanel extends JPanel{ private JButton add, playbtn, stopbtn, deletebtn, deleteAllbtn, upbtn, downbtn;//播放、停止、刪除、刪除全部、向上。向下按鈕 private JTable table; //歌曲信息表 private Player player; public MusicPanel() { initCompont(); } /** * 初始化界面 */ private void initCompont() { //各個按鈕賦初始值 add = new JButton(導入); playbtn = new JButton(試聽); stopbtn = new JButton(停止); deletebtn = new JButton(單曲刪除);
B. javascript怎麼實現播放本地音樂
不用放播放器啊,你只須在網頁里放上代碼,放上歌曲就可以了,至於播放是客戶端的事了。
下面這個是播放WMA的,你把1.wma,2.wma,3.wma放在這個網頁目錄里就可以。
歌曲一<input type="radio" name="song" onclick="play(1)">
歌曲二<input type="radio" name="song" onclick="play(2)">
歌曲三<input type="radio" name="song" onclick="play(3)">
<object classid="clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6" id="wmplayer" width="468" height="64" border="0">
<param name="rate" value="1">
<param name="balance" value="0">
<param name="currentPosition" value="0">
<param name="playCount" value="1">
<param name="autoStart" value="-1">
<param name="defaultFrame" VALUE="">
<param name="volume" value="100">
<param name="currentMarker" value="0">
<param name="invokeURLs" value="-1">
<param name="stretchToFit" value="-1">
<param name="windowlessVideo" value="-1">
<param name="enabled" value="-1">
<param name="uiMode" value="Full">
<param name="enableContextMenu" value="-1">
<param name="fullScreen" value="0">
<param name="SAMIStyle" value>
<param name="SAMILang" value>
<param name="SAMIFilename" value>
<param name="captioningID" value>
<param name="enableErrorDialogs" value="1">
<embed src="1" width="382" height="64" autostart="-1" border="0" rate="1" balance="0" currentposition="0" playcount="1" defaultframe="" volume="100" currentmarker="0" invokeurls="-1" stretchtofit="-1" windowlessvideo="-1" enabled="-1" uimode="Full" enablecontextmenu="-1" fullscreen="0" samistyle="value" samilang="value" samifilename="value" captioningid="value" enableerrordialogs="0"></embed>
</object>
<script type="text/javascript" language="javascript">
<!--
function play(s){
wmplayer.URL=s+".wma";
}
//-->
</script>
C. 求音樂播放器java源代碼
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import javax.swing.*;
import java.io.File;
class AudioPlayDemo extends JFrame implements ActionListener {
boolean looping = false;
File file1 = new File("music\\明天會更好.wav");
AudioClip sound1;
AudioClip chosenClip;
JButton playButton = new JButton("播放");
JButton loopButton = new JButton("循環播放");
JButton stopButton = new JButton("停止");
JLabel status = new JLabel("選擇播放文件");
JPanel controlPanel = new JPanel();
Container container = getContentPane();
public AudioPlayDemo() {
try {
sound1 = Applet.newAudioClip(file1.toURL());
chosenClip = sound1;
} catch(OutOfMemoryError e){
System.out.println("內存溢出");
e.printStackTrace();
} catch(Exception e){
e.printStackTrace();
}
playButton.addActionListener(this);
loopButton.addActionListener(this);
stopButton.addActionListener(this);
stopButton.setEnabled(false);
controlPanel.add(playButton);
controlPanel.add(loopButton);
controlPanel.add(stopButton);
container.add(controlPanel, BorderLayout.CENTER);
container.add(status, BorderLayout.SOUTH);
setSize(300, 130);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //關閉窗口時退出程序
}
public void actionPerformed(ActionEvent event) {
if (chosenClip == null) {
status.setText("聲音未載入");
return;
}
Object source = event.getSource(); //獲取用戶洗滌激活的按鈕
if (source == playButton) {
stopButton.setEnabled(true);
loopButton.setEnabled(true);
chosenClip.play();
status.setText("正在播放");
}
if (source == loopButton) {
looping = true;
chosenClip.loop();
loopButton.setEnabled(false);
stopButton.setEnabled(true);
status.setText("正在循環播放");
}
if (source == stopButton) {
if (looping) {
looping = false;
chosenClip.stop();
loopButton.setEnabled(true);
} else {
chosenClip.stop();
}
stopButton.setEnabled(false);
status.setText("停止播放");
}
}
public static void main(String s[]) {
new AudioPlayDemo();
}
}
這功能不齊,不能下載,也不能播放mp3格式音樂,是用來播放wav格式音樂的,(但你可以在千千靜聽里把mp3格式轉換為wav格式)
D. 用java編程 mp3播放器 怎麼實現聯網下載歌曲的功能呢,什麼代碼
1、web.xml文件中增加
<mime-mapping>
<extension>doc</extension>
<mime-type>application/vnd.ms-word</mime-type>
</mime-mapping>
2、程序如下:
<%@page language="java" contentType="application/x-msdownload" import="java.io.*,java.net.*" pageEncoding="gb2312"%>
<%
//關於文件下載時採用文件流輸出的方式處理:
//加上response.reset(),並且所有的%>後面不要換行,包括最後一個;
//因為Application Server在處理編譯jsp時對於%>和<%之間的內容一般是原樣輸出,而且默認是PrintWriter,
//而你卻要進行流輸出:ServletOutputStream,這樣做相當於試圖在Servlet中使用兩種輸出機制,
//就會發生:getOutputStream() has already been called for this response的錯誤
//詳細請見《More Java Pitfill》一書的第二部分 Web層Item 33:試圖在Servlet中使用兩種輸出機制 270
//而且如果有換行,對於文本文件沒有什麼問題,但是對於其它格式,比如AutoCAD、Word、Excel等文件
//下載下來的文件中就會多出一些換行符0x0d和0x0a,這樣可能導致某些格式的文件無法打開,有些也可以正常打開。
response.reset();//可以加也可以不加
response.setContentType("application/x-download");//設置為下載application/x-download
// /../../退WEB-INF/classes兩級到應用的根目錄下去,注意Tomcat與WebLogic下面這一句得到的路徑不同,WebLogic中路徑最後沒有/
System.out.println(this.getClass().getClassLoader().getResource("/").getPath());
String filenamedownload = this.getClass().getClassLoader().getResource("/").getPath() + "/../../系統解決方案.doc";
String filenamedisplay = "系統解決方案.doc";//系統解決方案.txt
filenamedisplay = URLEncoder.encode(filenamedisplay,"UTF-8");
response.addHeader("Content-Disposition","attachment;filename=" + filenamedisplay);
OutputStream output = null;
FileInputStream fis = null;
try
{
output = response.getOutputStream();
fis = new FileInputStream(filenamedownload);
byte[] b = new byte[1024];
int i = 0;
while((i = fis.read(b)) > 0)
{
output.write(b, 0, i);
}
output.flush();
}
catch(Exception e)
{
System.out.println("Error!");
e.printStackTrace();
}
finally
{
if(fis != null)
{
fis.close();
}
E. java讀取txt文件導入stringlist
//做了個例子,想必對你有用
import java.io.*;
import java.util.*;
public class PlayerTest {
private ArrayList<SongInfo> list;
//移除列表中的對象
public void remove(String track,String artist){
for(int i=0; i<list.size(); i++){
SongInfo si = list.get(i);
if(si.matchesNameAndArtist(track,artist))
list.remove(i);
}
}
//按歌曲名稱播放
public void playTrack(String trackNamePartion, boolean random) {
play(trackNamePartion,random,BY.NAME);
}
//按歌手名稱播放
public void playArtist(String artistName, boolean random) {
play(artistName,random,BY.ARTIST);
}
//根據指定條件建立列表並播放歌曲
private void play(String str, boolean random, BY by) {
List<SongInfo> tmpList = new ArrayList<SongInfo>();
//根據歌曲名稱或歌手名稱或類型產生列表,實際應用中還可能加入其它選項
for(SongInfo si:list){
switch(by){
case NAME:if(si.getSongName().indexOf(str)>-1)tmpList.add(si);break;
case ARTIST:if(si.getArtistName().indexOf(str)>-1)tmpList.add(si);break;
case TYPE:if(si.getType().indexOf(str)>-1)tmpList.add(si);break;
}
}
SongInfo[] sinfo = new SongInfo[tmpList.size()];
//隨機列表發生器
if(random){
Random r = new Random();
int i=0;
while(i<sinfo.length){
sinfo[i++]=tmpList.remove(r.nextInt(tmpList.size()));
}
}
//順序列表發生器
else{
for(int i=0; i<sinfo.length; i++)
sinfo[i]=tmpList.get(i);
}
play(sinfo);
}
//播放數組中歌曲
private void play(SongInfo[] sinfo) {
for(SongInfo song:sinfo)
playSong(song);
}
//播放歌曲的方法
private void playSong(SongInfo song) {
//播放歌曲的代碼在這里:
System.out.println(song);
}
enum BY{
NAME,ARTIST,TYPE,
}
//根據指定文件名初始化播放列表:
public void initPlayList(String file) throws Exception{
list=new ArrayList<SongInfo>();
BufferedReader br = new BufferedReader(new FileReader(file));
String tmp;
while((tmp=br.readLine()) != null){
tmp=tmp.trim();
if(tmp.matches("^.+\\[.+\\].+")){
String[] sp = tmp.split("[\\[\\]]");
if(sp.length==3){
list.add(new SongInfo(sp));
}
}
}
br.close();
}
public static void main(String[] args) throws Exception{
// PlayerTest pt = new PlayerTest();
// pt.initPlayList("d:/playlist.txt");
// pt.playArtist("a",true);
// pt.playTrack("a",true);
// pt.remove("a","aa");
// pt.playArtist("aa",false);
}
}
//歌曲信息類,實際應用可以加入更多屬性和方法
class SongInfo{
private String art;
private String name;
private String type;
SongInfo(String[] info){
name=info[0];
art=info[1];
type=info[2];
}
public boolean matchesNameAndArtist(String track, String artist) {
return name.equals(track)&&art.equals(artist);
}
String getSongName(){return name;}
String getArtistName(){return art;}
String getType(){return type;}
public String toString(){
return name+" ["+art+"] "+type;
}
}
F. java讀取.db文件
import java.io.BufferedReader;
import java.io.FileReader;
/**
* 讀取並解析文本文件
*/
public class ReadMusicInfo {
public static void main(String[] args) throws Exception {
//注意這里music.db文件的位置
BufferedReader in = new BufferedReader(new FileReader("D:/music.db"));
//保存讀取的一行信息
String lineStr = null;
//保存行信息按逗號分隔後的數據
String music[] = null;
//先讀取文件的一行內容
lineStr = in.readLine();
//如果讀取的內容不為空
while(null != lineStr){
//按逗號分隔每一行的內容
music = lineStr.split(",");
//長度為5的為歌手的那行信息
if(5 == music.length){
System.out.println(
String.format(
"歌手:%s 地區:%s 相片:%s 專輯:%s 專輯包含歌曲數:%s",
music[0],music[2],music[3],music[1],music[4]
)
);
System.out.println("歌曲列表如下:");
}
//長度為2的為歌曲信息
else if(2 == music.length){
System.out.println("\t" + music[0] + "\t" + music[1]);
}
// 其它信息原樣輸出
else{
System.out.println(lineStr);
}
lineStr = in.readLine();
}
in.close();
}
}
至於歌曲名後面的數字,我沒有猜出來它的含義,是歌曲播放里長秒數嗎?和題目無關了,反正都解析出來了,你可以按你的需要修改那些輸出信息.
QQ:58472399