iOS 文字轉(zhuǎn)語音+簡單音樂播放

初次看見有聲讀物感覺很神奇,就自己琢磨了一下,發(fā)現(xiàn)蘋果已經(jīng)給出了相關(guān)的接口。還是那句話,我們不是代碼的創(chuàng)造者,我們是代碼的搬運工。
避免多個播放器重復,建立單例,具體實現(xiàn)如下:

_synth = [[AVSpeechSynthesizer alloc] init];//創(chuàng)建AVSpeechSynthesizer
_voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];//漢語 -->默認不支持漢語
_utterance.rate = 0.5;//語速

附:語種

ar-SA Arabic Saudi Arabia
cs-CZ Czech Czech Republic
da-DK Danish Denmark
de-DE German Germany
el-GR Modern Greek Greece
en-AU English Australia
en-GB English United Kingdom
en-IE English Ireland
en-US English United States
en-ZA English South Africa
es-ES Spanish Spain
es-MX Spanish Mexico
fi-FI Finnish Finland
fr-CA French Canada
fr-FR French France
he-IL Hebrew Israel
hi-IN Hindi India
hu-HU Hungarian Hungary
id-ID Indonesian Indonesia
it-IT Italian Italy
ja-JP Japanese Japan
ko-KR Korean Republic of Korea
nl-BE Dutch Belgium
nl-NL Dutch Netherlands
no-NO Norwegian Norway
pl-PL Polish Poland
pt-BR Portuguese Brazil
pt-PT Portuguese Portugal
ro-RO Romanian Romania
ru-RU Russian Russian Federation
sk-SK Slovak Slovakia
sv-SE Swedish Sweden
th-TH Thai Thailand
tr-TR Turkish Turkey
zh-CN Chinese China
zh-HK Chinese Hong Kong
zh-TW Chinese Taiwan

文字轉(zhuǎn)語音

//通過傳遞的文字進行播放

-(void)playTextWithText:(NSString *)text
{
    [_synth stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];//停止播放
    _utterance = [AVSpeechUtterance speechUtteranceWithString:text];//播放語
    _utterance.voice = _voice;
    [_synth speakUtterance:_utterance];//播放
}

各種設(shè)置

>//開始播放
-(void)continuePlayText
{
    [_synth continueSpeaking];
}
//停止播放
-(void)stopPlayText
{
    [_synth stopSpeakingAtBoundary:AVSpeechBoundaryImmediate];//停止播放
}
//暫停播放
-(void)pausePlayText
{
    [_synth pauseSpeakingAtBoundary:AVSpeechBoundaryImmediate];//暫停播放
}

簡單音樂播放
>#pragma mark 通過音樂名稱和類型播放音樂
-(void)playMusicWithMusicName:(NSString *)musicName withwithExtension:(NSString *)ext
{
    // 獲取對應音樂資源
    NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:musicName withExtension:@"mp3"];
    if (fileUrl == nil) return;
    // 創(chuàng)建對應的播放器
    _player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:nil];
    // 準備播放
    [_player prepareToPlay];
    //播放音樂
    [_player play];
}

各種設(shè)置
>//開始播放
-(void)playMusic
{
    [_player play];
}
//停止播放
-(void)stopMusic
{
    [_player stop];
}
//暫停播放
-(void)pauseMusic
{
    [_player pause];
}

源碼下載地址:http://download.csdn.net/detail/qq_14827361/9889664
Github:https://github.com/HanWait/HanVideo/tree/master

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容