欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java中如何取得midi音乐的最大和弦数 音乐JavaJ# 

程序员文章站 2022-05-28 18:24:57
...
midi音乐的最大和弦数就是最大复音数,所谓复音就是同一时间点(tick)有多种声音,而这时的声音的种数就是复音数,最大复音数就是一首乐曲中复音数最大的那个时间点的复音数。在midi中声音是使用事件(Event)来记录的,事件有发生时间(tick)和该事件的内容(MidiMessage,即声音)两个属性。所以,复音数在midi里面就是同一个tick的事件的个数,最大复音数就是其最大值。java程序如下:
    public long getMaxChordNum(String midi); throws Exception {
        File mf = new File(midi);;
        Map m = new HashMap();;
        Track[] tracks = MidiSystem.getSequence(mf);.getTracks();;
        for (int i = 0; i < tracks.length; i++); {
            for (int j = 0; j < tracks[i].size();; j++); {
                Long ltick = new Long(tracks[i].get(j);.getTick(););;
                if (ltick.longValue(); == 0L); {
                    continue;
                }
                if (m.containsKey(ltick);); {
                    Long value = (Long); m.get(ltick);;
                    m.put(ltick, new Long(value.longValue(); + 1););;
                } else {
                    m.put(ltick, new Long(1););;
                }
            }
        }

        Set keys = m.keySet();;
        Iterator keyit = keys.iterator();;
        long max = 0;
        while (keyit.hasNext();); {
            Long key = (Long); keyit.next();;
            Long value = (Long); m.get(key);;
            long tmp = value.longValue();;
            if (tmp > max); {
                max = tmp;
            }
        }
        return max;
    }


效率提高版
    public long getMaxChordNum(Track[] tracks); throws Exception {
        long max = 0;
        if (tracks != null && tracks.length > 0); {
            int size = 0;
            for (int i = 0; i < tracks.length; i++); {
                size += tracks[i].size();;
            }
            long[] ticks = new long[size];
            int idx = 0;
            for (int i = 0; i < tracks.length; i++); {
                for (int j = 0; j < tracks[i].size();; j++); {
                    ticks[idx++] = tracks[i].get(j);.getTick();;
                }
            }
            Arrays.sort(ticks);;
            long pretick = 0;
            long precnt = 1;
            for (int i = 0; i < size; i++); {
                if (ticks[i] == 0);
                    continue;
                if (ticks[i] == pretick); {
                    precnt++;
                } else {
                    max = max < precnt ? precnt : max;
                    pretick = ticks[i];
                    precnt = 1;
                }
            }
            max = max < precnt ? precnt : max;
        }
        return max;
    }
相关标签: 音乐 Java J#