AVAudioPlayer 提供了大量的特性,包括暫停播放,調整音量,監控音頻的峰值和均值等等。
AVAudioPlayer *player; NSString *path; // 設置音樂文件路徑 path = [[NSBundle mainBundle] pathForResource:@"sound-file" ofType:@"mp3"]; // 判斷是否可以訪問這個文件 if ([[NSFileManager defaultManager] fileExistsAtPath:path]) { // 設置 player player = [[AVAudioPlayer alloc] initWithContentsOfURL: [NSURL fileURLWithPath:path] error:&error]; // 調節音量 (范圍從0到1) player.volume = 0.4f; // 准備buffer,減少播放延時的時間 [player prepareToPlay]; // 設置播放次數,0為播放一次,負數為循環播放 [player setNumberOfLoops:0]; [player play]; } ... // 清理工作 if (player != nil) { if (player.isPlaying == YES) [player stop]; [player release]; }