java寫的音頻播放器(JAVA播放器)

本文目錄一覽:

如何用java做一個音樂播放器?

看看其它網友的答案:

首先下載播放mp3的包,比如mp3spi1.9.4.jar。在工程中添加這個包。

播放器演示代碼如下

package com.test.audio;

import java.io.File;

import java.awt.BorderLayout;

import java.awt.FileDialog;

import java.awt.Frame;

import java.awt.GridLayout;

import java.awt.Label;

import java.awt.List;

import java.awt.Menu;

import java.awt.MenuBar;

import java.awt.MenuItem;

import java.awt.MenuShortcut;

import java.awt.Panel;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.KeyEvent;

import java.awt.event.MouseAdapter;

import java.awt.event.MouseEvent;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

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 MusicPlayer extends Frame {

/**

*

*/

private static final long serialVersionUID = -2605658046194599045L;

boolean isStop = true;// 控制播放線程

boolean hasStop = true;// 播放線程狀態

String filepath;// 播放文件目錄

String filename;// 播放文件名稱

AudioInputStream audioInputStream;// 文件流

AudioFormat audioFormat;// 文件格式

SourceDataLine sourceDataLine;// 輸出設備

List list;// 文件列表

Label labelfilepath;//播放目錄顯示標籤

Label labelfilename;//播放文件顯示標籤

public MusicPlayer() {

// 設置窗體屬性

setLayout(new BorderLayout());

setTitle(“MP3 Music Player”);

setSize(350, 370);

// 建立菜單欄

MenuBar menubar = new MenuBar();

Menu menufile = new Menu(“File”);

MenuItem menuopen = new MenuItem(“Open”, new MenuShortcut(KeyEvent.VK_O));

menufile.add(menuopen);

menufile.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

open();

}

});

menubar.add(menufile);

setMenuBar(menubar);

// 文件列表

list = new List(10);

list.addMouseListener(new MouseAdapter() {

public void mouseClicked(MouseEvent e) {

// 雙擊時處理

if (e.getClickCount() == 2) {

// 播放選中的文件

filename = list.getSelectedItem();

play();

}

}

});

add(list, “Center”);

// 信息顯示

Panel panel = new Panel(new GridLayout(2, 1));

labelfilepath = new Label(“Dir:”);

labelfilename = new Label(“File:”);

panel.add(labelfilepath);

panel.add(labelfilename);

add(panel, “North”);

// 註冊窗體關閉事件

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

setVisible(true);

}

// 打開

private void open() {

FileDialog dialog = new FileDialog(this, “Open”, 0);

dialog.setVisible(true);

filepath = dialog.getDirectory();

if (filepath != null) {

labelfilepath.setText(“Dir:” + filepath);

// 顯示文件列表

list.removeAll();

File filedir = new File(filepath);

File[] filelist = filedir.listFiles();

for (File file : filelist) {

String filename = file.getName().toLowerCase();

if (filename.endsWith(“.mp3”) || filename.endsWith(“.wav”)) {

list.add(filename);

}

}

}

}

// 播放

private void play() {

try {

isStop = true;// 停止播放線程

// 等待播放線程停止

System.out.print(“Start:” + filename);

while (!hasStop) {

System.out.print(“.”);

try {

Thread.sleep(10);

} catch (Exception e) {

}

}

System.out.println(“”);

File file = new File(filepath + filename);

labelfilename.setText(“Playing:” + filename);

// 取得文件輸入流

audioInputStream = AudioSystem.getAudioInputStream(file);

audioFormat = audioInputStream.getFormat();

// 轉換mp3文件編碼

if (audioFormat.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {

audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,

audioFormat.getSampleRate(), 16, audioFormat

.getChannels(), audioFormat.getChannels() * 2,

audioFormat.getSampleRate(), false);

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();

// 創建獨立線程進行播放

isStop = false;

Thread playThread = new Thread(new PlayThread());

playThread.start();

} catch (Exception e) {

e.printStackTrace();

}

}

class PlayThread extends Thread {

byte tempBuffer[] = new byte[320];

public void run() {

try {

int cnt;

hasStop = false;

// 讀取數據到緩存數據

while ((cnt = audioInputStream.read(tempBuffer, 0,

tempBuffer.length)) != -1) {

if (isStop)

break;

if (cnt 0) {

// 寫入緩存數據

sourceDataLine.write(tempBuffer, 0, cnt);

}

}

// Block等待臨時數據被輸出為空

sourceDataLine.drain();

sourceDataLine.close();

hasStop = true;

} catch (Exception e) {

e.printStackTrace();

System.exit(0);

}

}

}

public static void main(String args[]) {

new MusicPlayer();

}

}

求用java編寫MP3播放器

這個需要jmf的相關包,去網上下載下,給你寫了個例子

public class TestPlay extends JFrame {

private Component vc, cc;

private JButton file = new JButton(“file”);

private Player player = null;

public TestPlay() throws HeadlessException, NoPlayerException, MalformedURLException, IOException {

this.add(file);

file.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent arg0) {

JFileChooser f = new JFileChooser();

if(f.showOpenDialog(null)==JFileChooser.CANCEL_OPTION)return;

try {

player = Manager.createPlayer(f.getSelectedFile().toURL());

player.addControllerListener(new ControllerListener() {

public void controllerUpdate(ControllerEvent arg0) {

controllerUpdateImp(arg0);

}

});

player.prefetch();

} catch (Exception e) {

System.out.println(e);

JOptionPane.showMessageDialog(null, e.getMessage());

}

}

});

}

public void controllerUpdateImp(ControllerEvent e) {

if (e instanceof EndOfMediaEvent) {

player.setMediaTime(new Time(0));

player.start();

} else if (e instanceof PrefetchCompleteEvent) {

player.start();

} else if (e instanceof RealizeCompleteEvent) {

vc = player.getVisualComponent();

if (vc != null) this.add(vc, BorderLayout.CENTER);

cc = player.getControlPanelComponent();

if (cc != null) this.add(cc, BorderLayout.SOUTH);

this.pack();

this.setResizable(false);

this.setVisible(true);

} else if (e instanceof ControllerClosedEvent) {

System.exit(0);

}

}

public static void main(String[] args) {

TestPlay t;

try {

t = new TestPlay();

t.setDefaultCloseOperation(t.EXIT_ON_CLOSE);

t.pack();

t.setLocationRelativeTo(null);

t.setVisible(true);

} catch (Exception e) {

JOptionPane.showMessageDialog(null, e.getMessage());

}

}

}

怎麼用Java寫一個簡單的mp3播放器,用外部包

作業其實還是自己寫的好。要用到JMF包啊,到網上下載一個JMF包,照著說明安裝上。

以下是我寫的一個很簡單的播放器,只能播放mp3,mpeg,mpg,wav等簡單的格式。

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import javax.media.ControllerEvent;

import javax.media.ControllerListener;

import javax.media.MediaLocator;

import javax.media.RealizeCompleteEvent;

import javax.media.bean.playerbean.MediaPlayer;

import javax.swing.JPanel;

import javax.swing.JFrame;

import javax.swing.SwingUtilities;

import javax.swing.JList;

import java.awt.BorderLayout;

import javax.swing.JSplitPane;

import java.awt.Component;

import java.util.Vector;

public class JMF_T extends JFrame implements ControllerListener, ActionListener {

MediaPlayer Player;

private String filename = “”;

private static final long serialVersionUID = 1L;

private Vector vct = new Vector(); // @jve:decl-index=0:

private JPanel jContentPane = null;

private JSplitPane jSplitPane = null;

private JPanel playPanel = null;

private JList jList = null;

private JSplitPane getJSplitPane() {

if (jSplitPane == null) {

jSplitPane = new JSplitPane();

jSplitPane.setDividerSize(5);

jSplitPane.setResizeWeight(0.8);

jSplitPane.setRightComponent(getJList());

jSplitPane.setLeftComponent(getPlayPanel());

}

return jSplitPane;

}

private JPanel getPlayPanel() {

if (playPanel == null) {

playPanel = new JPanel();

playPanel.setLayout(new BorderLayout());

}

return playPanel;

}

private JList getJList() {

if (jList == null) {

jList = new JList();

jList.addMouseListener(new java.awt.event.MouseAdapter() {

public void mouseClicked(java.awt.event.MouseEvent e) {

// TODO Auto-generated Event stub mouseClicked()

if (e.getClickCount() == 1) {

String str = (String) jList.getSelectedValue();

if (str == null) {

return;

}

filename = str;

System.out.println(str);

}

if (e.getClickCount() == 2) {

String str = (String) jList.getSelectedValue();

if (str == null) {

return;

}

filename = str;

play();

}

}

});

}

return jList;

}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {

JMF_T thisClass = new JMF_T();

thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

thisClass.setVisible(true);

}

});

}

public JMF_T() {

initialize();

}

private void OpenFile() {

FileDialog fd = new FileDialog(this, “Choose Video”, FileDialog.LOAD);

fd.setVisible(true);

filename = fd.getDirectory() + fd.getFile();

System.out.println(filename);

if (filename.equals(“”)) {

return;

} else if (filename.equals(“nullnull”)) {

return;

}

boolean j = false;

for (int i = 0; i vct.size(); i++) {

if (vct.get(i).toString().equals(filename)) {

j = true;

break;

}

}

if (j == false) {

vct.add(filename);

jList.setListData(vct);

}

}

private void stop() {

if (Player != null) {

Player.stop();

Player.deallocate();

}

}

private void play() {

try {

if (filename.equals(“”)) {

return;

}

if (Player == null) {

Player = new MediaPlayer();

} else {

closePreviosPlayer();

}

Player.setMediaLocator(new MediaLocator(“” + filename));

Player.addControllerListener(this);

Player.realize();

Player.start();

} catch (Exception e) {

}

}

public void actionPerformed(ActionEvent e) {

String action = e.getActionCommand().toString();

if (action.equals(“Open”)) {

OpenFile();

}

if (action.equals(“Play”)) {

play();

}

if (action.equals(“Stop”)) {

stop();

}

if (action.equals(“Exit”)) {

dispose();

System.exit(0);

}

}

private void initialize() {

this.setSize(500, 350);

setLocation(300, 100);

this.setContentPane(getJContentPane());

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

dispose();

System.exit(0);

}

});

MenuBar mb = new MenuBar();

setMenuBar(mb);

Menu fileMenu = new Menu(“File”);

Menu actMenu = new Menu(“Action”);

mb.add(fileMenu);

mb.add(actMenu);

MenuItem itemOpen = new MenuItem(“Open”);

itemOpen.addActionListener(this);

fileMenu.add(itemOpen);

fileMenu.addSeparator();

MenuItem itemPlay = new MenuItem(“Play”);

itemPlay.addActionListener(this);

actMenu.add(itemPlay);

actMenu.addSeparator();

MenuItem itemStop = new MenuItem(“Stop”);

itemStop.addActionListener(this);

actMenu.add(itemStop);

MenuItem itemExit = new MenuItem(“Exit”);

itemExit.addActionListener(this);

fileMenu.add(itemExit);

this.validate();

this.setVisible(true);

}

private JPanel getJContentPane() {

if (jContentPane == null) {

jContentPane = new JPanel();

jContentPane.setLayout(new BorderLayout());

jContentPane.add(getJSplitPane(), BorderLayout.CENTER);

}

return jContentPane;

}

private void closePreviosPlayer() {

if (Player == null)

return;

Player.stop();

Player.deallocate(); // 停止播放並且重新裝載DateSource

Component visual = Player.getVisualComponent();

Component control = Player.getControlPanelComponent();

if (visual != null) {

playPanel.remove(visual);

}

if (control != null) {

playPanel.remove(control);

}

}

public synchronized void controllerUpdate(ControllerEvent event) {

if (event instanceof RealizeCompleteEvent) {

Component comp;

if ((comp = Player.getControlPanelComponent()) != null) {

playPanel.add(“South”, comp);

} else {

closePreviosPlayer();

}

if ((comp = Player.getVisualComponent()) != null) {

playPanel.add(“Center”, comp);

}

validate();

}

}

}

如何用Java來編寫一個音樂播放器

首先要在環境電腦中安裝下JMF環境,才能引入javax.sound.sampled.*這個包,一下是用過的代碼

package TheMusic;

import java.io.*;

import javax.sound.sampled.*;

public class Music {

public static void main(String[] args) {

// TODO Auto-generated method stub

//修改你的音樂文件路徑就OK了

AePlayWave apw=new AePlayWave(“突然好想你.wav”);

apw.start();

}

}

在程序中實例化這個類,啟動線程,實例化的時候參照Test修改路徑就OK播放聲音的類

Java代碼

public class AePlayWave extends Thread {

private String filename;

public AePlayWave(String wavfile) {

filename = wavfile;

}

public void run() {

File soundFile = new File(filename);

AudioInputStream audioInputStream = null;

try {

audioInputStream = AudioSystem.getAudioInputStream(soundFile);

} catch (Exception e1) {

e1.printStackTrace();

return;

}

AudioFormat format = audioInputStream.getFormat();

SourceDataLine auline = null;

DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);

try {

auline = (SourceDataLine) AudioSystem.getLine(info);

auline.open(format);

} catch (Exception e) {

e.printStackTrace();

return;

}

auline.start();

int nBytesRead = 0;

byte[] abData = new byte[512];

try {

while (nBytesRead != -1) {

nBytesRead = audioInputStream.read(abData, 0, abData.length);

if (nBytesRead = 0)

auline.write(abData, 0, nBytesRead);

}

} catch (IOException e) {

e.printStackTrace();

return;

} finally {

auline.drain();

auline.close();

}

}

}

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/199043.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-04 19:14
下一篇 2024-12-04 19:14

相關推薦

  • Java JsonPath 效率優化指南

    本篇文章將深入探討Java JsonPath的效率問題,並提供一些優化方案。 一、JsonPath 簡介 JsonPath是一個可用於從JSON數據中獲取信息的庫。它提供了一種DS…

    編程 2025-04-29
  • java client.getacsresponse 編譯報錯解決方法

    java client.getacsresponse 編譯報錯是Java編程過程中常見的錯誤,常見的原因是代碼的語法錯誤、類庫依賴問題和編譯環境的配置問題。下面將從多個方面進行分析…

    編程 2025-04-29
  • Java騰訊雲音視頻對接

    本文旨在從多個方面詳細闡述Java騰訊雲音視頻對接,提供完整的代碼示例。 一、騰訊雲音視頻介紹 騰訊雲音視頻服務(Cloud Tencent Real-Time Communica…

    編程 2025-04-29
  • Java Bean載入過程

    Java Bean載入過程涉及到類載入器、反射機制和Java虛擬機的執行過程。在本文中,將從這三個方面詳細闡述Java Bean載入的過程。 一、類載入器 類載入器是Java虛擬機…

    編程 2025-04-29
  • Java Milvus SearchParam withoutFields用法介紹

    本文將詳細介紹Java Milvus SearchParam withoutFields的相關知識和用法。 一、什麼是Java Milvus SearchParam without…

    編程 2025-04-29
  • Java 8中某一周的周一

    Java 8是Java語言中的一個版本,於2014年3月18日發布。本文將從多個方面對Java 8中某一周的周一進行詳細的闡述。 一、數組處理 Java 8新特性之一是Stream…

    編程 2025-04-29
  • Java判斷字元串是否存在多個

    本文將從以下幾個方面詳細闡述如何使用Java判斷一個字元串中是否存在多個指定字元: 一、字元串遍歷 字元串是Java編程中非常重要的一種數據類型。要判斷字元串中是否存在多個指定字元…

    編程 2025-04-29
  • VSCode為什麼無法運行Java

    解答:VSCode無法運行Java是因為默認情況下,VSCode並沒有集成Java運行環境,需要手動添加Java運行環境或安裝相關插件才能實現Java代碼的編寫、調試和運行。 一、…

    編程 2025-04-29
  • Java任務下發回滾系統的設計與實現

    本文將介紹一個Java任務下發回滾系統的設計與實現。該系統可以用於執行複雜的任務,包括可回滾的任務,及時恢復任務失敗前的狀態。系統使用Java語言進行開發,可以支持多種類型的任務。…

    編程 2025-04-29
  • Java 8 Group By 會影響排序嗎?

    是的,Java 8中的Group By會對排序產生影響。本文將從多個方面探討Group By對排序的影響。 一、Group By的概述 Group By是SQL中的一種常見操作,它…

    編程 2025-04-29

發表回復

登錄後才能評論