2012-05-19 74 views
2

我想播放從我的服務器檢索到的聲音文件,作爲基本64編碼文件。使用AVAudioPlayer從NSData播放聲音iOS

到目前爲止,我使用Base64已解碼的文件,並將其寫入到一個文件像這樣:

NSFileManager *fileManager = [NSFileManager defaultManager];    
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);    
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"voicemail.wav"]]; 
[fileManager createFileAtPath:filepath contents:[responseDict objectForKey:@"ResponseData"] attributes:nil]; 

但是,我無法實際播放聲音文件。我的代碼返回錯誤:

The operation couldn't be completed. OSStatus error 2003334207.

請你能告訴我我哪裏出錯了嗎?

NSURL * url = [NSURL fileURLWithPath:filePath]; 
AVAudioPlayer *sound = [[[AVAudioPlayer alloc] initWithContentsOfURL:url error:&err] autorelease]; 
if (! sound) { 
    NSLog(@"Sound had error %@", [err localizedDescription]); 
} else { 
    [sound prepareToPlay]; 
    [sound play]; 
} 
+0

我會在模擬器中運行這一點,看看voicemail.wav多的肯定它確實是一個正確的wav文件,使用'文件voicemail.wav'並在iTunes等方面發揮它還要確保您將AVAudioPlayer實例指定爲一個strong/retain屬性,就像您當前的示例代碼一樣,即使在開始播放聲音之前它可能會(自動)發佈。 –

+0

感謝Mattias,問題出在wav文件中,並且能夠解決它。感謝您的展示方式。 – SST

+0

不錯。任何與使用iOS API或其他人的東西有關的錯誤都可能遇到?那麼我認爲你應該用調查結果回答你自己的問題,以及你如何解決問題。 –

回答

1

@Himanshu

至於建議由馬蒂亞斯·瓦德曼,我嘗試使用VLC/iTunes的媒體播放器播放下載的文件,該文件是不是在玩。 所以問題可能出在編碼或解碼文件,而不是播放音頻代碼。我檢查了一下,編碼時嵌入了一些額外的字符。 我們致力於編碼並解決了問題。

希望這會有所幫助。

+0

你在使用編碼來解決這個問題時究竟做了什麼,請你詳細說明我在播放從服務器獲取的音頻文件作爲NSData時面臨同樣的問題。 – iShwar

0
NSData *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"FileName.mp3"] 
    NSURL *url = [[NSURL alloc] initFileURLWithPath: path]; 
    AVAudioPlayer *sound = [[[AVAudioPlayer alloc] initWithContentsOfURL:url error:&err] autorelease]; 
     if (! sound) { 
     NSLog(@"Sound had error %@", [err localizedDescription]); 
     } else { 
     [sound prepareToPlay]; 
     [sound play]; 
     }