如何在iOS 5中使用xcode播放随机声音? 我不断收到“抛出异常”错误。
我试过了:
int randomNumber = arc4random() % 24 + 1;
NSString *tmpFileNameRandom = [[NSString alloc] initWithFormat:@"Sound%d", randomNumber];
NSString *fileName = [[NSBundle mainBundle] pathForResource:tmpFileNameRandom ofType:@"mp3"];
AVAudioPlayer * soundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:fileName] error:nil];
[soundPlayer prepareToPlay];
[soundPlayer play];
谢谢!
答案 0 :(得分:3)
首先,将ViewController.h更改为
#import <UIKit/UIKit.h>
@class AVAudioPlayer;
@interface ViewController : UIViewController
-(IBAction)PlayRandomSound;
@property (nonatomic, retain) AVAudioPlayer *soundPlayer;
@end
和ViewController.m的第一行到
#import "ViewController.h"
#import <AVFoundation/AVAudioPlayer.h>
@implementation ViewController
@synthesize soundPlayer = _soundPlayer;
-(IBAction)PlayRandomSound{
int randomNumber = arc4random() % 8 + 1;
NSURL *soundURL = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:[NSString stringWithFormat:@"Sound%02d", randomNumber] ofType:@"mp3"]];
_soundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:nil];
[_soundPlayer prepareToPlay];
[_soundPlayer play];
NSLog(@"randomNumber is %d", randomNumber);
NSLog(@"tmpFilename is %@", soundURL);
}
编辑:我后来才注意到你没有使用ARC,所以这段代码有一个小漏洞。但它会起步。也许你应该在创建ViewController时将_soundPlayer设置为nil并稍后检查:如果它不是nil:释放它并创建新的,否则只需创建一个新的。或者,如果它是一个新项目,您可以考虑切换到ARC。
答案 1 :(得分:1)
对于您的文件名,您应该使用
NSString *tmpFileNameRandom = [[NSString alloc] initWithFormat:@"Sound%02d", randomNumber];
这将为您提供数字<0的前导零10 ...
或更好,试试这个:
int randomNumber = arc4random() % 24 + 1;
NSURL *soundURL = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:[NSString stringWithFormat:@"Sound%02d", randomNumber] ofType:@"mp3"]];
AVAudioPlayer * soundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:nil];
[soundPlayer prepareToPlay];
[soundPlayer play];
答案 2 :(得分:0)
您是否已将AVFoundation框架添加到项目中? AVAudioPlayer是这个框架的一个类。
要添加此框架(在Xcode 4中),请选择您的项目文件,选择“摘要”选项卡,然后通过单击“链接的框架和库”表视图下方的+来添加它。