今天在做一個項目,因爲要播放一個音頻,就選擇用 AVAudioPlayer來來做,因爲以前用過,也沒有注意太多後來就直接寫,但是寫好之後運行看效果,怎麼也播放不出來,本來是因爲本地音頻文件有問題,後來重新找一個文件然後在播放,還是出現同樣的問題.
用這段代碼,以前是正常的,現在就不可以了,(網上還有好多開發人員用該方式是沒有問題)
- (void)playRuningDistance:(TrainingPlayAudioType)playType{
NSString *playFileName = [NSString stringWithFormat:@"distance%d",playType];
NSString *filepath = [[NSBundle mainBundle] pathForResource:playFileName ofType:@"mp3"];
BOOL fileexit = [[NSFileManager defaultManager] fileExistsAtPath:filepath];
NSLog(@"本地問價 %d",fileexit);
if (fileexit) {
if (self.playerMusic && [self.playerMusic isPlaying]) {
return;
}
NSError *error;
self.playerMusic = nil;
self.playerMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
[self.playerMusic prepareToPlay];
[self.playerMusic play];
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 = [NSString stringWithFormat:@"distance%d",playType];
NSString *filepath = [[NSBundle mainBundle] pathForResource:playFileName ofType:@"mp3"];
BOOL fileexit = [[NSFileManager defaultManager] fileExistsAtPath:filepath];
NSLog(@"本地問價 %d",fileexit);
if (fileexit) {
if (self.playerMusic && [self.playerMusic isPlaying]) {
return;
}
NSError *error;
self.playerMusic = nil;
NSData *data = [[NSFileManager defaultManager] contentsAtPath:filepath];
self.playerMusic = [[AVAudioPlayer alloc] initWithData:data error:&error];
[self.playerMusic prepareToPlay];
[self.playerMusic play];
NSLog(@"error loading %@",error);
}
}
結果使用問題解決,希望能幫助你們,自己也留作問題解決.