Tải bản đầy đủ (.pdf) (14 trang)

Báo cáo Nhập môn Java

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (287.2 KB, 14 trang )

TRƯỜNG ĐẠI HỌC BÁCH KHOA HÀ NỘI
VIỆN ĐÀO TẠO QUỐC TẾ

BÁO CÁO VỀ
XỬ LÝ BÀN PHÍM , CHUỘT VÀ ÂM THANH
TRONG JAVA

Họ tên sinh viên:HOÀNG VĂN KIÊN
MSSV: 20158204
Lớp:LTU14


MỤC LỤC
MỤC LỤC ............................................................................................................................. 1
Phần 1. SƠ LƯỢC CHUNG VỀ XỬ LÝ SỰ KIỆN ............................................................. 2
Phần 2. XỬ LÝ SỰ KIỆN BÀN PHÍM ................................................................................ 4
Phần 3. XỬ LÝ SỰ KIỆN CHUỘT ...................................................................................... 6
Phần 4. XỬ LÝ ÂM THANH ............................................................................................... 9

1


Phần 1.SƠ LƯỢC CHUNG VỀ XỬ LÝ SỰ KIỆN
Mô hình xử lý sự kiện (Event- handling Model):
Ở một phần nào đó chúng ta chỉ đề cập đến vấn đề thiết kế giao diện chương trình ứng
dụng mà chưa đề cập đến vấn đề xử lý sự kiện. Những sự kiện được phát sinh khi người
dùng tương tác với giao diện chương trình GUI (Graphical User Interface: Giao diện đồ
họa người dùng). Những tương tác thường gặp như: di chuyển, nhấn chuột, nhấn một nút
nhấn, chọn một MenuItem trong hệ thống thực đơn, nhập dữ liệu trong một ô văn bản,
đóng cửa sổ ứng dụng, … Khi có một tương tác xảy ra thì một sự kiện được gởi đến
chương trình. Thông tin về sự kiện thường được lưu trữ trong một đối tượng dẫn xuất từ


lớp AWTEvent( Abstract Windowing Toolkit Event). Những kiểu sự kiện trong gói
java.awt.event có thể dùng cho cả những component AWT và JFC. Đối với thư viện JFC
thì có thêm những kiểu sự kiện mới trong gói java.swing.event (ở đây ta không đề cập
đến).
Ba thành phần chính của mô hình:
• Nguồn phát sinh sự kiện (Event source): nguồn gây ra sự kiện, thường là các thành
phần GUI trong chương trình, là thành phần của giao diện mà người dùng tác động.
• Sự kiện (Event object): Tóm tắt thông tin về xử kiện xảy ra, bao gồm tham chiếu
đến nguồn gốc phát sinh sự kiện và thông tin sự kiện sẽ gởi đến cho bộ lắng nghe
xử lý.
• Bộ lắng nghe(Event listener):Một bộ lắng nghe là một đối tượng của một lớp hiện
thực một hay nhiều interface của gói java.awt.event . Khi được thông báo, bộ lắng
nghe nhận sự kiện và xử lý. Nguồn phát sinh sự kiện phải cung cấp những phương
thức để đăng ký hoặc hủy bỏ một bộ lắng nghe. Nguồn phát sinh sự kiện luôn phải
gắn với một bộ lắng nghe, và nó sẽ thông báo với bộ lắng nghe đó khi có sự kiện
phát sinh đó.

Như vậy người lập trình cần làm hai việc:
• Tạo và đăng ký một bộ lắng nghe cho một component trên GUI.
• Cài đặt các phương thức quản lý và xử lý sự kiện.

2


Một đối tượng Event-Listener lắng nghe những sự kiện khác nhau phát sinh từ các
components của giao diện chương trình. Với mỗi sự kiện khác nhau phát sinh thì phương
thức tương ứng trong những Event-Listener sẽ được gọi thực hiện. Mỗi interface EventListener gồm một hay nhiều các phương thức mà chúng cần cài đặt trong các lớp hiện thực
(implements) interface đó. Những phương thức trong các interface là trừu tượng vì vậy lớp
(bộ lắng nghe) nào hiện thực các interface thì phải cài đặt tất cả những phương thức đó.
Nếu không thì các bộ lắng nghe sẽ trở thành các lớp trừu tượng.


3


Phần 2.XỬ LÝ SỰ KIỆN BÀN PHÍM
Để xử lý sự kiện bàn phím java hỗ trợ một bộ lắng nghe sự kiện đó là
interface KeyListener. Một sự kiện bàn phím được phát sinh khi người dùng
nhấn và nhả một phím trên bàn phím. Một lớp hiện thực KeyListener phải cài
đặt các phương thức KeyPressed, KeyReleased và KeyTyped. Mỗi phương
thức này có một tham số là một đối tượng kiểu KeyEvent. KeyEvent là lớp
con của lớp InputEvent.
Các phương thức của interface KeyListener:
• Phương thức KeyPressed được gọi khi một phím bất kỳ được nhấn.
• Phương thức KeyTyped được gọi thực hiện khi người dùng nhấn một
phím không phải “phím hành động” (như phím mũi tên, phím Home,
End, Page Up, Page Down, các phím chức năng như: Num Lock, Print
Screen, Scroll Lock, Caps Lock, Pause).
• Phương thức keyReleased được gọi thực hiện khi nhả phím nhấn sau
khi sự kiện KeyPressed hoặc KeyTyped.
Lớp KeyEvent có các hàm:
 int getKeyCode()
 Đối với các sự kiện keyPressed hoặc keyReleased, hàm này được sử
dụng để nhận giá trị nguyên tương ứng với mã của phím trên bàn
phím.
Đối với các sự kiện keyPressed, hàm này được sử dụng để nhận lại giá
trị nguyên là mã Unicode tương ứng với ký tự của bàn phím.
Đăng ký đối tượng lắng nghe
Để đăng ký đối tượng nghe ta sử dụng tên phương thức có cấu trúc như sau:
add + loại sự kiện + Listener(lớp nghe sự kiện)
=>Ví dụ với Component:

addKeyListener(KeyListener)
Các phương thức của Keylistener Interface:
 keyTyped:
public void keyTyped(KeyEvent event) {………..} : Được triệu hồi
khi một key đã được gõ.
 keyPressed:
public void keyPressed(KeyEvent event) {………..} : Được triệu hồi
khi một key đã được nhấn.
 keyReleased:
public void keyReleased(KeyEvent event) {………..} : Được triệu hồi
khi một key đã được nhả ra.
Ví dụ:
Minh họa việc xử lý sự kiện bàn phím thông qua các phương thức của
interface KeyListener. Lớp KeyDemo bên dưới hiện thực interface
KeyListener, vì vậy tất cả 3 phương thức trong KeyListener phải được
cài đặt trong chương trình.
4


import java.awt.*;
import java.awt.event.*;
public class KeyDemo extends Frame implements KeyListener {
private String line1 = "", line2 = "";
private String line3 = "";
private TextArea textArea;
// set up GUI
public KeyDemo() {
super("KeyListenerDemo");
textArea = new TextArea(10, 15);
textArea.setText("Please press any key on the keyboard !");

textArea.setEnabled(false);
this.add(textArea);
// allow frame to process Key events
addKeyListener(this);
setSize(350, 100);
setVisible(true);
}
// handle press of any key
public void keyPressed(KeyEvent event) {
line1 = "Key pressed: " + event.getKeyText(event.getKeyCode());
setLines2and3(event);
}
// handle release of any key
public void keyReleased(KeyEvent event) {
line1 = "Key released: " + event.getKeyText(event.getKeyCode());
setLines2and3(event);
}
// handle press of an action key
public void keyTyped(KeyEvent event) {
line1 = "Key typed: " + event.getKeyChar();
setLines2and3(event);
}
// set second and third lines of output
private void setLines2and3(KeyEvent event) {
line2 = "This key is " + (event.isActionKey() ? "" : "not ")
+ "an action key";
String temp = event.getKeyModifiersText(event.getModifiers());
line3 = "Modifier keys pressed: " + (temp.equals("") ? "none" : temp);
textArea.setText(line1 + "\n" + line2 + "\n" + line3 + "\n");
}

// execute application

5


public static void main(String args[]) {
KeyDemo application = new KeyDemo();
}
}

Phần 3.XỬ LÝ SỰ KIỆN CHUỘT
Lớp MouseEvent là lớp con của lớp trừu tượng InputEvent được sử dụng để
xử lý các tín hiệu của chuột. Lớp này có các hàm:
 int getX()
 int getY()
 Point getPoint()
Các hàm này được sử dụng để nhận lại tọa độ x,y của vị trí liên quan
đến sự kiện do chuột gây ra.
 void translatePoint(int dx, int dy)
Hàm translatePoint() được sử dụng để chuyển tọa độ của sự kiện do
chuột gây ra đến(dx , dy).
 Int get ClickCount()
Hàm get ClickCount() đếm số lần kích chuột.
Java cung cấp hai intefaces lắng nghe (bộ lắng nghe sự kiện chuột) là
MouseListener và MouseMotionListener để quản lý và xử lý các sự kiện
liên quan đến thiết bị chuột. Những sự kiện chuột có thể “bẫy” cho bất kỳ
component nào trên GUI mà dẫn xuất từ java.awt.component.
Các phương thức của interface MouseListener:
• public void mousePressed(MouseEvent event): được gọi khi một nút chuột
được nhấn và con trỏ chuột ở trên component.

• public void mouseClicked(MouseEvent event): được gọi khi một nút chuột
được nhấn và nhả trên component mà không di chuyển chuột.
• public void mouseReleased(MouseEvent event): được gọi khi một nút
chuột nhả sa khi kéo rê.
• public void mouseEntered(MouseEvent event): được gọi khi con trỏ chuột
vào trong đường biên của một component.
• public void mouseExited(MouseEvent event): được gọi khi con trỏ chuột ra
khỏi đường biên của một component.
Các phương thức của interface MouseMotionListener:

6


• public void mouseDragged(MouseEvent even ): phương thức này được gọi
khi người dùng nhấn một nút chuột và kéo trên một component.
• public void mouseMoved(MouseEvent event): phương thức này được gọi
khi di chuyển chuột trên component.
Mỗi phương thức xử lý sự kiện chuột có một tham số MouseEvent chứa
thông tin về sự kiện chuột phát sinh chẳng hạn như: tọa độ x, y nơi sự kiện
chuột xảy ra. Những phương thức tương ứng trong các interfaces sẽ tự động
được gọi khi chuột tương tác với một component. Để biết được người dùng
đã nhấn nút chuột nào, chúng ta dùng những phuơng thức, những hằng số của
lớp InputEvent (là lớp cha của lớp MouseEvent).
Ví dụ: Chương trình tên MouseTracker bên dưới minh họa việc dùng những
phương thức của các interfaces MouseListener và MouseMotionListener
để “bẫy” và xử lý các sự kiện chuột tương ứng.
import java.awt.*;
import java.awt.event.*;
public class MouseTracker extends Frame implements MouseListener,
MouseMotionListener {

private Label statusBar;
// set up GUI and register mouse event handlers:
public MouseTracker()
{ super( "MouseDemo" );
statusBar = new Label();
this.add( statusBar, BorderLayout.SOUTH );
// application listens to its own mouse events:
addMouseListener( this );
addMouseMotionListener( this );
setSize( 275, 100 );
setVisible( true );
}
// MouseListener event handlers
// handle event when mouse released immediately
// after press
public void mouseClicked( MouseEvent event )
{
statusBar.setText( "Clicked at [" + event.getX()+", " + event.getY() + "]" );
}
// handle event when mouse pressed:
public void mousePressed( MouseEvent event )
{
statusBar.setText( "Pressed at [" + event.getX() + ", " + event.getY() + "]" );
}
// handle event when mouse released after dragging:
public void mouseReleased( MouseEvent event )
{
statusBar.setText( "Released at [" + event.getX() +

", " + event.getY() + "]" );

7


}
// handle event when mouse enters area:
public void mouseEntered( MouseEvent event )
{
statusBar.setText( "Mouse in window" );
}
// handle event when mouse exits area :
public void mouseExited( MouseEvent event )
{
statusBar.setText( "Mouse outside window" );
}
// MouseMotionListener event handlers,
// handle event when user drags mouse with button pressed:
public void mouseDragged( MouseEvent event )
{
statusBar.setText( "Dragged at [" + event.getX() + ", " + event.getY() + "]" );
}
// handle event when user moves mouse:
public void mouseMoved( MouseEvent event )
{
statusBar.setText( "Moved at [" + event.getX() +
}

", " + event.getY() + "]" );

// execute application:
public static void main( String args[] )

{
MouseTracker application = new MouseTracker();
}
} // end class MouseTracker

8


Phần 4. XỬ LÝ ÂM THANH
StdAudio là một thư viện mà bạn có thể sử dụng để chơi và thao tác tập tin
âm thanh. Nó cho phép ta có thể chơi, thao tác và tổng hợp âm thanh. Có thể
bạn đã từng dùng máy tính để xử lý âm nhạc, và bây giờ ta có thể viết chương
trình làm điều đó.
Các phương thức :

public static void close() : Đóng âm thanh tiêu chuẩn

public static void play(double sample) : Mẫu âm thanh tiêu chuẩn
dao động từ -1 đến 1. Nếu mẫu vượt quá, nó sẽ bị cắt. Và throw
IllegalArgumentException nếu mẫu không phải là số( Double.NaN).

public static void play(double[] samples) : Giống mẫu trên và dùng
cho mảng.

public static double[] read(String filename) : Đọc mẫu âm thanh từ
một file có định dạng như .wav, .au,… và trả về cho chúng là mảng với
giá trị thực từ -1 đến 1. Trong đó,filename: là tên âm thanh.

public static void play(String filename): Chạy file âm
thanh(.wav,.au,.mid,..) trong luồng ẩn.


public static void loop(String filename): Lặp file âm
thanh(.wav,.au,.mid,..) trong luồng ẩn.

public static void save (String filename,double[] samples): lưu file
audio.
Package javax.sound.sampled : cung cấp cho chúng ta interfaces và classes
cho việc bắt, xử lý và phát lại dữ liệu sampled audio. Ví dụ về interfaces
như:Clip, DataLine,Line,Mixer,Port,SourceDataLine,... và class như:
AudioFileFormat,AudioFormat,AudioInputStream,AudioSystem,… và
các xử lý ngoại lệ như:
LineUnavailableExcption,UnsupportedAudioFileException.
Ví dụ minh họa:
import javax.sound.sampled.Clip;
import java.io.File;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.net.URL;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
9



public final class StdAudio {
//The sample rate - 44,100 Hz for CD quality audio.
public static final int SAMPLE_RATE = 44100;
private static final int BYTES_PER_SAMPLE = 2;
// 16-bit audio
private static final int BITS_PER_SAMPLE = 16;
// 16-bit audio
private static final double MAX_16_BIT = Short.MAX_VALUE; // 32,767
private static final int SAMPLE_BUFFER_SIZE = 4096;
private static SourceDataLine line; // to play the sound
private static byte[] buffer;
// our internal buffer
private static int bufferSize = 0; // number of samples currently in internal buffer
private StdAudio() {
// can not instantiate
}
// static initializer
static {
init();// khởi tạo các đối tượng
}
// open up an audio stream
private static void init() {
try {
// 44,100 samples per second, 16-bit audio, mono, signed PCM, little Endian
AudioFormat format = new AudioFormat((float) SAMPLE_RATE,
BITS_PER_SAMPLE, 1, true, false);
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
line = (SourceDataLine) AudioSystem.getLine(info);
line.open(format, SAMPLE_BUFFER_SIZE * BYTES_PER_SAMPLE);
// the internal buffer is a fraction of the actual buffer size, this choice is arbitrary

// it gets divided because we can't expect the buffered data to line up exactly with
when
// the sound card decides to push out its samples.
buffer = new byte[SAMPLE_BUFFER_SIZE * BYTES_PER_SAMPLE/3];
}
catch (LineUnavailableException e) {
System.out.println(e.getMessage());
}
// no sound gets made before this call
line.start();
}
//Closes standard audio.
public static void close() {
line.drain();
line.stop();
}
public static void play(double sample) {
// clip if outside [-1, +1]
if (Double.isNaN(sample)) throw new IllegalArgumentException("sample is NaN");
if (sample < -1.0) sample = -1.0;
if (sample > +1.0) sample = +1.0;
// convert to bytes

10


short s = (short) (MAX_16_BIT * sample);
buffer[bufferSize++] = (byte) s;
buffer[bufferSize++] = (byte) (s >> 8); // little Endian
// send to sound card if buffer is full

if (bufferSize >= buffer.length) {
line.write(buffer, 0, buffer.length);
bufferSize = 0;
}
}
public static void play(double[] samples) {
if (samples == null) throw new NullPointerException("argument to play() is null");
for (int i = 0; i < samples.length; i++) {
play(samples[i]);
}
}
public static double[] read(String filename) {
byte[] data = readByte(filename);
int n = data.length;
double[] d = new double[n/2];
for (int i = 0; i < n/2; i++) {
d[i] = ((short) (((data[2*i+1] & 0xFF) << 8) + (data[2*i] & 0xFF))) / ((double)
MAX_16_BIT);
}
return d;
}
public static synchronized void play(String filename) {
if (filename == null) throw new NullPointerException();
try {
Clip clip = AudioSystem.getClip();
InputStream is = StdAudio.class.getResourceAsStream(filename);
AudioInputStream ais = AudioSystem.getAudioInputStream(is);
clip.open(ais);
clip.start();
}

catch (RuntimeException e) {
System.out.println("could not play '" + filename + "'");
throw e;
}
catch (Exception e) {
System.out.println("could not play '" + filename + "'");
e.printStackTrace();
}
}
public static synchronized void loop(String filename) {
if (filename == null) throw new NullPointerException();
try {
Clip clip = AudioSystem.getClip();
InputStream is = StdAudio.class.getResourceAsStream(filename);
AudioInputStream ais = AudioSystem.getAudioInputStream(is);
clip.open(ais);

11


clip.loop(Clip.LOOP_CONTINUOUSLY);
}
catch (RuntimeException e) {
System.out.println("could not play '" + filename + "'");
throw e;
}
catch (Exception e) {
System.out.println("could not play '" + filename + "'");
e.printStackTrace();
}

}
// return data as a byte array
private static byte[] readByte(String filename) {
byte[] data = null;
AudioInputStream ais = null;
try {
// try to read from file
File file = new File(filename);
if (file.exists()) {
ais = AudioSystem.getAudioInputStream(file);
int bytesToRead = ais.available();
data = new byte[bytesToRead];
int bytesRead = ais.read(data);
if (bytesToRead != bytesRead) throw new RuntimeException("read only " +
bytesRead + " of " + bytesToRead + " bytes");
}
// try to read from URL
else {
URL url = StdAudio.class.getResource(filename);
ais = AudioSystem.getAudioInputStream(url);
int bytesToRead = ais.available();
data = new byte[bytesToRead];
int bytesRead = ais.read(data);
if (bytesToRead != bytesRead) throw new RuntimeException("read only " +
bytesRead + " of " + bytesToRead + " bytes");
}
}
catch (IOException e) {
System.out.println(e.getMessage());
throw new RuntimeException("Could not read " + filename);

}
catch (UnsupportedAudioFileException e) {
System.out.println(e.getMessage());
throw new RuntimeException(filename + " in unsupported audio format");
}
return data;
}
public static void save(String filename, double[] samples) {
// assumes 44,100 samples per second
// use 16-bit audio, mono, signed PCM, little Endian

12


AudioFormat format = new AudioFormat(SAMPLE_RATE, 16, 1, true, false);
byte[] data = new byte[2 * samples.length];
for (int i = 0; i < samples.length; i++) {
int temp = (short) (samples[i] * MAX_16_BIT);
data[2*i + 0] = (byte) temp;
data[2*i + 1] = (byte) (temp >> 8);
}
// now save the file
try {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
AudioInputStream ais = new AudioInputStream(bais, format, samples.length);
if (filename.endsWith(".wav") || filename.endsWith(".WAV")) {
AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new File(filename));
}
else if (filename.endsWith(".au") || filename.endsWith(".AU")) {
AudioSystem.write(ais, AudioFileFormat.Type.AU, new File(filename));

}
else {
throw new RuntimeException("File format not supported: " + filename);
}
}
catch (IOException e) {
System.out.println(e);
}
}
private static double[] note(double hz, double duration, double amplitude) {
int n = (int) (StdAudio.SAMPLE_RATE * duration);
double[] a = new double[n+1];
for (int i = 0; i <= n; i++)
a[i] = amplitude * Math.sin(2 * Math.PI * i * hz / StdAudio.SAMPLE_RATE);
return a;
}
public static void main(String[] args) {
// 440 Hz for 1 sec
double freq = 440.0;
for (int i = 0; i <= StdAudio.SAMPLE_RATE; i++) {
StdAudio.play(0.5 * Math.sin(2*Math.PI * freq * i / StdAudio.SAMPLE_RATE));
}
// scale increments
int[] steps = { 0, 2, 4, 5, 7, 9, 11, 12 };
for (int i = 0; i < steps.length; i++) {
double hz = 440.0 * Math.pow(2, steps[i] / 12.0);
StdAudio.play(note(hz, 1.0, 0.5));
}
// need to call this in non-interactive stuff so the program doesn't terminate
// until all the sound leaves the speaker.

StdAudio.close();
}
}

13



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×