標籤:objective-c ios iphone oc error
今天在做一個項目,因為要播放一個音頻,就選擇用 AVAudioPlayer來來做,因為以前用過,也沒有注意太多後來就直接寫,但是寫好之後運行看效果,怎麼也播放不出來,本來是因為本地音頻檔案有問題,後來重新找一個檔案然後在播放,還是出現同樣的問題.
用這段代碼,以前是正常的,現在就不可以了,(網上還有好多開發人員用該方式是沒有問題)
- (void)playRuningDistance:(TrainingPlayAudioType)playType{
NSString *playFileName = [NSStringstringWithFormat:@"distance%d",playType];
NSString *filepath = [[NSBundlemainBundle] pathForResource:playFileNameofType:@"mp3"];
BOOL fileexit = [[NSFileManagerdefaultManager] fileExistsAtPath:filepath];
NSLog(@"本地問價 %d",fileexit);
if (fileexit) {
if (self.playerMusic && [self.playerMusicisPlaying]) {
return;
}
NSError *error;
self.playerMusic =nil;
self.playerMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
[self.playerMusicprepareToPlay];
[self.playerMusicplay];
NSLog(@"error loading %@",error);
}
}
後來列印 error : Error Domain=NSOSStatusErrorDomain Code=-10875 "未能完成操作。(“OSStatus”錯誤 -10875。)"
後再在往常差有的說,需要加入以下代碼:
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
[session setActive:YES error:nil];
如果不添加會沒有聲音.但是加入了還是解決不了問題,
後來看官方文檔,說建議用 [[AVAudioPlayer alloc] initWithData:data error:&error]; 替代[[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:&error];
- (void)playRuningDistance:(TrainingPlayAudioType)playType{
NSString *playFileName = [NSStringstringWithFormat:@"distance%d",playType];
NSString *filepath = [[NSBundlemainBundle] pathForResource:playFileNameofType:@"mp3"];
BOOL fileexit = [[NSFileManagerdefaultManager] fileExistsAtPath:filepath];
NSLog(@"本地問價 %d",fileexit);
if (fileexit) {
if (self.playerMusic && [self.playerMusicisPlaying]) {
return;
}
NSError *error;
self.playerMusic =nil;
NSData *data = [[NSFileManagerdefaultManager] contentsAtPath:filepath];
self.playerMusic = [[AVAudioPlayeralloc] initWithData:dataerror:&error];
[self.playerMusicprepareToPlay];
[self.playerMusicplay];
NSLog(@"error loading %@",error);
}
}
結果使用問題解決,希望能協助你們,自己也留作問題解決.
AVAudioPlayer 的 Error Domain=NSOSStatusErrorDomain Code=-10875 "未能完成操作。(“OSStatus”錯誤 -10875。)"