应用处于后台模式时的文字转语音功能?

时间:2015-02-04 08:48:15

标签: ios objective-c text-to-speech background-mode

我正在使用TextToSpeech应用。我在UITextField中写了一段,然后按发言按钮。声音根据UITextField中的文字进行播放。

enter image description here

但是,当应用程序处于后台模式时,音频将停止播放。如何在后台模式下继续播放声音?类似于音频播放器如何在后台播放歌曲。

我使用以下代码进行文字转语音:

#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];
}

2 个答案:

答案 0 :(得分:5)

info.plist文件中添加以下代码...

应用程序无法在后台运行:否

所需的背景模式:App使用AirPlay播放音频或流音频/视频

然后在AppDelegate.m文件

中添加以下代码
- (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;
        }
    }
}

答案 1 :(得分:1)

在info.plist上的“所需背景模式”属性下添加“应用播放音频或使用AirPlay流音频/视频”

希望这会有所帮助......