SlideShare a Scribd company logo
SW218-  Програмчлалын технологи Лекц № 1 3   Multimedia
Multimedia Өнөө үед  Multimedia  гэж маш их яригдах болжээ. Үүнтэй холбогдуулан  Multimedia- ийг  Java  програмчлалын хэлэнд хэрхэн боловсруулдаг талаар энэ хичээлээрээ үзнэ.  Multimedia  нь  Image Animation Audio Video
Зураг  (Image) Програм бичих явцад та бүхэн зураг оруулж ирэх зайлшгүй шаардлага гарна.   Тэгвэл уг програмдаа зураг оруулж ирэхийн тулд тухайн зурагны байрлаж байгаа байрлал, эсвэл ямар нэг веб сайтаас авах бол тухайн сайтын  URL  хаяг болон тухайн зурагны өргөтгөлийг мэдэж байх шаардлагатай.   Зургийг  Ажилуулах буюу ачаалах  (loading) Харуулах  (displaying) Нарийвчлан засварлах  (manipulate)
Image loading Үүнд  getImage()  гэсэн функц ашиглагдана. Дараахь байдлаар ашиглана.   public Image getImage(URL url)  public Image getImage(URL url, String name)  Дээрхи зарлалтыг хэрэгжүүлэхдээ: Image image1 = toolkit.getImage("imageFile.gif"); Image image2 = toolkit.getImage(new URL("http://java.sun.com/graphics/people.gif")); Image img = getImage("http://www.myschool.edu/anImage.gif"); or :    Image img = getImage(getCodeBase(),"anImage.gif");
Зургийг засварлах шаардлага гарвал  public boolean imageUpdate(Image theimg, int infoflags,  int x, int y, int w, int h)   Үүнд:  theimg-  Тухайн програмд ашиглагдаж байгаа зургийн нэр Infoflag-  Binary image 5 RGB image 4 Intensity but not in standard range 3 Intensity image with values in standard range ([0,1] for single and double arrays, [0,255] for uint8 arrays, [0,65535] for uint16 arrays) 2 Indexed image data,  1 Type of Image Flags
import java.applet.Applet; import java.awt.*; Public class LoadImage&Scale extends JApplet{ Private Image logo1; Private ImageIcon logo2; Public void init() { Logo1=getImage(getDocumentBase(),”logo.gif”); Logo2.=new ImageIcon(“logo.gif”); } Public void paint (Graphics g){ g.drawImage(logo1,0,0,this); g.DrawImage(logo1,0,120,getWidth(),getHeight()-120,this); Logo2.paintIcon(this,g,180,0); } }
Displaying Images  Дэлгэц дээр зургийг харуулахын тулд  g.drawImage(image, 0, 0, this);   Мөн  g.drawImage(myImage, 90, 0, 300, 62, this);   Дараахь байдлаар өргөтгөн ашиглаж болно. public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer)  public abstract boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer)  public abstract boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer)  public abstract boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer)  drawImage()  функц дараахь аргументуудтай :   Image img  –Зурагдах зураг   int x, int y  –  x,y  координат int width, int height -   Зургийн урт, өргөн Color bgcolor  –  Backgound- ийн өнгө ImageObserver observer  -  An object that implements the ImageObserver interface. This registers the object as the image observer so that it's notified whenever new information about the image becomes available. Most components can simply specify this.
import java.awt.*; import java.applet.Applet;  public class ImageDisplayer extends Applet { Image image; public void init() { image = getImage(getCodeBase(), "../images/rocketship.gif"); } public void paint(Graphics g) { g.drawImage(image, 0, 0, this); g.drawImage(image, 90, 0, 300, 62, this); } }
Animation Animation  гэдэг нь ямар нэгэн хөдөлгөөнтэй зураг юмуу текст байдаг ба хоорондоо холбоотой олон  frame -үүдээс бүрдэнэ. Тэдгээр хоорондоо холбоотой  frame -үүд нь үнэн хэрэгтээ солигдон гарч ирж болох юм. Энгийн персональ компьютер нь секундэд 10-20  frame- ийг ээлжлэн харуулах чадвартай байдаг.  (8 frame-  бага, 12  frame -   стандарт, 24 хүртэл  frame- ийг солих чадвартай бол өндөр чанарын гэж үзнэ. )
Animation loop  үүсгэх Аливаа  animation -д үсрэлт хийх нь их чухал үндсэн үйлдэлд тооцогддог.  Тийм учраас хэдэн үсрэлтийг ямар интервалд хийхийгээ сайн тооцох хэрэгтэй. import java.awt.*; import javax.swing.*; public class LogoAnimator extends JPanel  implements ActionListener{ private ImageIcon images[]; private int totalImages=30;  //  з-ийн  тоо private int currentImage=0; //index private int animationDelay=50; // millisecond delay
private int width; private int height; Private String ImageName=“deitel”; private Timer animationTimer; Public LogoAnimator() Private void initializeAnimation(){ Images=new ImageIcon[totalImages]; For(int count=0;count<images.length;count++) Images[count]=newImageIcon(getClass().getResource(“images/”+imageName+count+”.gif”)); Width=images[0].getIconWidth(); Height=images[0].getIconHeight();} Public void paintComponent(Graphics g){ Super.paintComponent(g); Images[currentImage].paintIcon(this,g,0,0); currentImage=(currentImage+1)%totalImages; }
Public void actionPerformed(ActionEvent actionEvent){ Repaint();} Public void startAnimation(){ If(animationTimer==null){ currentImage=0; animationTimer=new Timer(animationDelay,this); animationTimer.start();} Else if (!animationTimer.isRunning()) Animation.restart();} Public void stopAnimation(){ animationTimer.stop();} Public Dimension getMinimumSize(){ Return getPreferredSize();}
Public Dimension getPreferredSize(){ Return new Dimension(width,height);} Public static void main(String args[]){ LogoAnimator animation=new LogoAnimator(); JFrame window=new LFrame(Animator test); Container container=window.getContentPane(); Container.add(animation); Window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Window.pack(); Insets insets=window.getInsets(); Window.setSize(animation.getPreferredSize().width+insets.left+insets.right,animation.getPreferredSize().height+insets.top+insets.bottom); Window.setVisible(true); Animation.startAnimation(); }}
Зураг хөндлөн гарах +
...//Where instance variables are declared: Image stars; Image rocket; ...//In the init() method: stars = getImage(getCodeBase(), &quot;../images/starfield.gif&quot;); rocket = getImage(getCodeBase(), &quot;../images/rocketship.gif&quot;); ...//In the update() method: //Paint the frame into the image. paintFrame(offGraphics); ...//A new method: void paintFrame(Graphics g) { Dimension d = size(); int w;  int h; //If we have a valid width and height for the background image,  //draw it. w = stars.getWidth(this); h = stars.getHeight(this); if ((w > 0) && (h > 0)) { g.drawImage(stars, (d.width - w)/2,  (d.height - h)/2, this);   }  //If we have a valid width and height for the background image,  //draw it.  w = rocket.getWidth(this); h = rocket.getHeight(this); if ((w > 0) && (h > 0)) {  g.drawImage(rocket, ((frameNumber*5) % (w + d.width)) - w, (d.height - h)/2, this);  }}
Audio Java  хэлэнд түүнтэй харьцах дараахь 3 функц байдаг.  public abstract void play()  public abstract void loop()  public abstract void stop()  Тэдгээрийн хэрэглээг дараахь жижиг програм дээр харъя.
Import java.applet.*; Import java.awt.*; Import java.awt.event.*; Import javax.swing.*; Public class Load Audio&Play extends JApplet{ Private AudioClip sound1, sound2, currentSound; Private JButton playSound,loopSound,stopSound; Private JComboBox chooseSound; Public void init(){ Container container=getContentPane(); Container.setLayout(new Layout()); String Choices[]={“Welcome”,”Hi”}; chooseSound=new JComboBox(choices);
ChooseSound.addItemListener{ New ItemListener(){ Public void ItemStateChanged(ItemEvent e){ CurrentSound.stop(); currentSound=chooseSound.getSelectedIndex()==0?sound1:sound2;}}}; Container.add(chooseSound); ButtonHandler handler =new ButtonHandler(); playSound=new JButton(“Play”); playSound.addActionListener(handler); Container.add(playSound);
loopSound=new JButton(“Loop”); loopSound.addActionListener(handler); Container.add(loopSound); stopSound=new JButton(“Stop”); stopSound.addActionListener(handler); Container.add(stopSound); sound1=getAudioClip(getDocumentBase(),”welcome.wav”); Sound2=getAudioClip(getDocumentBase(),”hi.au”); currentSound=sound1;} Public void stop(){ currentSound.stop();}
Private class ButtonHandler implements ActionListener{ Public void actionPerformed(ActionEvent actionEvent){ if(actionEvent.getSource()==playSound) currentSound.play(); Else if(actionEvent.getSource()==loopSound) currentSound.loop(); Else if(actionEvent.getSource()==stopSound) currentSound.stop(); } }}
// OnTheFarm Class // OnTheFarm.java // Imports import java.applet.*; import java.awt.*; import java.util.Random; public class OnTheFarm extends Applet implements Runnable {   AudioClip clip[] = new AudioClip[8];   Thread    thread;   Random    rand = new Random(System.currentTimeMillis());    public void init() {     // Load the sounds     clip[0] = getAudioClip(getDocumentBase(), &quot;Res/Hillbilly.au&quot;);     clip[1] = getAudioClip(getDocumentBase(), &quot;Res/Cow.au&quot;);     clip[2] = getAudioClip(getDocumentBase(), &quot;Res/Duck.au&quot;);     clip[3] = getAudioClip(getDocumentBase(), &quot;Res/Goat.au&quot;);     clip[4] = getAudioClip(getDocumentBase(), &quot;Res/Hen.au&quot;);     clip[5] = getAudioClip(getDocumentBase(), &quot;Res/Horse.au&quot;);     clip[6] = getAudioClip(getDocumentBase(), &quot;Res/Pig.au&quot;);     clip[7] = getAudioClip(getDocumentBase(), &quot;Res/Rooster.au&quot;);   }   public void start() {     if (thread == null) {       thread = new Thread(this);        thread.start();     }   }
public void stop() {     if (thread != null) {       thread.stop();       thread = null;     }   }   public void run() {     while (Thread.currentThread() == thread) {       // Loop the music sound       clip[0].loop();       while (true) {         // Wait three seconds         try           Thread.sleep(3000);          catch (InterruptedException e)           break;          // Play an animal sound         clip[(rand.nextInt() % 3) + 4].play();       }     }   }   public void paint(Graphics g) {     Font        font = new Font(&quot;TimesRoman&quot;, Font.PLAIN, 20);     FontMetrics fm = g.getFontMetrics(font);      String      str = new String(&quot;On the farm...&quot;);     g.setFont(font);     g.drawString(str, (size().width - fm.stringWidth(str)) / 2,       ((size().height - fm.getHeight()) / 2) + fm.getAscent());   } }

More Related Content

DOCX
Project Komputer Grafik
PDF
Java term project final
DOCX
Dokumen
PDF
Applet 7 image_j_panel
DOCX
Program project khusus
PDF
jQueryUI: Rich Interactivity, Simplified
PPTX
Gurb 160421085938
Project Komputer Grafik
Java term project final
Dokumen
Applet 7 image_j_panel
Program project khusus
jQueryUI: Rich Interactivity, Simplified
Gurb 160421085938

Recently uploaded (7)

PDF
"ಶ್ರೀ ಕ್ಷೇತ್ರ ಚಂಪಕಧಾಮ ಸ್ವಾಮಿ ದೇವಾಲಯ""Sri Kshetra Champakadham Swamy Temple"
PPTX
Slide Ibadah siang 29 mei 2025 jika .pptx
PPTX
Coklat Beige Ilustrasi 3 Dimensi Tugas Kelompok Presentasi.pptx
PPTX
science grade 7 quiz_Scientific Method.pptx
PDF
فێرکردن و فێربوونی مۆدێرن.pdf دەروازەیەک بۆ
PDF
ಶ್ರೀ ಕ್ಷೇತ್ರ ಚಂಪಕಧಾಮ ಸ್ವಾಮಿ ದೇವಾಲಯSri Kshetra Champakadham Swamy Temple
PPTX
Tahfidz Qur’an TIMING tampa musik bagian 2.pptx
"ಶ್ರೀ ಕ್ಷೇತ್ರ ಚಂಪಕಧಾಮ ಸ್ವಾಮಿ ದೇವಾಲಯ""Sri Kshetra Champakadham Swamy Temple"
Slide Ibadah siang 29 mei 2025 jika .pptx
Coklat Beige Ilustrasi 3 Dimensi Tugas Kelompok Presentasi.pptx
science grade 7 quiz_Scientific Method.pptx
فێرکردن و فێربوونی مۆدێرن.pdf دەروازەیەک بۆ
ಶ್ರೀ ಕ್ಷೇತ್ರ ಚಂಪಕಧಾಮ ಸ್ವಾಮಿ ದೇವಾಲಯSri Kshetra Champakadham Swamy Temple
Tahfidz Qur’an TIMING tampa musik bagian 2.pptx
Ad
Ad

Multmedia In Java

  • 1. SW218- Програмчлалын технологи Лекц № 1 3 Multimedia
  • 2. Multimedia Өнөө үед Multimedia гэж маш их яригдах болжээ. Үүнтэй холбогдуулан Multimedia- ийг Java програмчлалын хэлэнд хэрхэн боловсруулдаг талаар энэ хичээлээрээ үзнэ. Multimedia нь Image Animation Audio Video
  • 3. Зураг (Image) Програм бичих явцад та бүхэн зураг оруулж ирэх зайлшгүй шаардлага гарна. Тэгвэл уг програмдаа зураг оруулж ирэхийн тулд тухайн зурагны байрлаж байгаа байрлал, эсвэл ямар нэг веб сайтаас авах бол тухайн сайтын URL хаяг болон тухайн зурагны өргөтгөлийг мэдэж байх шаардлагатай. Зургийг Ажилуулах буюу ачаалах (loading) Харуулах (displaying) Нарийвчлан засварлах (manipulate)
  • 4. Image loading Үүнд getImage() гэсэн функц ашиглагдана. Дараахь байдлаар ашиглана. public Image getImage(URL url) public Image getImage(URL url, String name) Дээрхи зарлалтыг хэрэгжүүлэхдээ: Image image1 = toolkit.getImage(&quot;imageFile.gif&quot;); Image image2 = toolkit.getImage(new URL(&quot;http://java.sun.com/graphics/people.gif&quot;)); Image img = getImage(&quot;http://www.myschool.edu/anImage.gif&quot;); or :    Image img = getImage(getCodeBase(),&quot;anImage.gif&quot;);
  • 5. Зургийг засварлах шаардлага гарвал public boolean imageUpdate(Image theimg, int infoflags, int x, int y, int w, int h) Үүнд: theimg- Тухайн програмд ашиглагдаж байгаа зургийн нэр Infoflag- Binary image 5 RGB image 4 Intensity but not in standard range 3 Intensity image with values in standard range ([0,1] for single and double arrays, [0,255] for uint8 arrays, [0,65535] for uint16 arrays) 2 Indexed image data, 1 Type of Image Flags
  • 6. import java.applet.Applet; import java.awt.*; Public class LoadImage&Scale extends JApplet{ Private Image logo1; Private ImageIcon logo2; Public void init() { Logo1=getImage(getDocumentBase(),”logo.gif”); Logo2.=new ImageIcon(“logo.gif”); } Public void paint (Graphics g){ g.drawImage(logo1,0,0,this); g.DrawImage(logo1,0,120,getWidth(),getHeight()-120,this); Logo2.paintIcon(this,g,180,0); } }
  • 7. Displaying Images Дэлгэц дээр зургийг харуулахын тулд g.drawImage(image, 0, 0, this); Мөн g.drawImage(myImage, 90, 0, 300, 62, this); Дараахь байдлаар өргөтгөн ашиглаж болно. public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer) public abstract boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer) public abstract boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer) public abstract boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer) drawImage() функц дараахь аргументуудтай : Image img –Зурагдах зураг int x, int y – x,y координат int width, int height - Зургийн урт, өргөн Color bgcolor – Backgound- ийн өнгө ImageObserver observer - An object that implements the ImageObserver interface. This registers the object as the image observer so that it's notified whenever new information about the image becomes available. Most components can simply specify this.
  • 8. import java.awt.*; import java.applet.Applet; public class ImageDisplayer extends Applet { Image image; public void init() { image = getImage(getCodeBase(), &quot;../images/rocketship.gif&quot;); } public void paint(Graphics g) { g.drawImage(image, 0, 0, this); g.drawImage(image, 90, 0, 300, 62, this); } }
  • 9. Animation Animation гэдэг нь ямар нэгэн хөдөлгөөнтэй зураг юмуу текст байдаг ба хоорондоо холбоотой олон frame -үүдээс бүрдэнэ. Тэдгээр хоорондоо холбоотой frame -үүд нь үнэн хэрэгтээ солигдон гарч ирж болох юм. Энгийн персональ компьютер нь секундэд 10-20 frame- ийг ээлжлэн харуулах чадвартай байдаг. (8 frame- бага, 12 frame - стандарт, 24 хүртэл frame- ийг солих чадвартай бол өндөр чанарын гэж үзнэ. )
  • 10. Animation loop үүсгэх Аливаа animation -д үсрэлт хийх нь их чухал үндсэн үйлдэлд тооцогддог. Тийм учраас хэдэн үсрэлтийг ямар интервалд хийхийгээ сайн тооцох хэрэгтэй. import java.awt.*; import javax.swing.*; public class LogoAnimator extends JPanel implements ActionListener{ private ImageIcon images[]; private int totalImages=30; // з-ийн тоо private int currentImage=0; //index private int animationDelay=50; // millisecond delay
  • 11. private int width; private int height; Private String ImageName=“deitel”; private Timer animationTimer; Public LogoAnimator() Private void initializeAnimation(){ Images=new ImageIcon[totalImages]; For(int count=0;count<images.length;count++) Images[count]=newImageIcon(getClass().getResource(“images/”+imageName+count+”.gif”)); Width=images[0].getIconWidth(); Height=images[0].getIconHeight();} Public void paintComponent(Graphics g){ Super.paintComponent(g); Images[currentImage].paintIcon(this,g,0,0); currentImage=(currentImage+1)%totalImages; }
  • 12. Public void actionPerformed(ActionEvent actionEvent){ Repaint();} Public void startAnimation(){ If(animationTimer==null){ currentImage=0; animationTimer=new Timer(animationDelay,this); animationTimer.start();} Else if (!animationTimer.isRunning()) Animation.restart();} Public void stopAnimation(){ animationTimer.stop();} Public Dimension getMinimumSize(){ Return getPreferredSize();}
  • 13. Public Dimension getPreferredSize(){ Return new Dimension(width,height);} Public static void main(String args[]){ LogoAnimator animation=new LogoAnimator(); JFrame window=new LFrame(Animator test); Container container=window.getContentPane(); Container.add(animation); Window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Window.pack(); Insets insets=window.getInsets(); Window.setSize(animation.getPreferredSize().width+insets.left+insets.right,animation.getPreferredSize().height+insets.top+insets.bottom); Window.setVisible(true); Animation.startAnimation(); }}
  • 15. ...//Where instance variables are declared: Image stars; Image rocket; ...//In the init() method: stars = getImage(getCodeBase(), &quot;../images/starfield.gif&quot;); rocket = getImage(getCodeBase(), &quot;../images/rocketship.gif&quot;); ...//In the update() method: //Paint the frame into the image. paintFrame(offGraphics); ...//A new method: void paintFrame(Graphics g) { Dimension d = size(); int w; int h; //If we have a valid width and height for the background image, //draw it. w = stars.getWidth(this); h = stars.getHeight(this); if ((w > 0) && (h > 0)) { g.drawImage(stars, (d.width - w)/2, (d.height - h)/2, this); } //If we have a valid width and height for the background image, //draw it. w = rocket.getWidth(this); h = rocket.getHeight(this); if ((w > 0) && (h > 0)) { g.drawImage(rocket, ((frameNumber*5) % (w + d.width)) - w, (d.height - h)/2, this); }}
  • 16. Audio Java хэлэнд түүнтэй харьцах дараахь 3 функц байдаг. public abstract void play() public abstract void loop() public abstract void stop() Тэдгээрийн хэрэглээг дараахь жижиг програм дээр харъя.
  • 17. Import java.applet.*; Import java.awt.*; Import java.awt.event.*; Import javax.swing.*; Public class Load Audio&Play extends JApplet{ Private AudioClip sound1, sound2, currentSound; Private JButton playSound,loopSound,stopSound; Private JComboBox chooseSound; Public void init(){ Container container=getContentPane(); Container.setLayout(new Layout()); String Choices[]={“Welcome”,”Hi”}; chooseSound=new JComboBox(choices);
  • 18. ChooseSound.addItemListener{ New ItemListener(){ Public void ItemStateChanged(ItemEvent e){ CurrentSound.stop(); currentSound=chooseSound.getSelectedIndex()==0?sound1:sound2;}}}; Container.add(chooseSound); ButtonHandler handler =new ButtonHandler(); playSound=new JButton(“Play”); playSound.addActionListener(handler); Container.add(playSound);
  • 19. loopSound=new JButton(“Loop”); loopSound.addActionListener(handler); Container.add(loopSound); stopSound=new JButton(“Stop”); stopSound.addActionListener(handler); Container.add(stopSound); sound1=getAudioClip(getDocumentBase(),”welcome.wav”); Sound2=getAudioClip(getDocumentBase(),”hi.au”); currentSound=sound1;} Public void stop(){ currentSound.stop();}
  • 20. Private class ButtonHandler implements ActionListener{ Public void actionPerformed(ActionEvent actionEvent){ if(actionEvent.getSource()==playSound) currentSound.play(); Else if(actionEvent.getSource()==loopSound) currentSound.loop(); Else if(actionEvent.getSource()==stopSound) currentSound.stop(); } }}
  • 21. // OnTheFarm Class // OnTheFarm.java // Imports import java.applet.*; import java.awt.*; import java.util.Random; public class OnTheFarm extends Applet implements Runnable {   AudioClip clip[] = new AudioClip[8];   Thread    thread;   Random    rand = new Random(System.currentTimeMillis());   public void init() {     // Load the sounds     clip[0] = getAudioClip(getDocumentBase(), &quot;Res/Hillbilly.au&quot;);     clip[1] = getAudioClip(getDocumentBase(), &quot;Res/Cow.au&quot;);     clip[2] = getAudioClip(getDocumentBase(), &quot;Res/Duck.au&quot;);     clip[3] = getAudioClip(getDocumentBase(), &quot;Res/Goat.au&quot;);     clip[4] = getAudioClip(getDocumentBase(), &quot;Res/Hen.au&quot;);     clip[5] = getAudioClip(getDocumentBase(), &quot;Res/Horse.au&quot;);     clip[6] = getAudioClip(getDocumentBase(), &quot;Res/Pig.au&quot;);     clip[7] = getAudioClip(getDocumentBase(), &quot;Res/Rooster.au&quot;);   }   public void start() {     if (thread == null) {       thread = new Thread(this);       thread.start();     }   }
  • 22. public void stop() {     if (thread != null) {       thread.stop();       thread = null;     }   }   public void run() {     while (Thread.currentThread() == thread) {       // Loop the music sound       clip[0].loop();       while (true) {         // Wait three seconds         try           Thread.sleep(3000);         catch (InterruptedException e)           break;         // Play an animal sound         clip[(rand.nextInt() % 3) + 4].play();       }     }   }   public void paint(Graphics g) {     Font        font = new Font(&quot;TimesRoman&quot;, Font.PLAIN, 20);     FontMetrics fm = g.getFontMetrics(font);     String      str = new String(&quot;On the farm...&quot;);     g.setFont(font);     g.drawString(str, (size().width - fm.stringWidth(str)) / 2,       ((size().height - fm.getHeight()) / 2) + fm.getAscent());   } }