2013-09-26 33 views
4

我已经尝试了这里找到的所有不同的选项,甚至使用NSData来加载音频文件。我已经尝试过mp3,m4a,caf文件,但没有任何工作。AVAudioPlayer不能在iOS7上工作

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

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

这是我使用

- (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]; 

} 

任何帮助是极大的赞赏。我一直坚持这些太久了。

提前,谢谢。

+0

播放音频文件究竟是不工作怎么办?你说没有错误,那么问题是什么?你没有听到音频吗?你在使用模拟器还是设备? –

+0

实际上没有任何事情发生。没有声音,没有。无论是在模拟器和设备上。我用一个按钮来触发播放,按钮被禁用几秒钟,然后再次启用,但没有任何反应。没有任何声音。 – Elkucho

+0

我还添加了以下代码,但仍然没有任何内容... AVAudioSession * audioSession = [AVAudioSession sharedInstance]; [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil]; [audioSession setActive:YES error:nil]; – Elkucho

回答

17

您必须声明你AVAudioPlayer作为一个强有力的引用@property在视图控制器像下面

@property (strong, nonatomic) AVAudioPlayer * newAudio; 

如果您在方法声明AVAudioPlayer,将得到执行的方法后立即释放,没有有足够的时间发出声音。

+0

是的,你明白了。非常感谢。 – Elkucho

+0

这太酷了! –

2

我试过这样,我能够在iOS的7

- (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]; 
} 
+0

self.player与将其声明为强大的属性相同。 ARC要求范围超出这个方法,否则它会被分配 –

相关问题