OGeek|极客世界-中国程序员成长平台

标题: objective-c - 播放随机声音 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 19:02
标题: objective-c - 播放随机声音

如何在 xcode 中的 iOS 5 中播放随机声音? 我不断收到“抛出异常”错误。

我试过了:

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

谢谢!



Best Answer-推荐答案


首先,将您的 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。

关于objective-c - 播放随机声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8975266/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4