2013-09-26 45 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要求範圍超出這個方法,否則它會被分配 –

相關問題