Browse Source

Merge branch 'vip_price_827'

# Conflicts:
#	mec-biz/src/main/java/com/ym/mec/biz/dal/dto/SoundCompareHelper.java
#	mec-biz/src/main/java/com/ym/mec/biz/service/impl/SoundCompareHandler.java
yonge 4 years ago
parent
commit
05c3f03bc7

+ 167 - 30
mec-biz/src/main/java/com/ym/mec/biz/dal/dto/SoundCompareHelper.java

@@ -4,6 +4,7 @@ import be.tarsos.dsp.AudioEvent;
 import be.tarsos.dsp.SilenceDetector;
 import be.tarsos.dsp.pitch.PitchDetectionHandler;
 import be.tarsos.dsp.pitch.PitchDetectionResult;
+import com.alibaba.fastjson.JSON;
 import com.ym.mec.biz.dal.enums.DeviceTypeEnum;
 import com.ym.mec.biz.dal.enums.HeardLevelEnum;
 import com.ym.mec.biz.service.impl.SoundCompareHandler;
@@ -17,6 +18,7 @@ import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.stream.Collectors;
 
 /**
  * @Author Joburgess
@@ -56,21 +58,21 @@ public class SoundCompareHelper implements PitchDetectionHandler {
     @ApiModelProperty(value = "播放速度")
     private int speed = 90;
 
-    @ApiModelProperty(value = "小节xml信息字典")
+    @ApiModelProperty(value = "xml中每个小节的音符详情")
     private Map<Integer, List<MusicPitchDetailDto>> measureXmlInfoMap = new HashMap<>();
 
-    @ApiModelProperty(value = "小节结束时间字典")
+    @ApiModelProperty(value = "xml中每小节开始时间、结束时间")
     private Map<Integer, MusicPitchDetailDto> measureEndTime = new HashMap<>();
 
-    @ApiModelProperty(value = "录音音频信息")
-    private List<MusicPitchDetailDto> recordMeasurePithInfo = new ArrayList<>();
+//    @ApiModelProperty(value = "录音音频信息")
+//    private List<MusicPitchDetailDto> recordMeasurePithInfo = new ArrayList<>();
 
     @ApiModelProperty(value = "小节分数记录")
     private Map<String, BigDecimal> userScoreMap = new HashMap<>();
 
     private Map<Integer, Map<String, Object>> userMeasureScoreMap = new HashMap<>();
 
-    @ApiModelProperty(value = "音符频率字典")
+    @ApiModelProperty(value = "xml中每个音符频率")
     private Map<Integer, Float> musicalNotePitchMap = new HashMap<>();
 
     @ApiModelProperty(value = "每个音符评测结果")
@@ -79,8 +81,15 @@ public class SoundCompareHelper implements PitchDetectionHandler {
     @ApiModelProperty(value = "偏移时间量,解决客户端录音播放不同步导致的声音留白")
     private int offsetTime = -1;
 
+    /** xml中每个音符详情 */
     private List<MusicPitchDetailDto> musicXmlInfos;
 
+    /** 第一个音符前有多少个字节 */
+    private long firstMeasureStartBytes = 0;
+
+    /** 文件的总字节数长度 */
+    private long recordBytes = 0;
+
     private String clientId;
 
     private Integer detailId;
@@ -89,23 +98,48 @@ public class SoundCompareHelper implements PitchDetectionHandler {
 
     private String xmlUrl;
 
+    /** 演奏音频数据中频率变更明显持续数量 */
+    private int obviousChangeNum = 0;
+
+    /** 演奏音频中但前小节所有频率数据 */
+    private List<MusicPitchDetailDto> currPitchInfos = new ArrayList<>();
+    private List<MusicPitchDetailDto> currTmpPitchInfos = new ArrayList<>();
+
+    private List<MusicPitchDetailDto> recordMeasurePitchInfos = new ArrayList<>();
+
     /**
      * @describe 分贝检测器
      */
     public SilenceDetector silenceDetector = new SilenceDetector();
 
+    /**
+     * xml中每个音符详情 
+     * @return
+     */
     public List<MusicPitchDetailDto> getMusicXmlInfos() {
         return musicXmlInfos;
     }
 
+    /**
+     * xml中每个音符详情 
+     * @return
+     */
     public void setMusicXmlInfos(List<MusicPitchDetailDto> musicXmlInfos) {
         this.musicXmlInfos = musicXmlInfos;
     }
 
+    /**
+     * xml中每个音符对应的频率
+     * @return
+     */
     public Map<Integer, Float> getMusicalNotePitchMap() {
         return musicalNotePitchMap;
     }
 
+    /**
+     * xml中每个音符对应的频率
+     * @return
+     */
     public void setMusicalNotePitchMap(Map<Integer, Float> musicalNotePitchMap) {
         this.musicalNotePitchMap = musicalNotePitchMap;
     }
@@ -198,6 +232,10 @@ public class SoundCompareHelper implements PitchDetectionHandler {
         this.musicScoreId = musicScoreId;
     }
 
+    /**
+     * 录音文件
+     * @return
+     */
     public RandomAccessFile getAccessFile() {
         return accessFile;
     }
@@ -218,6 +256,10 @@ public class SoundCompareHelper implements PitchDetectionHandler {
         this.recordFilePath = recordFilePath;
     }
 
+    /**
+     * 录音文件
+     * @return
+     */
     public void setAccessFile(RandomAccessFile accessFile) {
         this.accessFile = accessFile;
     }
@@ -238,77 +280,172 @@ public class SoundCompareHelper implements PitchDetectionHandler {
         this.measureStartTime = measureStartTime;
     }
 
+    /**
+     * xml中每个小节的音符详情
+     * @return
+     */
     public Map<Integer, List<MusicPitchDetailDto>> getMeasureXmlInfoMap() {
         return measureXmlInfoMap;
     }
 
+    /**
+     * xml中每个小节的音符详情
+     * @return
+     */
     public void setMeasureXmlInfoMap(Map<Integer, List<MusicPitchDetailDto>> measureXmlInfoMap) {
         this.measureXmlInfoMap = measureXmlInfoMap;
     }
 
+    /**
+     * xml中每小节开始时间、结束时间
+     * @return
+     */
     public Map<Integer, MusicPitchDetailDto> getMeasureEndTime() {
         return measureEndTime;
     }
 
+    /**
+     * xml中每小节开始时间、结束时间
+     * @param measureEndTime
+     */
     public void setMeasureEndTime(Map<Integer, MusicPitchDetailDto> measureEndTime) {
         this.measureEndTime = measureEndTime;
     }
 
+    /**
+     * 每个音符的评测结果
+     * @return
+     */
     public List<MusicalNotesPlayStatDto> getMusicalNotesPlayStats() {
         return musicalNotesPlayStats;
     }
 
+    /**
+     * 每个音符的评测结果
+     * @return
+     */
     public void setMusicalNotesPlayStats(List<MusicalNotesPlayStatDto> musicalNotesPlayStats) {
         this.musicalNotesPlayStats = musicalNotesPlayStats;
     }
 
-    public List<MusicPitchDetailDto> getRecordMeasurePithInfo() {
-        return recordMeasurePithInfo;
-    }
-
-    public void setRecordMeasurePithInfo(List<MusicPitchDetailDto> recordMeasurePithInfo) {
-        this.recordMeasurePithInfo = recordMeasurePithInfo;
-    }
-
+    /**
+     * 小节累积得分(节奏、音准、完整度)
+     * @return
+     */
     public Map<String, BigDecimal> getUserScoreMap() {
         return userScoreMap;
     }
 
+    /**
+     * 小节累积得分(节奏、音准、完整度)
+     * @return
+     */
     public void setUserScoreMap(Map<String, BigDecimal> userScoreMap) {
         this.userScoreMap = userScoreMap;
     }
 
+    /**
+     * 第一个音符前有多少个字节
+     * @return
+     */
+    public long getFirstMeasureStartBytes() {
+        return firstMeasureStartBytes;
+    }
+
+    /**
+     * 第一个音符前有多少个字节
+     * @param firstMeasureStartBytes
+     */
+    public void setFirstMeasureStartBytes(long firstMeasureStartBytes) {
+        this.firstMeasureStartBytes = firstMeasureStartBytes;
+    }
+
+    /**
+     * 文件的总字节数长度
+     * @return
+     */
+    public long getRecordBytes() {
+        return recordBytes;
+    }
+
+    /**
+     * 文件的总字节数长度
+     * @param recordBytes
+     */
+    public void setRecordBytes(long recordBytes) {
+        this.recordBytes = recordBytes;
+    }
+
+    /**
+     * 小节得分结果
+     * @return
+     */
     public Map<Integer, Map<String, Object>> getUserMeasureScoreMap() {
         return userMeasureScoreMap;
     }
 
+    /**
+     * 小节得分结果
+     * @return
+     */
     public void setUserMeasureScoreMap(Map<Integer, Map<String, Object>> userMeasureScoreMap) {
         this.userMeasureScoreMap = userMeasureScoreMap;
     }
 
+    public List<MusicPitchDetailDto> getRecordMeasurePitchInfos() {
+        return recordMeasurePitchInfos;
+    }
+
+    public void setRecordMeasurePitchInfos(List<MusicPitchDetailDto> recordMeasurePitchInfos) {
+        this.recordMeasurePitchInfos = recordMeasurePitchInfos;
+    }
+
     @Override
     public void handlePitch(PitchDetectionResult pitchDetectionResult, AudioEvent audioEvent) {
         int timeStamp = (int) (measureStartTime + audioEvent.getTimeStamp()*1000);
         float pitch = pitchDetectionResult.getPitch();
-        if(offsetTime == -1 && !DeviceTypeEnum.IOS.equals(deviceType) && pitch>0){
-            int preTimeStamp = CollectionUtils.isEmpty(recordMeasurePithInfo)?0:recordMeasurePithInfo.get(recordMeasurePithInfo.size()-1).getTimeStamp();
-            offsetTime = timeStamp - (timeStamp - preTimeStamp)/2;
-            for (MusicPitchDetailDto musicXmlInfo : musicXmlInfos) {
-                if(!musicXmlInfo.getDontEvaluating()){
-                    if(offsetTime > musicXmlInfo.getTimeStamp())
-                        offsetTime = offsetTime - musicXmlInfo.getTimeStamp();
-                    break;
-                }
+        int decibel = (int) (100 - Math.abs(silenceDetector.currentSPL()));
+
+        if(decibel <= SoundCompareHandler.soundCompareConfig.validDb){
+            pitch = -1;
+            decibel = 0;
+        }
+
+        SoundCompareHandler.LOGGER.info("时间:{}, 频率:{}, 分贝:{}", timeStamp, pitch, decibel);
+
+        //上次的频率与本次的频率相差10hz或分贝相差10
+        if(currPitchInfos.size()>0&&(Math.abs(currPitchInfos.get(currPitchInfos.size()-1).getFrequency()-pitch)>10||Math.abs(currPitchInfos.get(currPitchInfos.size()-1).getDecibel()-decibel)>10)){
+            Double avgPitch = currPitchInfos.stream().skip(1).collect(Collectors.averagingDouble(MusicPitchDetailDto::getFrequency));
+            Double avgDb = currPitchInfos.stream().skip(1).collect(Collectors.averagingDouble(MusicPitchDetailDto::getDecibel));
+
+            MusicPitchDetailDto measureDetail = new MusicPitchDetailDto(currPitchInfos.get(0).getTimeStamp(), avgPitch.floatValue(), avgDb);
+            measureDetail.setEndTimeStamp(timeStamp);
+            measureDetail.setDuration(measureDetail.getEndTimeStamp()-measureDetail.getTimeStamp());
+
+            if(measureDetail.getDuration()>25&&(avgPitch>0||avgDb>SoundCompareHandler.soundCompareConfig.validDb)){
+                recordMeasurePitchInfos.add(measureDetail);
             }
-            for (Map.Entry<Integer, MusicPitchDetailDto> musicPitchDetailDtoEntry : measureEndTime.entrySet()) {
-                musicPitchDetailDtoEntry.getValue().setTimeStamp(musicPitchDetailDtoEntry.getValue().getTimeStamp() + offsetTime);
-                musicPitchDetailDtoEntry.getValue().setEndTimeStamp(musicPitchDetailDtoEntry.getValue().getEndTimeStamp() + offsetTime);
+
+            currPitchInfos.clear();
+
+            //初始化偏移时间
+            if(offsetTime == -1 && recordMeasurePitchInfos.size() == 1){
+                offsetTime = recordMeasurePitchInfos.get(0).getTimeStamp();
+                for (MusicPitchDetailDto musicXmlInfo : musicXmlInfos) {
+                    if(!musicXmlInfo.getDontEvaluating()){
+                        if(offsetTime > musicXmlInfo.getTimeStamp()) {
+                            offsetTime = offsetTime - musicXmlInfo.getTimeStamp();
+                        }
+                        break;
+                    }
+                }
+                musicXmlInfos.forEach(e->e.setTimeStamp(e.getTimeStamp()+offsetTime));//??????
+                for (Map.Entry<Integer, MusicPitchDetailDto> musicPitchDetailDtoEntry : measureEndTime.entrySet()) {
+                    musicPitchDetailDtoEntry.getValue().setTimeStamp(musicPitchDetailDtoEntry.getValue().getTimeStamp() + offsetTime);
+                    musicPitchDetailDtoEntry.getValue().setEndTimeStamp(musicPitchDetailDtoEntry.getValue().getEndTimeStamp() + offsetTime);
+                }
             }
         }
-        if(silenceDetector.currentSPL()< SoundCompareHandler.soundCompareConfig.validDb){
-            pitch = -1;
-        }
-//            LOGGER.info("时间:{}, 频率:{}, 分贝:{}", timeStamp, pitch, silenceDetecor.currentSPL());
-        recordMeasurePithInfo.add(new MusicPitchDetailDto(timeStamp, pitch, silenceDetector.currentSPL()));
+        currPitchInfos.add(new MusicPitchDetailDto(timeStamp, pitch, decibel));
     }
 }

+ 73 - 127
mec-biz/src/main/java/com/ym/mec/biz/service/impl/SoundCompareHandler.java

@@ -6,6 +6,7 @@ import be.tarsos.dsp.pitch.PitchProcessor;
 import be.tarsos.dsp.util.PitchConverter;
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONObject;
+import com.alibaba.fastjson.serializer.SerializerFeature;
 import com.ym.mec.biz.dal.config.SoundCompareConfig;
 import com.ym.mec.biz.dal.dao.SysMusicScoreAccompanimentDao;
 import com.ym.mec.biz.dal.dto.*;
@@ -31,7 +32,6 @@ import org.springframework.web.socket.WebSocketSession;
 
 import javax.sound.sampled.UnsupportedAudioFileException;
 import java.io.File;
-import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.io.RandomAccessFile;
 import java.math.BigDecimal;
@@ -50,7 +50,7 @@ import static com.ym.mec.biz.service.SoundSocketService.VIDEO_UPDATE;
 @Service
 public class SoundCompareHandler implements WebSocketEventHandler {
 
-    private final Logger LOGGER = LoggerFactory.getLogger(SoundCompareHandler.class);
+    public static final Logger LOGGER = LoggerFactory.getLogger(SoundCompareHandler.class);
 
     private BigDecimal oneHundred = new BigDecimal(100);
 
@@ -99,6 +99,9 @@ public class SoundCompareHandler implements WebSocketEventHandler {
                 userSoundInfoMap.get(phone).setMusicXmlInfos(musicXmlInfos);
                 musicXmlInfos = musicXmlInfos.stream().filter(m->!m.getDontEvaluating()).collect(Collectors.toList());
                 userSoundInfoMap.get(phone).setMusicScoreId(bodyObject.getInteger("id"));
+                if(bodyObject.containsKey("beatLength")){
+                    userSoundInfoMap.get(phone).setFirstMeasureStartBytes((long) (bodyObject.getLong("beatLength")/1000f*(soundCompareConfig.audioFormat.getFrameSize()*soundCompareConfig.audioFormat.getFrameRate())));
+                }
                 if(bodyObject.containsKey("platform")){
                     userSoundInfoMap.get(phone).setDeviceType(DeviceTypeEnum.valueOf(bodyObject.getString("platform")));
                 }
@@ -148,8 +151,9 @@ public class SoundCompareHandler implements WebSocketEventHandler {
                     File file = new File(tmpDir+phone + "_"+ userSoundInfoMap.get(phone).getMusicScoreId() +"_"+ LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) +".wav");
                     userSoundInfoMap.get(phone).setFile(file);
                     userSoundInfoMap.get(phone).setAccessFile(new RandomAccessFile(file, "rw"));
+                    userSoundInfoMap.get(phone).getAccessFile().seek(44);
                     userSoundInfoMap.get(phone).setRecordFilePath(file.getAbsolutePath());
-                } catch (FileNotFoundException e) {
+                } catch (IOException e) {
                     throw new BizException("文件创建失败:", e);
                 }
                 break;
@@ -159,6 +163,7 @@ public class SoundCompareHandler implements WebSocketEventHandler {
                 }
                 try {
                     if(!CollectionUtils.isEmpty(userSoundInfoMap.get(phone).getMeasureEndTime())){
+                    	//这是最后播放的一小节吗?
                         Integer lastMeasureIndex = userSoundInfoMap.get(phone).getMeasureEndTime().keySet().stream().min(Integer::compareTo).get();
                         double recordTime = userSoundInfoMap.get(phone).getAccessFile().length()/(soundCompareConfig.audioFormat.getFrameSize()*soundCompareConfig.audioFormat.getFrameRate())*1000;
                         //如果结束时时长大于某小节,则此小节需要评分
@@ -178,10 +183,10 @@ public class SoundCompareHandler implements WebSocketEventHandler {
                 createHeader(phone, false);
                 break;
             case SoundSocketService.PROXY_MESSAGE:
-                if(DeviceTypeEnum.IOS.equals(userSoundInfoMap.get(phone).getDeviceType())&&bodyObject.containsKey(SoundSocketService.OFFSET_TIME)){
-                    int offsetTime = bodyObject.getIntValue(SoundSocketService.OFFSET_TIME);
-                    calOffsetTime(phone, offsetTime);
-                }
+//                if(DeviceTypeEnum.IOS.equals(userSoundInfoMap.get(phone).getDeviceType())&&bodyObject.containsKey(SoundSocketService.OFFSET_TIME)){
+//                    int offsetTime = bodyObject.getIntValue(SoundSocketService.OFFSET_TIME);
+//                    calOffsetTime(phone, offsetTime);
+//                }
                 break;
             case VIDEO_UPDATE:
                 SysMusicCompareRecord update = null;
@@ -207,24 +212,29 @@ public class SoundCompareHandler implements WebSocketEventHandler {
         if(!userSoundInfoMap.containsKey(phone)){
             return;
         }
+        userSoundInfoMap.get(phone).setRecordBytes(userSoundInfoMap.get(phone).getRecordBytes()+message.getPayloadLength());
+        if(userSoundInfoMap.get(phone).getRecordBytes()<userSoundInfoMap.get(phone).getFirstMeasureStartBytes()){
+            return;
+        }
+        //待优化:节拍器占用的字节未被完全剔除
         try {
             if(Objects.nonNull(userSoundInfoMap.get(phone).getAccessFile())){
                 userSoundInfoMap.get(phone).getAccessFile().write(message.getPayload().array());
+            }else{
+                return;
             }
 
             AudioDispatcher dispatcher = AudioDispatcherFactory.fromByteArray(message.getPayload().array(), soundCompareConfig.audioFormat, soundCompareConfig.simpleSize, soundCompareConfig.overlap);
-
             dispatcher.addAudioProcessor(userSoundInfoMap.get(phone).silenceDetector);
             dispatcher.addAudioProcessor(new PitchProcessor(soundCompareConfig.algo, soundCompareConfig.simpleRate, soundCompareConfig.simpleSize, userSoundInfoMap.get(phone)));
             dispatcher.run();
-            if(Objects.isNull(userSoundInfoMap.get(phone).getAccessFile())){
-                return;
-            }
 
+            //待优化:文件大小需要去掉头信息(44)
             double recordTime = userSoundInfoMap.get(phone).getAccessFile().length()/(soundCompareConfig.audioFormat.getFrameSize()*soundCompareConfig.audioFormat.getFrameRate())*1000;
             userSoundInfoMap.get(phone).setMeasureStartTime(recordTime);
+
             for (Map.Entry<Integer, MusicPitchDetailDto> userMeasureEndTimeMapEntry : userSoundInfoMap.get(phone).getMeasureEndTime().entrySet()) {
-                if(recordTime>(userMeasureEndTimeMapEntry.getValue().getEndTimeStamp())){
+                if(recordTime>(userMeasureEndTimeMapEntry.getValue().getEndTimeStamp()+100)){
                     if(userMeasureEndTimeMapEntry.getValue().getDontEvaluating()){
                         continue;
                     }else{
@@ -261,6 +271,7 @@ public class SoundCompareHandler implements WebSocketEventHandler {
             musicPitchDetailDtoEntry.getValue().setTimeStamp(musicPitchDetailDtoEntry.getValue().getTimeStamp() + offsetTime);
             musicPitchDetailDtoEntry.getValue().setEndTimeStamp(musicPitchDetailDtoEntry.getValue().getEndTimeStamp() + offsetTime);
         }
+        userSoundInfoMap.get(phone).getMusicXmlInfos().forEach(e->e.setTimeStamp(e.getTimeStamp()+offsetTime));
     }
 
     /**
@@ -345,113 +356,36 @@ public class SoundCompareHandler implements WebSocketEventHandler {
             int totalCompareNum = userSoundInfoMap.get(phone).getMeasureXmlInfoMap().get(measureIndex).size();
 
             for (int i = 0; i < userSoundInfoMap.get(phone).getMeasureXmlInfoMap().get(measureIndex).size(); i++) {
+            	//获取音符信息
                 MusicPitchDetailDto musicXmlInfo = userSoundInfoMap.get(phone).getMeasureXmlInfoMap().get(measureIndex).get(i);
 
-                int ot5 = (int) (musicXmlInfo.getDuration()*0.1);
-                int startTimeStamp = musicXmlInfo.getTimeStamp() + userSoundInfoMap.get(phone).getOffsetTime() + ot5;
-                int endTimeStamp = musicXmlInfo.getTimeStamp()  + userSoundInfoMap.get(phone).getOffsetTime() + musicXmlInfo.getDuration() - ot5;
-
-                //时间范围内有效节奏数量
-                float cadenceValidNum = 0;
-                //时间范围内有效音频数量
-                float integrityValidNum = 0;
-                //时间范围内匹配次数
-                float compareNum = 0;
+                int startTimeStamp = musicXmlInfo.getTimeStamp();
+                int endTimeStamp = musicXmlInfo.getTimeStamp() + musicXmlInfo.getDuration();
 
-                List<MusicPitchDetailDto> measureSoundPitchInfos = new ArrayList<>();
+                int ot5 = (int) (musicXmlInfo.getDuration()*0.22<70?70:musicXmlInfo.getDuration()*0.22);
+                int rightTimeRange = ot5>200?200:ot5;
 
-                for (int j = 0; j < userSoundInfoMap.get(phone).getRecordMeasurePithInfo().size(); j++) {
-                    MusicPitchDetailDto recordInfo = userSoundInfoMap.get(phone).getRecordMeasurePithInfo().get(j);
-                    //如果在时间范围之外直接跳过
-                    if(recordInfo.getTimeStamp()<startTimeStamp||recordInfo.getTimeStamp()>endTimeStamp){
-                        continue;
-                    }
-                    measureSoundPitchInfos.add(recordInfo);
-                    compareNum++;
-                    //如果在最低有效频率以下则跳过
-                    if(recordInfo.getFrequency()<soundCompareConfig.validFrequency&&musicXmlInfo.getFrequency()!=-1){
-                        continue;
-                    }
-                    cadenceValidNum++;
-                    //如果频率差值在节奏误差范围内
-//                    if(Math.abs(recordInfo.getFrequency()-musicXmlInfo.getFrequency())<=soundCompareConfig.integrityFrequencyRange){
-//                        integrityValidNum++;
-//                    }
-                }
-
-                //非正常频率次数
-                int errPitchNum = 0;
-                //分贝变化次数
-                int decibelChangeNum = 0;
-
-                if(CollectionUtils.isEmpty(measureSoundPitchInfos)){
-                    userSoundInfoMap.get(phone).getMusicalNotePitchMap().put(musicXmlInfo.getMusicalNotesIndex(), (float) 0);
-                }else{
-                    Map<Integer, Long> collect = measureSoundPitchInfos.stream().map(pitch -> (int)pitch.getFrequency()).collect(Collectors.groupingBy(Integer::intValue, Collectors.counting()));
-                    //出现次数最多的频率
-                    Integer pitch = collect.entrySet().stream().max(Comparator.comparing(e -> e.getValue())).get().getKey();
-                    //当前频率
-                    double cf = -1;
-                    //频率持续数量
-                    int fnum = 0;
-                    //是否演奏中
-                    boolean ing = false;
-                    //当前分贝
-                    double cd = 0;
-                    //分贝变化方向,-1变小,1变大
-                    int dcd = -1;
-                    //分贝持续数量
-                    int dnum = 0;
-                    for (MusicPitchDetailDto musicalNotesPitch : measureSoundPitchInfos) {
-                        //计算频率断层次数
-                        if (Math.abs(musicalNotesPitch.getFrequency() - cf) > 20){
-                            fnum ++;
-                        }
-                        if (fnum>=5){
-                            cf = musicalNotesPitch.getFrequency();
-                            fnum = 0;
-                            if (cf != -1){
-                                errPitchNum ++;
-                                ing = true;
-                                cd = musicalNotesPitch.getDecibel();
-                            }
-                        }
-                        //计算声音大小断层册数
-                        if(ing && Math.abs(musicalNotesPitch.getDecibel() - cd) > 10){
-                            dnum ++;
-                        }
-                        if (dnum > 2){
-                            int tdcd = cd > musicalNotesPitch.getDecibel() ? -1 : 1;
-                            cd = musicalNotesPitch.getDecibel();
-                            dnum = 0;
-                            if (tdcd != dcd) {
-                                decibelChangeNum++;
-                            }
-                            dcd = tdcd;
-                        }
-                    }
-                    userSoundInfoMap.get(phone).getMusicalNotePitchMap().put(musicXmlInfo.getMusicalNotesIndex(), (float) pitch);
-                }
+                // 待优化:结束时间应该是加偏移量
+                List<MusicPitchDetailDto> recordPitchs = userSoundInfoMap.get(phone).getRecordMeasurePitchInfos().stream().filter(m -> m.getTimeStamp()>=startTimeStamp-rightTimeRange && m.getTimeStamp() < endTimeStamp+rightTimeRange).collect(Collectors.toList());
 
                 boolean cadenceRight = false;
                 boolean intonationRight = false;
                 boolean integrityRight = false;
 
-                //有效节奏占比
-                float cadenceDuty = cadenceValidNum/compareNum;
-                //如果频率出现断层或这个音量出现断层,则当前音符节奏无效
-                if(errPitchNum>=2 || decibelChangeNum>1){
-                    cadenceDuty = 0;
+                float integrityDuty = 0;
+                if(recordPitchs.size()>0){
+                    integrityDuty = recordPitchs.get(0).getDuration()/(float)musicXmlInfo.getDuration();
                 }
+                integrityDuty = scoreMapping(integrityDuty, userSoundInfoMap.get(phone).getHeardLevel().getIntegrityRange(), 1);
                 //节奏
-                if(cadenceDuty>=userSoundInfoMap.get(phone).getHeardLevel().getCadenceRange()){
+                if(recordPitchs.size()==1){
                     cadenceNum++;
                     cadenceRight = true;
                 }
                 //音准、完成度
-                if (cadenceRight && !CollectionUtils.isEmpty(measureSoundPitchInfos)){
+                if (cadenceRight){
                     //音准
-                    Double avgPitch = measureSoundPitchInfos.stream().filter(pitch -> Math.abs((pitch.getFrequency()-musicXmlInfo.getFrequency()))<15).collect(Collectors.averagingDouble(pitch -> pitch.getFrequency()));
+                    float avgPitch = recordPitchs.get(0).getFrequency();
                     //音分
                     double recordCents = 0;
                     if (avgPitch > 0){
@@ -461,29 +395,40 @@ public class SoundCompareHandler implements WebSocketEventHandler {
                     if(musicXmlInfo.getFrequency()>0){
                         cents =  PitchConverter.hertzToAbsoluteCent(musicXmlInfo.getFrequency());
                     }
-                    double score = 100 - Math.round(Math.abs(cents - recordCents)) + userSoundInfoMap.get(phone).getHeardLevel().getIntonationCentsRange();
+                    double score = 100 - Math.round(Math.abs(cents - recordCents)) + 3;
                     if (score < 0){
                         score = 0;
                     }else if(score > 100){
                         score = 100;
                     }
-                    intonationScore += score;
-                    musicXmlInfo.setAvgFrequency(avgPitch.floatValue());
-                    intonationRight = score>70;
 
-                    if(score>0){
-                        integrityValidNum = measureSoundPitchInfos.stream().filter(pitch -> Math.abs((pitch.getFrequency()-musicXmlInfo.getFrequency()))<15).count();
-                    }else{
-                        integrityValidNum = 0;
+                    score = Math.pow(score/100f, userSoundInfoMap.get(phone).getHeardLevel().getIntonationCentsRange())*100;
+
+                    if(Objects.nonNull(userSoundInfoMap.get(phone).getSubjectId())&&userSoundInfoMap.get(phone).getSubjectId()==23){
+                        score = 100;
+                        integrityDuty = 1;
                     }
+
+                    intonationScore += score;
+                    musicXmlInfo.setAvgFrequency(avgPitch);
+                    intonationRight = score>70; //大于70分音准才正确?????
+
+                    integrityScore += integrityDuty;
+                    integrityRight = integrityDuty>0.7;//大于70%完整性才正确????
                 }
-                //完成度
-                if(integrityValidNum > compareNum){
-                    integrityValidNum = compareNum;
+
+                //如果当前音符不需要演奏
+                if (musicXmlInfo.getFrequency()<0&&recordPitchs.size()<=0){
+                    cadenceNum++;
+                    cadenceRight = true;
+
+                    intonationScore += 100;
+                    musicXmlInfo.setAvgFrequency(-1);
+                    intonationRight = true;
+
+                    integrityScore += 1;
+                    integrityRight = true;
                 }
-                float integrityDuty = integrityValidNum/compareNum;
-                integrityScore += integrityDuty;
-                integrityRight = integrityDuty>0.7;
 
                 if(!cadenceRight){
                     userSoundInfoMap.get(phone).getMusicalNotesPlayStats().add(new MusicalNotesPlayStatDto(musicXmlInfo.getMusicalNotesIndex(), MusicalErrorTypeEnum.CADENCE_WRONG));
@@ -528,6 +473,11 @@ public class SoundCompareHandler implements WebSocketEventHandler {
         createPushInfo(phone, "measureScore", measureIndex, intonation, cadence, integrity);
     }
 
+    private float scoreMapping(float score, float divisor, float maxValue){
+        score = score*divisor;
+        return score>maxValue?maxValue:score;
+    }
+
     /**
      * @describe 计算最终评分
      * @author Joburgess
@@ -543,15 +493,15 @@ public class SoundCompareHandler implements WebSocketEventHandler {
         BigDecimal integrity = BigDecimal.ZERO;
 
         if(currentCompareNum>0){
-            intonation = userSoundInfoMap.get(phone).getUserScoreMap().get("intonation").divide(new BigDecimal(currentCompareNum), 0, BigDecimal.ROUND_DOWN);
-            cadence = userSoundInfoMap.get(phone).getUserScoreMap().get("cadence").divide(new BigDecimal(currentCompareNum), 0, BigDecimal.ROUND_DOWN);
-            integrity = userSoundInfoMap.get(phone).getUserScoreMap().get("integrity").divide(new BigDecimal(currentCompareNum), 0, BigDecimal.ROUND_DOWN);
+            intonation = userSoundInfoMap.get(phone).getUserScoreMap().get("intonation").divide(new BigDecimal(currentCompareNum), 0, BigDecimal.ROUND_UP);
+            cadence = userSoundInfoMap.get(phone).getUserScoreMap().get("cadence").divide(new BigDecimal(currentCompareNum), 0, BigDecimal.ROUND_UP);
+            integrity = userSoundInfoMap.get(phone).getUserScoreMap().get("integrity").divide(new BigDecimal(currentCompareNum), 0, BigDecimal.ROUND_UP);
         }
 
         //计算分数并推送
         createPushInfo(phone, "overall", -1, intonation, cadence, integrity);
 
-        LOGGER.info("评分数据:{}", JSON.toJSONString(userSoundInfoMap.get(phone)));
+        LOGGER.info("评分数据:{}", JSON.toJSONString(userSoundInfoMap.get(phone), SerializerFeature.DisableCircularReferenceDetect));
     }
 
     /**
@@ -570,12 +520,8 @@ public class SoundCompareHandler implements WebSocketEventHandler {
         WebSocketInfo webSocketInfo = new WebSocketInfo();
         webSocketInfo.setHeader(new WebSocketInfo.Head(command));
         Map<String, Object> result = new HashMap<>(5);
-        //打击乐只看节奏分
-        BigDecimal score = cadence;
-        //非打击乐总分为平均分
-        if(Objects.isNull(userSoundInfoMap.get(phone).getSubjectId())||userSoundInfoMap.get(phone).getSubjectId()!=23){
-            score = intonation.add(cadence).add(integrity).divide(new BigDecimal(3), CommonConstants.DECIMAL_PLACE, BigDecimal.ROUND_DOWN).setScale(0, BigDecimal.ROUND_UP);
-        }
+        BigDecimal score  = intonation.add(cadence).add(integrity).divide(new BigDecimal(3), CommonConstants.DECIMAL_PLACE, BigDecimal.ROUND_DOWN).setScale(0, BigDecimal.ROUND_UP);
+
         result.put("score", score);
         result.put("intonation", intonation);
         result.put("cadence", cadence);