objective-c - 播放随机声音
<p><p>如何在 xcode 中的 iOS 5 中播放随机声音?
我不断收到“抛出异常”错误。</p>
<p>我试过了:</p>
<pre><code>int randomNumber = arc4random() % 24 + 1;
NSString *tmpFileNameRandom = [ initWithFormat:@"Sound%d", randomNumber];
NSString *fileName = [ pathForResource:tmpFileNameRandom ofType:@"mp3"];
AVAudioPlayer * soundPlayer = [ initWithContentsOfURL: error:nil];
;
;
</code></pre>
<p>谢谢!</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>首先,将您的 ViewController.h 更改为</p>
<pre><code>#import <UIKit/UIKit.h>
@class AVAudioPlayer;
@interface ViewController : UIViewController
-(IBAction)PlayRandomSound;
@property (nonatomic, retain) AVAudioPlayer *soundPlayer;
@end
</code></pre>
<p>和 ViewController.m 的第一行到</p>
<pre><code>#import "ViewController.h"
#import <AVFoundation/AVAudioPlayer.h>
@implementation ViewController
@synthesize soundPlayer = _soundPlayer;
-(IBAction)PlayRandomSound{
int randomNumber = arc4random() % 8 + 1;
NSURL *soundURL = pathForResource: ofType:@"mp3"]];
_soundPlayer = [ initWithContentsOfURL:soundURL error:nil];
;
;
NSLog(@"randomNumber is %d", randomNumber);
NSLog(@"tmpFilename is %@", soundURL);
}
</code></pre>
<p>编辑:我后来才注意到你没有使用 ARC,所以这段代码有一点泄漏。但它会开始。也许你应该在创建 ViewController 时将 _soundPlayer 设置为 nil 并稍后检查:如果它不是 nil:释放它并创建一个新的,否则只创建一个新的。或者,如果是新项目,您可以考虑切换到 ARC。</p></p>
<p style="font-size: 20px;">关于objective-c - 播放随机声音,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/8975266/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/8975266/
</a>
</p>
页:
[1]