Text to Speech function when the application is in the background?

I am working on a TextToSpeech application. I write one paragraph in a UITextField , then click the Speak button. The sound is played in accordance with the text recorded in the UITextField .

enter image description here

However, when the application is in the background, the sound stops playing. How to continue playing sound in the background? Just like an audio player can play a song in the background.

I use the following code for text to speech:

 #import "ViewController.h" #import "Google_TTS_BySham.h" #import <AVFoundation/AVFoundation.h> @interface ViewController () @property (nonatomic,strong)Google_TTS_BySham *google_TTS_BySham; @property (nonatomic,strong)IBOutlet UITextField *txtString; @end @implementation ViewController #pragma mark - View Life Cycle - (void)viewDidLoad { [super viewDidLoad]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } #pragma mark - Button Tapped event - (IBAction)btnSpeakTapped:(id)sender{ NSString *str = [NSString stringWithFormat:@"%@",_txtString.text]; self.google_TTS_BySham = [[Google_TTS_BySham alloc] init]; [self.google_TTS_BySham speak:str]; } 
+4
source share
2 answers

Add the following code to info.plist ...

Application does not work in background: NO

Necessary background modes: the application plays audio or streams of audio / video using AirPlay

and then add the following code to the AppDelegate.m file

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. [[AVAudioSession sharedInstance] setDelegate:self]; [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; [[AVAudioSession sharedInstance] setActive:YES error:nil]; [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; UInt32 size = sizeof(CFStringRef); CFStringRef route; AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &size, &route); NSLog(@"route = %@", route); return YES; } - (void)remoteControlReceivedWithEvent:(UIEvent *)theEvent { if (theEvent.type == UIEventTypeRemoteControl) { switch(theEvent.subtype) { case UIEventSubtypeRemoteControlPlay: [[NSNotificationCenter defaultCenter] postNotificationName:@"TogglePlayPause" object:nil]; break; case UIEventSubtypeRemoteControlPause: [[NSNotificationCenter defaultCenter] postNotificationName:@"TogglePlayPause" object:nil]; break; case UIEventSubtypeRemoteControlStop: break; case UIEventSubtypeRemoteControlTogglePlayPause: [[NSNotificationCenter defaultCenter] postNotificationName:@"TogglePlayPause" object:nil]; break; default: return; } } } 
+5
source

Add “The application plays audio or audio / video streams using AirPlay” in the “Required background modes” section on your info.plist

Hope this helps ...

+1
source

Source: https://habr.com/ru/post/1275322/


All Articles