I am trying to create a karaoke-like application but I'm facing a problem.
I have a song as an mp3 and the corresponding lyrics shown in a UITextView. I want to highlight/underline (or something like this) the words that are heard from that mp3 file. I have the corresponding timing for each word (startTime, endTime, duration) but I have no idea how to get them highlighted.
I've searched on Stack Overflow but none of the already posted questions solved my problem.
I've seen that UITextView could be inappropriate for my requirement, but I have no idea what else to use.
I've seen something like this presented at WWDC 2011: a Core Animation "Bouncing Ball" demo, but I couldn't manage to implement it.
Please help me find a way to do this.
As I see it you have two options:
With Core Text, you can underline words and apply many other ornaments to them. Here's an example for underlining text:
//Create a font
CTFontRef sysUIFont = CTFontCreateUIFontForLanguage(kCTFontSystemFontType,
24.0, NULL);
//Create a string
NSString *aString = @"Random text";
//Choose the color
CGColorRef color = [UIColor blueColor].CGColor;
//Single underline
NSNumber *underline = [NSNumber numberWithInt:kCTUnderlineStyleSingle];
//Pack the attributes into a dictionary
NSDictionary *attributesDict = [NSDictionary dictionaryWithObjectsAndKeys:
(id)sysUIFont, (id)kCTFontAttributeName,
color, (id)kCTForegroundColorAttributeName,
underline, (id)kCTUnderlineStyleAttributeName, nil];
//Make the attributed string
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:string
attributes:attributesDict];
Now this works fine for underlining text, but I'm not sure how to animate the underline moving from word to word as the lyrics progress.
Now your second option is to create a custom underline class that subclasses UIView. This would be easy to animate. You don't even have to create a separate class for the underline (though I recommend it); you could just create a UIView and animate it moving from word to word with an animation like the following:
CABasicAnimation *underlineMove = [CABasicAnimation animationWithKeyPath:@"position"];
underlineMove.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
endPosition = CGPointMake((float)nextWord.x, (float)nextWord.y);
underlineMove.toValue = [NSValue valueWithCGPoint:endPosition];
underlineMove.duration = currentWord.duration;
[underlineView addAnimation:underlineMove forKey:@"animation"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With