首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AVAudioPlayer不工作于iOS7

AVAudioPlayer不工作于iOS7
EN

Stack Overflow用户
提问于 2013-09-26 15:22:02
回答 2查看 6.2K关注 0票数 4

我已经尝试了这里找到的所有不同的选项,甚至使用NSData加载音频文件。我尝试过mp3、m4a、caf文件,但是都没有用。

没有错误信息什么都没有。

这是一个使用XCODE 5,iOS7的新应用程序。

这就是我要用的

代码语言:javascript
复制
- (void)playOnce:(NSString *)aSound
{


    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker error:nil];
    [audioSession setActive:YES error:nil];

    // Gets the file system path to the sound to play.
    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:aSound ofType:@"m4a"];

    // Converts the sound's file path to an NSURL object
    NSURL *soundURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
    AVAudioPlayer * newAudio=[[AVAudioPlayer alloc] initWithContentsOfURL: soundURL error:nil];


    [newAudio prepareToPlay];

    // set it up and play
    [newAudio setNumberOfLoops:0];
    [newAudio setVolume: 1];
    [newAudio setDelegate: self];
    [newAudio play];

}

任何帮助都是非常感谢的。我被这些东西缠住太久了。

提前,谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-09-27 04:15:05

您需要在视图控制器中将AVAudioPlayer声明为强引用的@属性,如下所示

代码语言:javascript
复制
@property (strong, nonatomic)  AVAudioPlayer * newAudio;

如果在方法中声明AVAudioPlayer,它将在该方法执行后立即释放,因此没有足够的时间发出声音。

票数 17
EN

Stack Overflow用户

发布于 2013-10-07 05:57:59

我试过这样做,我能够在iOS 7中播放音频文件

代码语言:javascript
复制
- (void)viewDidLoad {
  [super viewDidLoad];

  NSURL* url = [[NSBundle mainBundle] URLForResource:@"DR" withExtension:@"mp3"];
  NSAssert(url, @"URL is valid."); 
  NSError* error = nil;
  self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
  if(!self.player) {
    NSLog(@"Error creating player: %@", error);
  }
  self.player.delegate = self;
  [self.player prepareToPlay];
}

- (IBAction)playAction:(id)sender {
   [self.player play];
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19032254

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档