我使用录音机在文档目录中录制并创建文件,然后使用音频播放器播放它。我可以在模拟器和设备上录制它,但无法仅在设备上播放。
请注意 1.我不从文件中播放声音,我从NSData中播放(我将音乐存储到数据库中,然后检索它们来播放) 2.在模拟器上运行正常,但在设备上失败。
这是我播放音频的代码
- (void)playAudioWithData:(NSData *)data {
[self stopPlayingAudio];
[self stopRecordingAudio];
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[audioSession setActive:YES error:nil];
self.audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:nil];
[self.audioPlayer play];
}
这是录制设置:
NSDictionary *audioSettings = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:44100],AVSampleRateKey,
[NSNumber numberWithInt: kAudioFormatLinearPCM],AVFormatIDKey,
[NSNumber numberWithInt: 1],AVNumberOfChannelsKey,
[NSNumber numberWithInt:AVAudioQualityMedium],AVEncoderAudioQualityKey,nil];
最佳答案
不要使用 AVAudioSessionCategoryPlayAndRecord
,而是尝试在录制时将 Audio Session 设置为 AVAudioSessionCategoryRecord
,然后在您想要播放刚刚播放的内容时将 Audio Session 设置为 AVAudioSessionCategoryPlayback
已记录。
在录制和播放音频时,我在应用程序中遇到了同样的情况,这解决了问题。
关于iOS 在模拟器上播放音频成功,但在设备上播放失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21950584/