2009-07-21 86 views
12

我在使用AVAudioPlayer時遇到了問題,我想重置播放器,如果它正在播放並再次播放它。AVAudioPlayer重置當前正在播放的聲音並從開始播放

我嘗試沒有運氣以下:

聲音播放一次,但然後我第二次選擇它停止聲音按鈕,第三次再次啓動的聲音響了起來。

//Stop the player and restart it 
if (player.playing) { 
    NSLog(@"Reset sound: %@", selectedSound); 
    [player stop]; 
    [player play]; 
} else { 
    NSLog(@"playSound: %@", selectedSound); 
    [player play];  
} 

我使用player.currentTime = 0,這表明會重置播放器,沒有工作也試過,我也嘗試重置currentTime的= 0,然後調用播放,沒有工作。

//Stop the player and restart it 
if (player.playing) { 
    NSLog(@"Reset sound: %@", selectedSound); 
    player.currentTime = 0; 
    [player play]; 
} else { 
    NSLog(@"playSound: %@", selectedSound); 
    [player play];  
} 

回答

33

對於你的情況我想嘗試以下

//Pause the player and restart it 
if (player.playing) { 
    NSLog(@"Reset sound: %@", selectedSound); 
    [player pause]; 
} 

player.currentTime = 0; 
[player play]; 

如果你要立即再次播放聲音,我會建議暫停而不是停止。調用停止「停止播放並撤消播放所需的設置。」

+6

FWIW,我已經看到了剛剛設置currentTime的零就足夠了。用這裏描述的方法,我看到音頻在連續幾次之後拒絕播放。 – Plumenator 2011-06-13 09:09:57

0

斯威夫特例如:

player.currentTime = 0.0;