Results 1 to 13 of 13
  1. #1
    caustr01 is offline Member
    Join Date
    Mar 2014
    Posts
    6
    Rep Power
    0

    Angry Help with code. Midi Player

    Hi I need help with my code. I apologize it is a bit messy I am adding deleting readding things so it isn't very organized.

    Here are the guidelines:
    1. Create a Song class.
    i) Create a default constructor that sets the name of the song to "Unknown".
    ii) Create a second constructor that takes as input a String for the name of the song, and saves the name in an instance variable in the class.
    2. Create an addNote method that takes as input a note, velocity, and duration and saves it somehow in the class (adding the note to array(s) would be a good way to go).
    3. Create a playSong method that outputs the name of the song and then plays the notes that have been added to the song.

    For example, the following would create a Song named "Test" that plays a middle C for half a second and D for a second:

    Song test = new Song("Test");
    test.addNote(60,127,500);
    test.addNote(61,127,1000);
    test.playSong();

    b) Write a main method that uses your Song class to play Twinkle Twinkle Little Star, which starts with the notes: C, C, G, G, A, A, G (half note), F, F, E, E, D, D, C (half note).

    I haven't tackled the name of the song part because I am not sure if the computer is suppose to ask for the name and the print it to the screen or if it is just supposed to printed to the screen. Right now I am trying to call my method in main but it is giving me an error telling me to create a class for "channels[]" but that is an array not a class. New at this and I am very black and white so I try to reserach and think outside the box and much as I can but its hard for me haha
    thank you for any input or help

    Here is what i have so far

    package song;

    import javax.sound.midi.*;

    public class Song {

    //variables
    private String name;
    private int note;
    private int duration;
    private int velocity;

    //default constructor
    public Song(){
    name="Unknown";
    }

    //constructor
    public Song(String nam){
    name=nam;
    }

    //method that takes input and saves it in the class (using array)
    /**
    *
    * @param note
    * @param duration
    * @param velocity
    * @param notes
    */
    public static void addNote(int note, int duration, int velocity){
    Song[] addNote= new Song[3];
    }

    //method that outputs the name of the song and plays the notes that had been
    //added to the song
    public static void playSong(int note, int velocity,int duration, MidiChannel channels[]){

    //start playing the note using instrument in slot 0
    channels[0].noteOn(note, velocity);
    //wait out the duration
    try
    {
    Thread.sleep(duration);
    }
    catch (InterruptedException e)
    {
    }
    //stop playing the note
    channels[0].noteOff(note);

    Song test= new Song("Twinkle Twinkle Little Star");

    test.addNote(60, 127, 1000);
    test.addNote(60, 127, 1000);
    test.addNote(67, 127, 1000);
    test.addNote(67, 127, 1000);
    test.addNote(69, 127, 1000);
    test.addNote(69, 127, 1000);
    test.addNote(67, 127, 500);
    test.addNote(65, 127, 1000);
    test.addNote(65, 127, 1000);
    test.addNote(64, 127, 1000);
    test.addNote(64, 127, 1000);
    test.addNote(62, 127, 1000);
    test.addNote(62, 127, 1000);
    test.addNote(60, 127, 500);



    }

    //accessors
    public String getName(){
    return name;
    }



    public static void main(String[] args) {

    // Initialize the synthesizer
    Synthesizer synth = null;
    try {
    synth = MidiSystem.getSynthesizer();
    }
    catch (MidiUnavailableException e) { }
    try
    {
    synth.open();
    }
    catch (MidiUnavailableException e)
    {
    e.printStackTrace();
    System.exit(1);
    }
    MidiChannel[] channels = synth.getChannels();
    playSong(note, velocity, duration, channels[]);
    System.exit(0);

    }

    }

  2. #2
    jashburn is offline Senior Member
    Join Date
    Feb 2014
    Posts
    219
    Rep Power
    1

    Default Re: Help with code. Midi Player

    Firstly, please wrap your code with [code] tags so that it is easier to read, e.g.,
    [code]
    // your code here
    [/code]

    It preserves formatting and provides syntax highlighting:
    Java Code:
        // your code here
    There are a number of issues with your code such that it can be confusing for you if I point out each of the issues. I'd suggest it'll be better to make a copy of your existing code, and rewrite it in a more systematic way as follows.

    1. Method signatures

    Pay attention to the example given in the assignment as it tells you the method signatures to use:

    Java Code:
    Song test = new Song("Test");
    test.addNote(60,127,500);
    test.addNote(61,127,1000);
    test.playSong();
    Your Song constructors are fine, so keep them. They address guidelines 1 (i) and (ii).

    Based on the example and guideline 2, the addNote method should look like this:

    Java Code:
    public void addNote(int note, int velocity, long duration)
    Note:

    Based on the example and guideline 3, the playSong method should look like this:

    Java Code:
    public void playSong()
    Compare this with your existing playSong method, and note the difference.

    2. addNote method implementation

    Guideline 2 suggests to implement it so that it

    takes as input a note, velocity, and duration and saves it somehow in the class (adding the note to array(s) would be a good way to go)
    Your current implementation of

    Java Code:
    Song[] addNote = new Song[3]
    doesn't do this. To save note, velocity and duration in the class would imply saving them into one or more fields in the class. The guideline suggests to use "array(s)", i.e., one or more arrays. You can create 3 array fields, 1 each for note, velocity and duration. As you'll need to initialise the size of the arrays, and you do not know how many notes there will be until all the addNote method calls have been made, just initialise the arrays to a size that will fit all the notes in the Twinkle Twinkle Little Star song.

    Once you have the array fields, your addNote method should therefore just add note, velocity and duration into the corresponding arrays. Be aware that with each addNote call you'll need to add the note details into the next available position in the arrays, so think about how you'll keep track of the array indices.

    Note: If you have already learned about data structures such as ArrayList, it'll be better to use ArrayList rather than fixed-size arrays mentioned above as ArrayList's size is dynamic. Also, it is possible to create a Note class containing note, velocity and duration fields, and save instances of Note objects into the array/ArrayList, but if you do not know what this means, forget it as it'll only confuse you for this assignment.

    3. playSong method implementation

    Unlike your current implementation, this method's signature does not have parameters. This implies the method's main responsibility is to play the notes that have been saved in the arrays in #2. To do this you can place the code to get and prepare the synthesizer and MIDI channels here. You'll also need to iterate through the arrays, and for each note, make the noteOn, sleep and noteOff method calls.

    4. main method implementation

    The main method's implementation is pretty much like the example in the assignment:

    Java Code:
    Song test = new Song("Test");
    test.addNote(60,127,500);
    test.addNote(61,127,1000);
    test.playSong();
    Do try the above and see how far you can get with them. If you run into problems that you cannot solve, post your re-worked code here. Remember to wrap your code using [code] tags.

  3. #3
    caustr01 is offline Member
    Join Date
    Mar 2014
    Posts
    6
    Rep Power
    0

    Default Re: Help with code. Midi Player

    Here is what I have so far. I am a bit confused on the parameters for playSong() because in order for the noteOn, sleep etc to work i need to put in the playSong(int note, int velocity, int duration) or am I missing something. By the way you made it sound I need to use a loop in order to iterate through the arrays and the code above?

    Java Code:
    package song;
    
    import java.util.ArrayList;
    import javax.sound.midi.*;
    
    public class Song {
    
        private String name;
    
        public Song() {
            name = "Unknown";
        }
    
        public Song(String nam) {
            name = nam;
        }
    
        public class Info {
    
            int note;
            int velocity;
            int duration;
        }
    
        public void addNote(int note, int velocity, int duration) {
            ArrayList<Info> addNote = new ArrayList<Info>();
    
        }
    
        public void playSong(int note, int velocity, int duration) {
    
            Synthesizer synth = null;
            try {
                synth = MidiSystem.getSynthesizer();
            } catch (MidiUnavailableException e) {
            }
            try {
                synth.open();
            } catch (MidiUnavailableException e) {
                e.printStackTrace();
    
                System.exit(1);
            }
    
            MidiChannel[] channels = synth.getChannels();
    
            Instrument instruments[] = synth.getAvailableInstruments();
            synth.loadInstrument(instruments[0]);
            channels[0].programChange(74);
    
            //start playing the note using instrument in slot 0
            channels[0].noteOn(note, velocity);
            //wait out the duration
            try {
                Thread.sleep(duration);
            } catch (InterruptedException e) {
            }
            //stop playing the note
            channels[0].noteOff(note);
        }
    
        public static void main(String[] args) {
            Song test = new Song("Twinkle Twinkle Little Star");
            test.addNote(60, 127, 500);
            test.addNote(60, 127, 500);
            test.addNote(67, 127, 500);
            test.addNote(67, 127, 500);
            test.addNote(69, 127, 500);
            test.addNote(69, 127, 500);
            test.addNote(67, 127, 1000);
            test.addNote(65, 127, 500);
            test.addNote(65, 127, 500);
            test.addNote(64, 127, 500);
            test.addNote(64, 127, 500);
            test.addNote(62, 127, 500);
            test.addNote(62, 127, 500);
            test.addNote(60, 127, 1000);
    
        }
    }
    Last edited by caustr01; 03-17-2014 at 07:41 PM.

  4. #4
    jashburn is offline Senior Member
    Join Date
    Feb 2014
    Posts
    219
    Rep Power
    1

    Default Re: Help with code. Midi Player

    You can only store 1 object per element in an ArrayList, and so you'll need an ArrayList each for notes, velocities and durations. However if you write a custom class (i.e., the Note class I mentioned in my last post) containing fields for note, velocity and duration - much like the UserInfo class in the stackoverflow example - you can then use just 1 ArrayList to store instances of this custom class. You'll have:

    Each element in ArrayList =[contains]=> a Note object =[that has]=> note, velocity and duration

  5. #5
    caustr01 is offline Member
    Join Date
    Mar 2014
    Posts
    6
    Rep Power
    0

    Default Re: Help with code. Midi Player

    Like this?
    Java Code:
    public class Song {
    
        private String name;
        private ArrayList<Info> addNote;
    
        public Song() {
            name = "Unknown";
            addNote = new ArrayList<Info>();
        }
    
        public Song(String nam) {
            name = nam;
        }
    
        public class Info {
    
            int note;
            int velocity;
            int duration;
    
        }
    
        public void addNote(int note, int velocity, int duration) {
    
            Info n = new Info(note, velocity, duration); //getting error
            addNote.add(60, 127, 500); //getting error
            
        }

  6. #6
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,601
    Rep Power
    5

    Default Re: Help with code. Midi Player

    When you play a MIDI note you send it with the Receiver via Reciever.send(MidiMessage msg, long timestamp). You can use ShortMessage and the various constants to set values. You can even encode the channel into the message. So, you can have an ArrayList<ShortMessage> to contain your premade tones. Some systems ignore the timestamp value.

    Regards,
    Jim
    Last edited by jim829; 03-18-2014 at 12:42 AM.
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  7. #7
    jashburn is offline Senior Member
    Join Date
    Feb 2014
    Posts
    219
    Rep Power
    1

    Default Re: Help with code. Midi Player

    You're getting there. :-)

    Quote Originally Posted by caustr01 View Post
    Like this?
    Java Code:
    public class Song {
    
        private String name;
        private ArrayList<Info> addNote;
    
        // ... and so on ...
    
        public class Info {
    
            int note;
            int velocity;
            int duration;
    
        }
    
        public void addNote(int note, int velocity, int duration) {
    
            Info n = new Info(note, velocity, duration); //getting error
            addNote.add(60, 127, 500); //getting error
            
        }
    Almost. Compare the code above with the example given in the stackoverflow post (java - How to create an arraylist class that can store multiple objects? - Stack Overflow) you referred to previously (but edited out when you modified your reply above):

    Java Code:
    class UserInfo {
        String user;
        String pass;
        String secretCode;
    }
    
    ...
    
    public void addUser(String i, String j, String k) {
        UserInfo newUser = new UserInfo();
        newUser.user = i;
        newUser.pass = j;
        newUser.secretCode = k;
        InfoList.add(newUser);
    }
    See why you're getting the errors?

    Quote Originally Posted by caustr01 View Post
    I am a bit confused on the parameters for playSong() because in order for the noteOn, sleep etc to work i need to put in the playSong(int note, int velocity, int duration) or am I missing something.
    Yup, you're indeed missing something. Referring back to the example given in your original post:

    Java Code:
    test.playSong();
    Look again - playSong() - no parameters. Hence I wrote in my previous reply,

    3. playSong method implementation

    Unlike your current implementation, this method's signature does not have parameters.

    I also wrote before that,

    Based on the example and guideline 3, the playSong method should look like this:

    Java Code:
    public void playSong()

    Quote Originally Posted by caustr01 View Post
    By the way you made it sound I need to use a loop in order to iterate through the arrays and the code above?
    Indeed you do.

    Once all the test.addNote(.., ..., ...) calls have been made in the main method, the addNote ArrayList will contain a collection of Info objects that were added via the public void addNote(int note, int velocity, int duration) method.

    In the playSong method, once you have set up the Synthesizer, channels and instruments, loop through the addNote ArrayList. As you loop, for each Info object in the ArrayList make the noteOn, sleep and noteOff calls using the note, velocity and duration data stored within the Info object.

    Additional notes:
    • Some will say the way you wrote the Info class with direct access to the note, velocity and duration fields (following the stackoverflow example) is not good practice. That is a topic of discussion for another day in a different thread.
    • You've named the ArrayList addNote, and there is also have a method called addNote. You should rename the ArrayList as it can be confused with the method since they have the same name. Call the ArrayList notesList or something similar.

  8. #8
    caustr01 is offline Member
    Join Date
    Mar 2014
    Posts
    6
    Rep Power
    0

    Default Re: Help with code. Midi Player

    No errors still not playing music :/
    Java Code:
    package song;
    
    import java.util.ArrayList;
    import javax.sound.midi.*;
    
    public class Song {
    
        private String name;
        private ArrayList<Info> notes;
    
        public Song() {
            name = "Unknown";
            notes = new ArrayList<Info>();
        }
    
        public Song(String nam) {
            name = nam;
            notes = new ArrayList<Info>();
    
        }
    
        public String getName() {
            return name;
        }
    
        public class Info {
            int note;
            int velocity;
            int duration;
            
            private Info(int note, int velocity, int duration) {
                this.note = note;
                this.velocity = velocity;
                this.duration = duration;
            }
        }
    
        public void addNote(int note, int velocity, int duration) {
    
            Info info = new Info(note, velocity, duration);
    
            notes.add(info);
    
        }
    
        public void playSong() {
    
            Synthesizer synth = null;
            try {
                synth = MidiSystem.getSynthesizer();
            } catch (MidiUnavailableException e) {
            }
            try {
                synth.open();
            } catch (MidiUnavailableException e) {
                e.printStackTrace();
    
                System.exit(1);
            }
    
            MidiChannel[] channels = synth.getChannels();
    
            Instrument instruments[] = synth.getAvailableInstruments();
            synth.loadInstrument(instruments[0]);
            channels[0].programChange(74);
             
            for (Info note : notes) {
                channels[0].noteOn(note.note, note.velocity);
                try {
                    Thread.sleep(note.duration);
                } catch (InterruptedException e) {
                }
                channels[0].noteOff(note.note);
            }
        }
    
        public static void main(String[] args) {
            Song test = new Song("Twinkle Twinkle Little Star");
            test.addNote(60, 127, 500);
            test.addNote(60, 127, 500);
            test.addNote(67, 127, 500);
            test.addNote(67, 127, 500);
            test.addNote(69, 127, 500);
            test.addNote(69, 127, 500);
            test.addNote(67, 127, 1000);
            test.addNote(65, 127, 500);
            test.addNote(65, 127, 500);
            test.addNote(64, 127, 500);
            test.addNote(64, 127, 500);
            test.addNote(62, 127, 500);
            test.addNote(62, 127, 500);
            test.addNote(60, 127, 1000);
            test.playSong();
    
        }
    }
    Last edited by caustr01; 03-18-2014 at 09:16 AM.

  9. #9
    jashburn is offline Senior Member
    Join Date
    Feb 2014
    Posts
    219
    Rep Power
    1

    Default Re: Help with code. Midi Player

    Doesn't play music for you? I just tried the code above and it does work for me!

    If it's really not playing, try commenting out these lines:

    Java Code:
    		Instrument instruments[] = synth.getAvailableInstruments();
    		synth.loadInstrument(instruments[0]);
    		channels[0].programChange(74);
    Also, try adding synth.close(); at the bottom of the playSong method.

  10. #10
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,601
    Rep Power
    5

    Default Re: Help with code. Midi Player

    It may be possible the synthesizer volume is all the way down. On some OS's (e.g. Windows) each audio device has its own volume control.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  11. #11
    caustr01 is offline Member
    Join Date
    Mar 2014
    Posts
    6
    Rep Power
    0

    Default Re: Help with code. Midi Player

    Nevermind it worked! I am not sure why it wasn't working last night because I tried again this morning without changing anything and it worked this time! Yay thank you for your help!! :)

  12. #12
    jashburn is offline Senior Member
    Join Date
    Feb 2014
    Posts
    219
    Rep Power
    1

    Default Re: Help with code. Midi Player

    Cool! You're welcome. Now that it's working, can I have Chopin's Piano Concerto No. 1 in E minor, please? ;-)

  13. #13
    caustr01 is offline Member
    Join Date
    Mar 2014
    Posts
    6
    Rep Power
    0

    Default Re: Help with code. Midi Player

    Bahahah Ill let you know if I ever get around to that :P !

Similar Threads

  1. Replies: 1
    Last Post: 12-18-2013, 03:22 AM
  2. Java midi player not work with all files
    By campello.davide in forum Advanced Java
    Replies: 0
    Last Post: 07-17-2013, 09:44 PM
  3. Java Midi player
    By Suende in forum New To Java
    Replies: 21
    Last Post: 04-17-2011, 06:32 PM
  4. MIDI - Music Player Help
    By bs3ac in forum New To Java
    Replies: 0
    Last Post: 08-29-2010, 01:03 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •