Is it possible to make “HTML to speech” same like “Text to speech”?

后端 未结 4 820
余生分开走
余生分开走 2021-02-12 14:13

I have one weird requirement that in my existing app I have Text2Speech and for that, I have used AVSpeechSynthesizer to speech text, but now my client

4条回答
  •  难免孤独
    2021-02-12 15:03

    As I have worked with HTML parsing and text2speech here you can go with 2 steps 1.get Attribute string from HTML file with below code works in iOS7+

    As per your client perspective : if there is any API in market for HTML2Speech may be its Paid or you are depended on that API if you use any. While Native framework will help same what you/client wants.

    Step 1:

    [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding] 
                                     options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                               NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)} 
                          documentAttributes:nil error:nil];
    

    Then you can pass this Attributed String in AVSpeechUtterance

    Step 2: use below method to get HTML2String:

    /**
     *  "ConvertHTMLtoStrAndPlay" : This method will convert the HTML to String 
     synthesizer.
     *
     *  @param aURLHtmlFilePath : "object of html file path"
     */
    -(void)ConvertHTMLtoStrAndPlay:(UIButton*)aBtnPlayPause
                    isSpeechPaused:(BOOL)speechPaused
          stringWithHTMLAttributes:(NSAttributedString*)aStrWithHTMLAttributes
    {
    
        if (synthesizer.speaking == NO && speechPaused == NO) {
    
            AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:aStrWithHTMLAttributes.string];
            //utterance.rate = AVSpeechUtteranceMinimumSpeechRate;
    
            if (IS_ARABIC) {
                utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"ar-au"];
            }else{
                utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"en-au"];
            }
    
            [synthesizer speakUtterance:utterance];
        }
        else{
            [synthesizer pauseSpeakingAtBoundary:AVSpeechBoundaryImmediate];
        }
    
        if (speechPaused == NO) {
            [synthesizer continueSpeaking];
        } else {
            [synthesizer pauseSpeakingAtBoundary:AVSpeechBoundaryImmediate];
        }
    
    }
    

    and as usual while you need to stop use below code to stop Speech.

    /**
     *  "StopPlayWithAVSpeechSynthesizer" : this method will stop the playing of audio on the application.
     */
    -(void)StopPlayWithAVSpeechSynthesizer{
    
        // Do any additional setup after loading the view, typically from a nib.
        [synthesizer stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];
    }
    

    Hope This will help you to get HTML2Speech feature.

提交回复
热议问题