iOS 5 - AVAPlayer 不再工作

发布于 2024-12-18 06:43:05 字数 4977 浏览 2 评论 0原文

我有一些在 iOS 4.3 上运行良好的代码。我上网查了一下,发现其他人也有同样的问题,但没有答案,这对我有用。我认为我可以录制一些东西,但无法播放它。这是我的代码:

DetailViewController.h

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <CoreAudio/CoreAudioTypes.h>
#import <AudioToolbox/AudioServices.h>

@interface DetailViewController : UIViewController <UISplitViewControllerDelegate, AVAudioRecorderDelegate> {

id detailItem;
UILabel *detailDescriptionLabel;

IBOutlet UIButton *btnStart;
IBOutlet UIButton *btnPlay;

//Variables setup for access in the class:
NSURL * recordedTmpFile;
AVAudioRecorder * recorder;
BOOL toggle;
}

// Needed properties
@property (nonatomic, retain) IBOutlet UIButton *btnStart;
@property (nonatomic, retain) IBOutlet UIButton *btnPlay;
@property (strong, nonatomic) id detailItem;
@property (strong, nonatomic) IBOutlet UILabel *detailDescriptionLabel;

-(IBAction) start_button_pressed;
-(IBAction) play_button_pressed;
@end

DetailViewController.m

- (void)viewDidLoad {
[super viewDidLoad];
toggle = YES;
btnPlay.hidden = YES;
NSError *error;

// Create the Audio Session
AVAudioSession *audioSession = [AVAudioSession sharedInstance];

// Set up the type of session
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];

// Activate the session.
[audioSession setActive:YES error:&error];

[self configureView];    
}

-(IBAction) start_button_pressed{
if (toggle) {
    toggle = NO;
    [btnStart setTitle:@"Press to stop recording" forState:UIControlStateNormal];
    btnPlay.enabled = toggle;
    btnPlay.hidden = !toggle;
            NSError *error;

    NSMutableDictionary *recordSettings = [[NSMutableDictionary alloc] init];

    [recordSettings setValue:[NSNumber numberWithInt:kAudioFormatAppleIMA4] forKey:AVFormatIDKey];

    [recordSettings setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];

    [recordSettings setValue:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];

    // Create a temporary files to save the recording. 
    recordedTmpFile = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat: @"%.0f.%@", [NSDate timeIntervalSinceReferenceDate] * 1000.0, @"caf"]]];

    NSLog(@"The temporary file used is: %@", recordedTmpFile);

    recorder = [[AVAudioRecorder alloc] initWithURL:recordedTmpFile settings:recordSettings error:&error];

    [recorder setDelegate:self];

    [recorder prepareToRecord];
    [recorder record];
}
else {
    toggle = YES;
    [btnStart setTitle:@"Start recording" forState:UIControlStateNormal];
    btnPlay.hidden = !toggle;
    btnPlay.enabled = toggle;

    NSLog(@"Recording stopped and saved in file: %@", recordedTmpFile);
    [recorder stop];
}
}

-(IBAction) play_button_pressed{

NSError *error;
AVAudioPlayer * avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:recordedTmpFile error:&error];

   if (!error)
   {
       [avPlayer prepareToPlay];
       [avPlayer play];

       NSLog(@"File is playing");
   }

}

- (void) audioPlayerDidFinishPlaying: (AVAudioPlayer *) player
                    successfully: (BOOL) flag {
     NSLog (@"audioPlayerDidFinishPlaying:successfully:");
}

- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *) aRecorder successfully: (BOOL)flag
{
    NSLog (@"audioRecorderDidFinishRecording:successfully:");
}

这是我的程序运行的代码:

2011-11-25 11:58:02.005 Bluetooth1[897:707] 使用的临时文件是:文件://localhost/private/var/mobile/Applications/D81023F8-C53D-4AC4-B1F7-14D66EB4844A/tmp/343915082005.caf 2011-11-25 11:58:05.956 Bluetooth1[897:707] 录制停止并保存在文件中: file://localhost/private/var/mobile/Applications/D81023F8-C53D-4AC4-B1F7-14D66EB4844A/tmp/343915082005 .caf 2011-11-25 11:58:05.998 蓝牙1[897:707]audioRecorderDidFinishRecording:成功: 2011-11-25 11:58:11.785 Bluetooth1[897:707] 文件正在播放

由于某种原因,函数audioPlayerDidFinishPlaying 从未被调用。不过,似乎有些事情已经被记录下来了。现在我不知道哪个部分不起作用,但我想这与 AVAudioPlayer 有关。

[编辑] 事情变得越来越奇怪了。我想确保记录了某些内容,因此我寻找记录的持续时间。这是新的播放功能:

-(IBAction) play_button_pressed{

    NSError *error;
AVAudioPlayer * avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: recordedTmpFile error:&error];

    if (!error)
    {
        AVURLAsset* audioAsset = [AVURLAsset URLAssetWithURL:recordedTmpFile options:nil];
        CMTime audioDuration = audioAsset.duration;
        float audioDurationSeconds = CMTimeGetSeconds(audioDuration);

        [avPlayer prepareToPlay];
        [avPlayer play];

        NSString *something = [NSString stringWithFormat:@"%f",audioDurationSeconds]; 
        NSLog(@"File is playing: %@", something);
    }
    else
    {
         NSLog(@"Error playing.");
    }   
}

现在,记录的长度被记录下来并且有意义(如果我记录 10 秒,它会显示大约 10 秒的内容)。然而,当我第一次输入这些代码行时,我忘记了将 float 转换为 NSString。所以它崩溃了...并且应用程序播放了声音...经过不同的测试,我可以得出结论,我的应用程序可以录制和播放声音,但会崩溃以播放录制的声音。我不知道会出现什么问题。我发现 AVPlayer 是异步的,这与他们有什么关系吗?我完全迷失了...

I've a bit of code which was working fine with iOS 4.3. I had a look on the Internet, I found others having the same problem without answer which worked for me. I think that I can record something but I cannot play it. Here is my code:

DetailViewController.h

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <CoreAudio/CoreAudioTypes.h>
#import <AudioToolbox/AudioServices.h>

@interface DetailViewController : UIViewController <UISplitViewControllerDelegate, AVAudioRecorderDelegate> {

id detailItem;
UILabel *detailDescriptionLabel;

IBOutlet UIButton *btnStart;
IBOutlet UIButton *btnPlay;

//Variables setup for access in the class:
NSURL * recordedTmpFile;
AVAudioRecorder * recorder;
BOOL toggle;
}

// Needed properties
@property (nonatomic, retain) IBOutlet UIButton *btnStart;
@property (nonatomic, retain) IBOutlet UIButton *btnPlay;
@property (strong, nonatomic) id detailItem;
@property (strong, nonatomic) IBOutlet UILabel *detailDescriptionLabel;

-(IBAction) start_button_pressed;
-(IBAction) play_button_pressed;
@end

DetailViewController.m

- (void)viewDidLoad {
[super viewDidLoad];
toggle = YES;
btnPlay.hidden = YES;
NSError *error;

// Create the Audio Session
AVAudioSession *audioSession = [AVAudioSession sharedInstance];

// Set up the type of session
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];

// Activate the session.
[audioSession setActive:YES error:&error];

[self configureView];    
}

-(IBAction) start_button_pressed{
if (toggle) {
    toggle = NO;
    [btnStart setTitle:@"Press to stop recording" forState:UIControlStateNormal];
    btnPlay.enabled = toggle;
    btnPlay.hidden = !toggle;
            NSError *error;

    NSMutableDictionary *recordSettings = [[NSMutableDictionary alloc] init];

    [recordSettings setValue:[NSNumber numberWithInt:kAudioFormatAppleIMA4] forKey:AVFormatIDKey];

    [recordSettings setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];

    [recordSettings setValue:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];

    // Create a temporary files to save the recording. 
    recordedTmpFile = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat: @"%.0f.%@", [NSDate timeIntervalSinceReferenceDate] * 1000.0, @"caf"]]];

    NSLog(@"The temporary file used is: %@", recordedTmpFile);

    recorder = [[AVAudioRecorder alloc] initWithURL:recordedTmpFile settings:recordSettings error:&error];

    [recorder setDelegate:self];

    [recorder prepareToRecord];
    [recorder record];
}
else {
    toggle = YES;
    [btnStart setTitle:@"Start recording" forState:UIControlStateNormal];
    btnPlay.hidden = !toggle;
    btnPlay.enabled = toggle;

    NSLog(@"Recording stopped and saved in file: %@", recordedTmpFile);
    [recorder stop];
}
}

-(IBAction) play_button_pressed{

NSError *error;
AVAudioPlayer * avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:recordedTmpFile error:&error];

   if (!error)
   {
       [avPlayer prepareToPlay];
       [avPlayer play];

       NSLog(@"File is playing");
   }

}

- (void) audioPlayerDidFinishPlaying: (AVAudioPlayer *) player
                    successfully: (BOOL) flag {
     NSLog (@"audioPlayerDidFinishPlaying:successfully:");
}

- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *) aRecorder successfully: (BOOL)flag
{
    NSLog (@"audioRecorderDidFinishRecording:successfully:");
}

Here is the of my program running:

2011-11-25 11:58:02.005 Bluetooth1[897:707] The temporary file used is: file://localhost/private/var/mobile/Applications/D81023F8-C53D-4AC4-B1F7-14D66EB4844A/tmp/343915082005.caf
2011-11-25 11:58:05.956 Bluetooth1[897:707] Recording stopped and saved in file: file://localhost/private/var/mobile/Applications/D81023F8-C53D-4AC4-B1F7-14D66EB4844A/tmp/343915082005.caf
2011-11-25 11:58:05.998 Bluetooth1[897:707] audioRecorderDidFinishRecording:successfully:
2011-11-25 11:58:11.785 Bluetooth1[897:707] File is playing

For some reason, the function audioPlayerDidFinishPlaying is never called. However it seems that something has been recorded. Right now I do not know which part is not working but I guess this has something to do with AVAudioPlayer.

[EDIT] It's getting weirder and weirder. I wanted to make sure that something was recorded so I look for taking the duration of the record. Here is the new play function:

-(IBAction) play_button_pressed{

    NSError *error;
AVAudioPlayer * avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: recordedTmpFile error:&error];

    if (!error)
    {
        AVURLAsset* audioAsset = [AVURLAsset URLAssetWithURL:recordedTmpFile options:nil];
        CMTime audioDuration = audioAsset.duration;
        float audioDurationSeconds = CMTimeGetSeconds(audioDuration);

        [avPlayer prepareToPlay];
        [avPlayer play];

        NSString *something = [NSString stringWithFormat:@"%f",audioDurationSeconds]; 
        NSLog(@"File is playing: %@", something);
    }
    else
    {
         NSLog(@"Error playing.");
    }   
}

Now, the length of the record is recorded and it make sense (if I record for 10s it shows something around 10s). However, when I put these lines of code for the first time I forgot to do the conversion float to NSString. So it crashed... and the app play the sound... After different tests I can conclude that my app can record and play a sound but is as to crash to play the recorded sound. I've no idea what can be the problem. I found that AVPlayer is asynchronous, is their something to do with that? I'm completely lost...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

檐上三寸雪 2024-12-25 06:43:05

将 urlpath 替换为以下代码:

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(
         NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filepath = [documentsDirectory stringByAppendingPathComponent:@"urfile.xxx"];

NSURL *url = [NSURL fileURLWithPath:filepath];

Replace the urlpath with the following code:

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(
         NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filepath = [documentsDirectory stringByAppendingPathComponent:@"urfile.xxx"];

NSURL *url = [NSURL fileURLWithPath:filepath];
初吻给了烟 2024-12-25 06:43:05

尝试此处的解决方案:

录音和播放

Try the solution here:

Recording and playback

§普罗旺斯的薰衣草 2024-12-25 06:43:05

好吧,回答你自己的问题并不是很酷。此外,当答案不干净但它正在工作时......为了播放我录制的内容,我使用了以下代码块:

    AVURLAsset* audioAsset = [AVURLAsset URLAssetWithURL:recordedTmpFile options:nil];
    CMTime audioDuration = audioAsset.duration;
    float audioDurationSeconds = CMTimeGetSeconds(audioDuration);

    [avPlayer prepareToPlay];
    [avPlayer play];

    // Block for audioDurationSeconds seconds
    [NSThread sleepForTimeInterval:audioDurationSeconds];

我正在计算录制文件的长度,并且我正在等待这段时间。 ..它很脏,但它正在发挥作用。另外,如果它在另一个线程中启动,它不会阻塞应用程序。

我任何人都有东西我很乐意接受!

OK, that is not really cool to answer you own questions. Moreover when the answer is not clean but it is working... In order to play what I have recorded I have used the following block of code:

    AVURLAsset* audioAsset = [AVURLAsset URLAssetWithURL:recordedTmpFile options:nil];
    CMTime audioDuration = audioAsset.duration;
    float audioDurationSeconds = CMTimeGetSeconds(audioDuration);

    [avPlayer prepareToPlay];
    [avPlayer play];

    // Block for audioDurationSeconds seconds
    [NSThread sleepForTimeInterval:audioDurationSeconds];

I am calculating the length of the recorded file and I am waiting for this amount of time... it is dirty but it is doing the trick. Plus, if it launched in another thread it will not block the application.

I anyone has something I would gladly take it!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文