package tts import "math" // Pitch shifting without changing duration: time-stretch by the pitch factor, // then resample by it. This is a line-for-line port of PitchShifter.java in // android-engine; both ends must keep the same algorithm and parameters so the // same text produces subjectively identical audio. const ( grain = 1024 overlap = 512 hops = grain - overlap search = 128 ) func PitchShiftNeeded(pitch float32) bool { return math.Abs(float64(pitch-1)) >= 0.01 } func ShiftPitch(samples []float32, factor float32) []float32 { if len(samples) == 0 || !PitchShiftNeeded(factor) { return samples } stretched := timeStretch(samples, factor) return resample(stretched, factor) } func timeStretch(in []float32, factor float32) []float32 { originalLength := len(in) padded := make([]float32, len(in)+2*grain) // Reflect boundaries so even sub-window sounds retain their energy. for i := range padded { at := i - grain if len(in) == 1 { padded[i] = in[0] continue } period := 2 * (len(in) - 1) at = ((at % period) + period) % period if at >= len(in) { at = period - at } padded[i] = in[at] } in = padded hopA := roundInt(float32(hops) / factor) if hopA < 1 { hopA = 1 } window := hann(grain) expected := roundInt(float32(len(in)) * factor) if expected < grain { expected = grain } out := make([]float32, expected+grain) weights := make([]float32, len(out)) inPos, outPos := 0, 0 for inPos+grain <= len(in) { best := inPos if outPos > 0 { from := inPos - search if from < 0 { from = 0 } to := inPos + search if to > len(in)-grain { to = len(in) - grain } bestCorr := 0.0 for cand := from; cand <= to; cand += 4 { var corr float64 for i := 0; i < overlap; i++ { corr += float64(in[cand+i]) * float64(out[outPos+i]) } if corr > bestCorr { bestCorr = corr best = cand } } } for i := 0; i < grain; i++ { out[outPos+i] += in[best+i] * window[i] weights[outPos+i] += window[i] } inPos += hopA outPos += hops } length := max(1, roundInt(float32(originalLength)*factor)) offset := roundInt(float32(grain) * factor) result := make([]float32, length) for i := range result { at := offset + i if at < len(out) && weights[at] > 0.00001 { result[i] = out[at] / weights[at] } } return result } func resample(in []float32, factor float32) []float32 { outLen := roundInt(float32(len(in)) / factor) if outLen < 1 { outLen = 1 } out := make([]float32, outLen) for i := 0; i < outLen; i++ { pos := float64(i) * float64(factor) i0 := int(pos) if i0 >= len(in) { break } i1 := i0 + 1 if i1 > len(in)-1 { i1 = len(in) - 1 } frac := pos - float64(i0) out[i] = float32(float64(in[i0])*(1-frac) + float64(in[i1])*frac) } return out } func hann(size int) []float32 { w := make([]float32, size) for i := 0; i < size; i++ { w[i] = float32(0.5 - 0.5*math.Cos(2*math.Pi*float64(i)/float64(size-1))) } return w } // roundInt matches Java Math.round(float): floor(x + 0.5). func roundInt(x float32) int { return int(math.Floor(float64(x) + 0.5)) }